incompatible data type in conversion: from SQL type VARCHAR to java.lang.Long - spring

ERROR [hybrisHTTP15] [FlexibleSearch] Flexible search error occured...
Aug 16, 2022 5:37:53 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [DispatcherServlet] in context with path [/trainingstorefront] threw exception [Request processing failed; nested exception is de.hybris.platform.servicelayer.search.exceptions.FlexibleSearchException: SQL search error - enable the property 'flexible.search.exception.show.query.details' for more details] with root cause
org.hsqldb.HsqlException: incompatible data type in conversion: from SQL type VARCHAR to java.lang.Long, value: customer10
at org.hsqldb.error.Error.error(Unknown Source)
In my SAP Hybris flow, I'm hitting the url from the Controller. While the data is being retrieved from the DB, I am getting the above mentioned error.
P.S.: the customer name "customer10" is being loaded correctly but facing this issue. The code to retrieve data from DB is attached below:
#Override
public List<NewCustomerModel> getCustomerNameFromID() {
final StringBuilder query=new StringBuilder();
query.append("SELECT {" + NewCustomerModel.NAME + "} FROM {" + NewCustomerModel._TYPECODE + "} WHERE { "+ NewCustomerModel.CUSTID + "}=1");
final FlexibleSearchQuery flexQuery = new FlexibleSearchQuery(query);
final SearchResult<NewCustomerModel> searchResult = flexibleSearchService.search(flexQuery);
if (CollectionUtils.isNotEmpty(searchResult.getResult()))
{
return searchResult.getResult();
}
return Collections.EMPTY_LIST;
}
Please let me know if there is any error in the query or is there any configuration issue?

Related

MSAL4J with Extensions error: com.microsoft.aad.msal4jextensions.CrossProcessCacheFileLock - null

I try to authenticate to Azure AD throught MSAL4J Java library (https://github.com/AzureAD/microsoft-authentication-library-for-java) with extention (https://github.com/AzureAD/microsoft-authentication-extensions-for-java) for cross platform cache serialization.
I am using the "Desktop app that calls web APIs: Acquire a token interactively" flow (https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-desktop-acquire-token-interactive?tabs=dotnet)
Here is my code:
private static IAuthenticationResult acquireTokenInteractive(final boolean onlyFromCache) throws Exception {
scopeSet.add(API_SCOPE);
final PersistenceTokenCacheAccessAspect perSettings = new PersistenceTokenCacheAccessAspect(createPersistenceSettings());
pca = PublicClientApplication.builder(CLIENT_ID).authority(AUTHORITY).setTokenCacheAccessAspect(perSettings).build();
final Set<IAccount> accountsInCache = pca.getAccounts().join();
IAuthenticationResult result;
try {
// Take first account in the cache. In a production application, you would filter
// accountsInCache to get the right account for the user authenticating.
final IAccount account = accountsInCache.iterator().next();
final SilentParameters silentParameters = SilentParameters.builder(scopeSet, account).build();
// try to acquire token silently. This call will fail since the token cache
// does not have any data for the user you are trying to acquire a token for
result = pca.acquireTokenSilently(silentParameters).join();
} catch (final Exception ex) {
if ((ex.getCause() instanceof MsalException) || (ex instanceof NoSuchElementException)) {
if (!onlyFromCache) {
final InteractiveRequestParameters parameters = InteractiveRequestParameters.builder(new URI("http://localhost"))
.scopes(scopeSet).build();
// Try to acquire a token interactively with system browser. If successful, you should see
// the token and account information printed out to console
result = pca.acquireToken(parameters).join();
} else {
return null;
}
} else {
// Handle other exceptions accordingly
throw ex;
}
}
return result;
}
I get an error while accessing cache:
[ForkJoinPool.commonPool-worker-19] ERROR com.microsoft.aad.msal4jextensions.CrossProcessCacheFileLock - null
and when I try to acquire token, an exception is thrown after a valid login in the browser (Firefox) :
java.util.concurrent.CompletionException:
java.lang.AbstractMethodError: Receiver class
com.sun.jna.platform.win32.WinCrypt$DATA_BLOB does not define or
inherit an implementation of the resolved method 'abstract
java.util.List getFieldOrder()' of abstract class
com.sun.jna.Structure. at
java.base/java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:314)
at
java.base/java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:319)
at
java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1702)
at
java.base/java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1692)
at
java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
at
java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
at
java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
at
java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
at
java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177)
Caused by: java.lang.AbstractMethodError: Receiver class
com.sun.jna.platform.win32.WinCrypt$DATA_BLOB does not define or
inherit an implementation of the resolved method 'abstract
java.util.List getFieldOrder()' of abstract class
com.sun.jna.Structure. at
com.sun.jna.Structure.fieldOrder(Structure.java:952) at
com.sun.jna.Structure.getFields(Structure.java:1006) at
com.sun.jna.Structure.deriveLayout(Structure.java:1172) at
com.sun.jna.Structure.calculateSize(Structure.java:1097) at
com.sun.jna.Structure.calculateSize(Structure.java:1049) at
com.sun.jna.Structure.allocateMemory(Structure.java:403) at
com.sun.jna.Structure.(Structure.java:194) at
com.sun.jna.Structure.(Structure.java:182) at
com.sun.jna.Structure.(Structure.java:169) at
com.sun.jna.Structure.(Structure.java:161) at
com.sun.jna.platform.win32.WinCrypt$DATA_BLOB.(WinCrypt.java:74)
at
com.sun.jna.platform.win32.Crypt32Util.cryptProtectData(Crypt32Util.java:80)
at
com.sun.jna.platform.win32.Crypt32Util.cryptProtectData(Crypt32Util.java:60)
at
com.sun.jna.platform.win32.Crypt32Util.cryptProtectData(Crypt32Util.java:47)
at
com.microsoft.aad.msal4jextensions.persistence.CacheFileAccessor.write(CacheFileAccessor.java:56)
at
com.microsoft.aad.msal4jextensions.PersistenceTokenCacheAccessAspect.afterCacheAccess(PersistenceTokenCacheAccessAspect.java:144)
at
com.microsoft.aad.msal4j.TokenCache$CacheAspect.close(TokenCache.java:171)
at com.microsoft.aad.msal4j.TokenCache.saveTokens(TokenCache.java:218)
at
com.microsoft.aad.msal4j.AbstractClientApplicationBase.acquireTokenCommon(AbstractClientApplicationBase.java:131)
at
com.microsoft.aad.msal4j.AcquireTokenByAuthorizationGrantSupplier.execute(AcquireTokenByAuthorizationGrantSupplier.java:63)
at
com.microsoft.aad.msal4j.AcquireTokenByInteractiveFlowSupplier.acquireTokenWithAuthorizationCode(AcquireTokenByInteractiveFlowSupplier.java:193)
at
com.microsoft.aad.msal4j.AcquireTokenByInteractiveFlowSupplier.execute(AcquireTokenByInteractiveFlowSupplier.java:39)
at
com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:71)
at
com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:20)
at
java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700)
... 6 more
What am I doing wrong ?
Thanks by advance !

Null values inside #PreAuthorize giving error

I'm trying to check if the user has role "ADMIN" and if he is the project's creator before giving him access to change the project like this:
#PreAuthorize("hasRole('ROLE_ADMIN') and this.projectService.findById(#id).getAdmin().getUsername() == authentication.name")
#RequestMapping(value = "/projects/{id}", method = RequestMethod.PUT)
public ResponseEntity<?> doUpdateProject(#PathVariable("id") Long id, #RequestBody ProjectDto project)
throws InstanceNotFoundException, DuplicatedResourceException {
Project updatedProject = projectService.update(id, project.getName(), project.getDescription());
return ResponseEntity.ok(updatedProject);
}
This works, only allowing an admin to update the project if he is the owner. But I noticed that if I make the call to a non-existent project, I get a 500 Internal Server Error instead of a 404 Not Found:
Servlet.service() for servlet [dispatcherServlet] in context with path [/tasks-service] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: Failed to evaluate expression 'hasRole('ROLE_ADMIN') and this.projectService.findById(#id).getAdmin().getUsername() == authentication.name'] with root cause.
I think that it is because of pointing to a null value (projectService.findById(#id)) but even when checking if the value is null, using for example a ternary operator that returns "true" if the value is null, I keep getting the same error.
#PreAuthorize("hasRole('ROLE_ADMIN') and this.projectService.findById(#id) != null ? this.projectService.findById(#id)?.getAdmin().getUsername() == authentication.name : true")
My idea here is to "pass" the #PreAuthorize condition when the project ID specified does not exist in order to get a 404 error later, but the same internal error is happening.
What should I do to get a 404 Not Found in this case?

How to improve error responses when using #RepositoryRestResource

I'm using spring's #RepositoryRestResource annotation on a PagingAndSortingRepository.
When I send an erroneous payload to the corresponding endpoint, the error responses that are sent back are hard to parse, e.g.
{
"cause": {
"cause": {
"cause": null,
"message": "ERROR: duplicate key value violates unique constraint \"uk_bawli8xm92f30ei6x9p3h8eju\"\n Detail: Key (email)=(jhunstone0#netlog.com) already exists."
},
"message": "could not execute statement"
},
"message": "could not execute statement; SQL [n/a]; constraint [uk_bawli8xm92f30ei6x9p3h8eju]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"
}
Is there any way to configure the messages, so it is clear which field (here: email) caused the error?
Regarding the error handling - you can implement a custom exception handler for such exceptions, extract the constraint name from the root cause, analyze it and create a corresponding message for the user.
Some error handling examples: 1, 2.
UPDATED
You should check the app log to determine which exception you have to handle. If I'm not mistaken for constraint violation we must handle org.springframework.dao.DataIntegrityViolationException, for example:
#ControllerAdvice
public class CommonExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(DataIntegrityViolationException.class)
ResponseEntity<?> handleDataIntegrityViolation(DataIntegrityViolationException ex, HttpServletRequest req) {
String causeMessage = NestedExceptionUtils.getMostSpecificCause(ex).getMessage(); // determine the root cause message
String reqPath = req.getServletPath(); // get the request path
String userMessage = ... // Decide what the message you will show to users
HttpStatus status = HttpStatus... // Decide what the status your response will be have, for example HttpStatus.CONFLICT
ApiErrorMessage message = new ApiErrorMessage(userMessage, status, reqPath); // Create your custom error message
return new ResponseEntity<>(message, status); // return response to users
}
// other handlers
}
Or you can implement this handler easier as in the official example.

Webapi depedency injection

Hej,
I am working on asp.net Webapi. When I try to inject value in my repository constructor so It throws an Exception.
Resolution of the dependency failed,
type = "Controllers.XXXXX", name = "(none)"
. Exception occurred while: while resolving. Exception is:
InvalidOperationException - The current type, IRepository, is an interface and cannot be constructed. Are you missing a type mapping? -----------------------------------------------
I am doing registration like that
string modelMapperName = Guid.NewGuid().ToString();
container.RegisterType<IBulkCopy, BulkCopy>("bulkCopy", new InjectionConstructor("dbo", "test"));
container.RegisterType<IMapConfigurator, ProductMap>(modelMapperName, new ContainerControlledLifetimeManager());
container.RegisterType<IModelMapper, ModelAutoMapper>(modelMapperName,
new ContainerControlledLifetimeManager(), new InjectionConstructor(new ResolvedParameter<IMapConfigurator>(modelMapperName)));
container.RegisterType<IProductRepository, EProductRepository>("productRepository", new PerResolveLifetimeManager(),
new InjectionConstructor(
new ResolvedParameter<IRepositoryFactory>(DatabaseConnection.XXXX)
, new ResolvedParameter<IModelMapper>(modelMapperName),
new ResolvedParameter<IBulkCopy>("bulkCopy")));
When I remove ResolvedParamater from the IProductRepository mappings so it works fine. Could anybody help me to identify this problems.
Thanks in advance

Hive Server 2 thrift Client error: Required field 'operationHandle' is unset

I am trying to run the below hive thrift code on hive server2 on CDH 4.3 and getting below error. Here is my code: I can run hive jdbc connection to same server successfully, it is just thrift which is not working.
public static void main(String[] args) throws Exception
{
TSocket transport = new TSocket("my.org.hiveserver2.com",10000);
transport.setTimeout(999999999);
TBinaryProtocol protocol = new TBinaryProtocol(transport);
TCLIService.Client client = new TCLIService.Client(protocol);
transport.open();
TOpenSessionReq openReq = new TOpenSessionReq();
TOpenSessionResp openResp = client.OpenSession(openReq);
TSessionHandle sessHandle = openResp.getSessionHandle();
TExecuteStatementReq execReq = new TExecuteStatementReq(sessHandle, "SELECT * FROM testhivedrivertable");
TExecuteStatementResp execResp = client.ExecuteStatement(execReq);
TOperationHandle stmtHandle = execResp.getOperationHandle();
TFetchResultsReq fetchReq = new TFetchResultsReq(stmtHandle, TFetchOrientation.FETCH_FIRST, 1);
TFetchResultsResp resultsResp = client.FetchResults(fetchReq);
TRowSet resultsSet = resultsResp.getResults();
List<TRow> resultRows = resultsSet.getRows();
for(TRow resultRow : resultRows){
resultRow.toString();
}
TCloseOperationReq closeReq = new TCloseOperationReq();
closeReq.setOperationHandle(stmtHandle);
client.CloseOperation(closeReq);
TCloseSessionReq closeConnectionReq = new TCloseSessionReq(sessHandle);
client.CloseSession(closeConnectionReq);
transport.close();
}
Here is the error log:
Exception in thread "main" org.apache.thrift.protocol.TProtocolException: Required field 'operationHandle' is unset! Struct:TFetchResultsReq(operationHandle:null, orientation:FETCH_FIRST, maxRows:1)
at org.apache.hive.service.cli.thrift.TFetchResultsReq.validate(TFetchResultsReq.java:465)
at org.apache.hive.service.cli.thrift.TCLIService$FetchResults_args.validate(TCLIService.java:12607)
at org.apache.hive.service.cli.thrift.TCLIService$FetchResults_args$FetchResults_argsStandardScheme.write(TCLIService.java:12664)
at org.apache.hive.service.cli.thrift.TCLIService$FetchResults_args$FetchResults_argsStandardScheme.write(TCLIService.java:12633)
at org.apache.hive.service.cli.thrift.TCLIService$FetchResults_args.write(TCLIService.java:12584)
at org.apache.thrift.TServiceClient.sendBase(TServiceClient.java:63)
at org.apache.hive.service.cli.thrift.TCLIService$Client.send_FetchResults(TCLIService.java:487)
at org.apache.hive.service.cli.thrift.TCLIService$Client.FetchResults(TCLIService.java:479)
at HiveJDBCServer1.main(HiveJDBCServer1.java:26)
Are you really sure you set the operationsHandle field to a valid value? The Thrift eror indicates what it says: The API expects a certain field (operationHandle in your case) to be set, which has not been assigned a value. And you stack trace confirms this:
Struct:TFetchResultsReq(operationHandle:null, orientation:FETCH_FIRST,
maxRows:1)
In case anyone finds this, like I did, by googling that error message: I had a similar problem with a PHP Thrift library for hiverserver2. At least in my case, execResp.getOperationHandle() returned NULL because there was an error in the executed request that generated execResp. This didn't throw an exception for some reason, and I had to examine execResp in detail, and specifically check the status, before attempting to get an operation handle.

Resources