Why Boolean is not accepting null value? - boolean

public Map<String, BigDecimal> getData(Set<String> ids, Boolean flag) {
Map<String, BigDecimal> data = new HashMap<>();
if(flag == null){
try {
data = *code logic*
} catch (RuntimeException e) {
log.error("Error occurred while fetching data : {}", e.getMessage());
}
}
else{
try {
data = *code logic*;
} catch (RuntimeException e) {
log.error("Error occurred while fetching data : {}", e.getMessage());
}
}
return data;
Whenever the value of flag is passed as null I am getting this error :
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Boolean'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [null]
Why is this happening? Isn't the wrapper class Boolean supposed to hold values true, false and null?

Related

hadoop-connectors/gcsio - no message in exception

GoogleCloudStorageExceptions.java
It looks like HttpResponseException is created without message.
public static GoogleJsonResponseException createJsonResponseException(
GoogleJsonError e, HttpHeaders responseHeaders) {
if (e != null) {
// ISSUE: HttpResponseException.Builder() constructor below doesn't set HttpResponseException.Builder.message.
// HttpResponseException.Builder.message is passed to Throwable.detailMessage that is printed in Throwable.toString().
// As a result, received from server exception doesn't print any information, it prints: null.
return new GoogleJsonResponseException(
new HttpResponseException.Builder(e.getCode(), e.getMessage(), responseHeaders), e);
}
return null;
}

Postgres JDBC fetchSize() ignored

Why I'm having the fetch size ignored, I set it to 2, but whenever I run the program it returns whole records! If I print the fetch size will print 2, but the result will return whole records. Any implementation that I can return rows according to the fetch size? i.e I have 10 records in my DB I need to return 2 records for each trip in my tableAsStream method?
private Stream<SecurityGroup> tableAsStream(Context context, Connection connection) throws SQLException {
try {
connection.setAutoCommit(false);
Statement statement = connection.createStatement();
statement.setFetchSize(FETCH_SIZE);
ResultSet resultSet = statement.executeQuery(SELECT_SCHEDULE_MODULES_QUERY);
log.info("Returning a stream of SecurityGroups from the prepared statement ");
return StreamSupport.stream(new Spliterators.AbstractSpliterator<SecurityGroup>(Long.MAX_VALUE, Spliterator.ORDERED) {
#Override
public boolean tryAdvance(Consumer<? super SecurityGroup> action) {
try {
if(!resultSet.next()) return false;
action.accept(createRecord(resultSet));
return true;
} catch(SQLException ex) {
throw new RuntimeException(ex);
}
}
}, false);
} catch(SQLException sqlEx) {
throw sqlEx;
}
}
public void migrate(Context context) throws Exception {
Connection connection = context.getConnection();
// do{
log.info("Migration script started for (SCHEDULE_SHIFTS_EDIT_SELF).");
List<SecurityGroup> securityGroupList = tableAsStream(context, connection).collect(Collectors.toList());
securityGroupList.stream()
.flatMap(securityGroup -> securityGroup.getModules().stream())
.filter(securityModule -> securityModule.getName() == ModuleName.SCHEDULE)
.forEach(filteredSecurityModule -> {
boolean editPermissionExists = filteredSecurityModule.getFeatures().stream()
.anyMatch(x->PermissionName.SCHEDULE_SHIFTS_EDIT == x.getName());
boolean editSelfPermissionExists = filteredSecurityModule.getFeatures().stream()
.anyMatch(x->PermissionName.SCHEDULE_SHIFTS_EDIT_SELF == x.getName());
if (editPermissionExists && !editSelfPermissionExists) {
filteredSecurityModule.getFeatures().add(SecurityFeature.of(PermissionName.SCHEDULE_SHIFTS_EDIT_SELF, true, false));
}
});
updateSecurityGroups(securityGroupList, context);
log.info("Migration script Ended for (SCHEDULE_SHIFTS_EDIT_SELF).");
// } while(condition);
}

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null

I have written following code in my application:
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
public static final String JDBC_URL = "jdbc:derby:c:/coopcashier/db/COOP;create=true";
try {
Class.forName(DRIVER);
Connection conn = DriverManager.getConnection(JDBC_URL);
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery("select * from USERS");
while(resultset.next()) {
if(resultset.getString(4).toString().equals(txtUsername) && resultset.getString(5).toString().equals(txtPassword)) {
homePage home = new homePage();
setVisible(false);
home.setVisible(true);
}
else {
JOptionPane.showMessageDialog(null,"Invalid Username or Password.","Invalid Credentials",JOptionPane.ERROR_MESSAGE);
}
}
if(conn != null) conn.close();
if(statement != null) statement.close();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e2) {
e2.printStackTrace();
}
When I am running this in Eclipse, everything goes well. But when I made the jar file of my project with same code and try to run, it always throw following exception:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null
I could not find solution. Please share if anybody resolved this problem.
TIA

Can we throw an exception in fallback or fallbackFactory of #FeignClient

I'm use the #FeignClient and want to do some logic(like record the exception information) when Feign throw Exception and then reply the result to front end.
I noticed Feign will throw FeignException when connection fail or http status not expect.
So I defined a #ExceptionHandler to caught FeignException after the callback method was invoked.
#ExceptionHandler(value = FeignException.class)
#ResponseBody
public ResponseResult feignException(FeignException exception){
String message = exception.getMessage();
byte[] content = exception.content();
int status = exception.status();
if(content!=null){
String response=new String(content);
message=String.format("%s response message : %s",message,response);
}
log.warn("{} : {} , cause by : {}",exception.getClass().getSimpleName(),message,exception.getCause());
return ResponseResult.fail(HttpStatus.valueOf(status),String.format("9%s00",status),message);
But it can't caught when I set the callback or callbackFactory of #FeignClient.
#FeignClient(url = "${onboardingcase.uri}",name = "OnBoardingCaseService",
fallbackFactory = OnBoardingCaseServiceFallBack.class)
#Component
#Slf4j
public class OnBoardingCaseServiceFallBack implements FallbackFactory<OnBoardingCaseService> {
#Override
public OnBoardingCaseService create(Throwable throwable) {
return new OnBoardingCaseService() {
#Override
public OnBoardingCaseVo query(String coid) {
if(throwable instanceof FeignException){
throw (FeignException)throwable;
}
return null;
}
};
}
}
I noticed because hystrix took over this method.And will catch exception in HystrixInvocationHandler.
try {
Object fallback = HystrixInvocationHandler.this.fallbackFactory.create(this.getExecutionException());
Object result = ((Method)HystrixInvocationHandler.this.fallbackMethodMap.get(method)).invoke(fallback, args);
if (HystrixInvocationHandler.this.isReturnsHystrixCommand(method)) {
return ((HystrixCommand)result).execute();
} else if (HystrixInvocationHandler.this.isReturnsObservable(method)) {
return ((Observable)result).toBlocking().first();
} else if (HystrixInvocationHandler.this.isReturnsSingle(method)) {
return ((Single)result).toObservable().toBlocking().first();
} else if (HystrixInvocationHandler.this.isReturnsCompletable(method)) {
((Completable)result).await();
return null;
} else {
return HystrixInvocationHandler.this.isReturnsCompletableFuture(method) ? ((Future)result).get() : result;
}
} catch (IllegalAccessException var3) {
throw new AssertionError(var3);
} catch (ExecutionException | InvocationTargetException var4) {
throw new AssertionError(var4.getCause());
} catch (InterruptedException var5) {
Thread.currentThread().interrupt();
throw new AssertionError(var5.getCause());
}
So I want to know how can I throw an exception when I using callback / callbackFactory or there is another way to instead callbackFactory to do the "call back"?
Many Thanks
I found a solution to this problem.
public class OnBoardingCaseServiceFallBack implements FallbackFactory<OnBoardingCaseService> {
#Override
public OnBoardingCaseService create(Throwable throwable) {
return new OnBoardingCaseService() {
#Override
public OnBoardingCaseVo query(String coid) {
log.error("OnBoardingCaseService#query fallback , exception",throwable);
if(throwable instanceof FeignException){
throw (FeignException)throwable;
}
return null;
}
};
}
}
And then caught the HystrixRuntimeException and get the cause of exception in ExceptionHandler for get the realException that was wrapped by Hystrix.
#ExceptionHandler(value = HystrixRuntimeException.class)
#ResponseBody
public ResponseResult hystrixRuntimeException(HystrixRuntimeException exception){
Throwable fallbackException = exception.getFallbackException();
Throwable assertError = fallbackException.getCause();
Throwable realException = assertError.getCause();
if(realException instanceof FeignException){
FeignException feignException= (FeignException) realException;
String message = feignException.getMessage();
byte[] content = feignException.content();
int status = feignException.status();
if(content!=null){
String response=new String(content);
message=String.format("%s response message : %s",message,response);
}
return ResponseResult.fail(HttpStatus.valueOf(status),String.format("9%s00",status),message);
}
String message = exception.getMessage();
log.warn("{} : {} , cause by : {}",exception.getClass().getSimpleName(),message,exception.getCause());
return ResponseResult.fail(ResultCode.FAIL.httpStatus(),ResultCode.FAIL.code(),message);
}
But I don't think that's a good way~
I have never done this in fallback, I have implemented custom error decoder(“CustomFeignErrorDecoder”) class and extended feign.codec.ErrorDecoder, every time an error occurs it comes to this class.
In decode function throw a custom exception and catch it in the controller or service layer to show your message to the frontend.
Example:
#Component
public class CustomFeignErrorDecoder implements ErrorDecoder {
#Override
public Exception decode(String methodKey, Response response) {
throw new CustomFeignErrorDecoderException(methodKey +" response status "+ response.status() +" request "+ response.request()+ " method "+ response.request().httpMethod());
}
}

Problem in getting attributes from webservice to servlet when the return type of operation in webservice is STRING []

I made a Webservice Operation whose return type is STRING []
Following is the code
#WebMethod(operationName = "authorize")
public String [] authorize(#WebParam(name = "Username")
String Username) {
CAuthorization CA = new CAuthorization();
String [] Result= null;
try {
Result = CA.CheckAuthorization(Username);
} catch (SQLException ex) {
Logger.getLogger(WS_Authentication.class.getName()).log(Level.SEVERE, null, ex);
}
**return Result;**
}
And then i made a Servlet
The code of the servlet thing is :
try { // Call Web Service Operation
java.lang.String result = null;
result = port.authorize(Username);
out.println("Result = "+result);
} catch (Exception ex) {
// TODO handle custom exceptions here
}
Problem is in my WEbservice Code in RETURN STATEMENT i have attributes of any table
and i want to take these attributes to servlet so that i can see them on my front end
but what im getting here is the only the LAST ATTRIBUTE
Thanks!
This is the way u can handle Webservice Operation of String Return type
#WebMethod(operationName = "authorize")
public String authorize(#WebParam(name = "Username")
String Username) {
CAuthorization CA = new CAuthorization();
StringBuffer result = new StringBuffer();
try {
if (CA.CheckAuthorization(Username).length > 0) {
result.append(CA.CheckAuthorization(Username)[0]);
for (int i = 1; i < CA.CheckAuthorization(Username).length; i++) {
result.append(",");
result.append(CA.CheckAuthorization(Username)[i]);
}
}
} catch (SQLException ex) {
Logger.getLogger(WS_Authentication.class.getName()).log(Level.SEVERE, null, ex);
}
//TODO write your implementation code here:
return result.toString();
}
}