Best way to assert that a value is not null - spring-boot

This is my method.
public boolean authenticateAndPollCallbackResult(BankIdAuthRequest bankIdAuthRequest) {
ResponseEntity<BankIdAuthResponse> authResponse = bankIdAuthentication(bankIdAuthRequest);
AbstractApplicationForm applicationForm = applicationFormRepository.findByToken(bankIdAuthRequest.getRefID());
try {
//Add new bankId authentication to database.
BankIdAuthenticationEntity bankIdAuthenticationEntity = new BankIdAuthenticationEntity();
bankIdAuthenticationEntity.setAbstractApplicationForm(applicationForm);
bankIdAuthenticationEntity.setAuthStatus(STATUS_PROGRESS);
bankIdAuthenticationEntity.setOrderReference(authResponse.getBody().getOrderRef());
bankIdAuthenticationEntity.setAutoStartToken(authResponse.getBody().getAutoStartToken());
Long bankIdAuthenticationId = bankIdAuthenticationRepository.save(bankIdAuthenticationEntity).getId();
BankIdAuthenticationEntity.AuthStatus authStatus;
do {
TimeUnit.MILLISECONDS.sleep(1500);
authStatus = getAuthStatus(bankIdAuthenticationId);
if (authStatus == BankIdAuthenticationEntity.AuthStatus.COMPLETED)
return true;
if (authStatus == BankIdAuthenticationEntity.AuthStatus.FAILED || authStatus == BankIdAuthenticationEntity.AuthStatus.NOT_ASSIGNED)
return false;
} while (authStatus == BankIdAuthenticationEntity.AuthStatus.PROGRESS);
} catch (InterruptedException e) {
log.error("InterruptedException: ", e);
Thread.currentThread().interrupt();
} catch (NullPointerException e) {
log.error("Either BankId API not responding correctly. Check server connection", e);
} catch (Exception e) {
log.error("Exception: Polling collect endpoint method failed", e);
}
return false;
}
Now SonarQube warns that these two lines can return null (and they can):
bankIdAuthenticationEntity.setOrderReference(authResponse.getBody().getOrderRef());
bankIdAuthenticationEntity.setAutoStartToken(authResponse.getBody().getAutoStartToken();
But i don't know what the best way to check for null is.
I tried using Objects.requireNonNull which throws a null and the i figured the null check would catch it but it just feel ugly and not correct.
Any suggestions or absolute correct ways of doing this that i might have missed?

The problem is that authResponse.getBody() can be null. Right?
In this cas you should check it before an either throw an exception or not execute the two lines:
if(authResponse.getBody() != null {
bankIdAuthenticationEntity.setOrderReference(authResponse.getBody().getOrderRef());
bankIdAuthenticationEntity.setAutoStartToken(authResponse.getBody().getAutoStartToken();
})
or
if(authResponse.getBody() == null {
throw new ....Exception();
}
And if the problem is that getOrderRef() or getAutoStartToken() could return null, you should check these values before and handle the cases when they are null.

Related

How to handle feign client connection timeout

I have below code to check this error but I am not getting timeout error its going to else condition
Response response = null;
try {
response = client.getResponse(URI.create(uri), headers, reuest);
} catch (Exception ex) {
if(ex instanceof SocketTimeoutException){
throw new ExternalClientException(Errors.TIMEOUT_ERROR);
} else {
throw new ExternalClientException(Errors.UNEXPECTED_ERROR);
}
}
You need to catch feign.RetryableException instead of SocketTimeoutException.
javadoc
Please send all code of class. You need to provide class of "client" variable so people can help.
One more thing, instead of checking instance of exception in "catch" clause, you should use multiple catching like this:
Response response = null;
try {
response = client.getResponse(URI.create(uri), headers, reuest);
} catch (SocketTimeoutException ex1) {
throw new ExternalClientException(Errors.TIMEOUT_ERROR, ex1);
} catch (Exception ex2) {
throw new ExternalClientException(Errors.UNEXPECTED_ERROR, ex2);
}

Transform Optional String and return Date in Java 8?

I am currently parsing a nullable String to a Date. I try to use Optional to avoid using if statement. Here is what I have written so far :
Client client = new Client();
Optional.ofNullable(methodThatMayReturnStringOrNull())
.ifPresent((s) -> {
try {
client.setBirthDate(DateUtils.parseDate(
StringUtils.substring(s, 0, 10),
new String[]{"yyyy-MM-dd"}));
} catch (ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
});
Is it possible to transform this lambda so I can make it a method similar to the following but java 8 style?
private Date parse(String complexString) {
Date birthDate = null;
if (complexString != null) {
try {
birthDate = DateUtils.parseDate(
StringUtils.substring(complexString, 0, 10),
new String[]{"yyyy-MM-dd"});
} catch (final ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
}
return birthDate;
}
Not sure how far you want to go, but you can start with
Optional<Date> date = Optional.ofNullable(methodThatMayReturnStringOrNull())
.map((s) -> {
try {
return DateUtils.parseDate(
StringUtils.substring(s, 0, 10),
new String[]{"yyyy-MM-dd"}));
} catch (ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
});
You might also consider using flatMap instead of map and returning empty optional instead of throwing exception on error - depends on how you want to progress you flow.
On completely unrelated note, get rid of Date and use either joda or new java time classes ;)

jTable that will listen to jDateChooser's 'textfield'?

Hello everyone I'm trying to make a scheduling system for my System and Analysis Design thesis and I am having trouble trying to connect/bind/make the jTable listen to the jDateChooser's input. Elaborately, I want my scheduling to be like this:
I choose a date in the jDateChooser
jTable will 'sort out' itself via the date inputted on the jDatechooser
is there anyway to do this?
For now all I have is a table propertyChangelistener:
private void sched_tablePropertyChangeListener(java.beans.PropertyChangeEvent evt) {
try{
String calendar = ((JTextField)jdc.getDateEditor().getUiComponent()).getText();
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/accountsDB?zeroDateTimeBehavior=convertToNull","root","");
String query = "select * from accountsdb.schedules where Date= ?";
ps= conn.prepareStatement(query);
ps.setString(1, calendar);
ResultSet rs = ps.executeQuery();
sched_table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
} finally {
if (conn != null)
try { conn.close();
} catch (SQLException ignore) {}
if (ps != null){
try {
ps.close();
} catch (SQLException ignore){}
}
}
}
Somehow when I run my application it doesn't seem to open if that block of code is on it which means I really did do something wrong. Can anyone change or tell me what I should do or where should I start with the jTable listening to the jDatechooser thing?
~Thanks in advance for those who will answer!~
Nevermind, turns out all I had to do was change the jDateChooser's Date Format since it wasn't exactly the same formatting hence I couldn't call anything from the database. If anyone's interested on what I did I'll just leave this here
private void jdcPropertyChange(java.beans.PropertyChangeEvent evt) {
try{
String d1 = ((JTextField)jdc.getDateEditor().getUiComponent()).getText();
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/accountsDB?zeroDateTimeBehavior=convertToNull","root","");
String query = "select * from accountsdb.schedules where Date= ? order by time,timezone";
ps = conn.prepareStatement(query);
ps.setString(1, d1);
ResultSet rs = ps.executeQuery();
sched_table.setModel(DbUtils.resultSetToTableModel(rs));
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
} finally {
if (conn != null) {
try { conn.close();
} catch (SQLException ignore) {}
}
if (ps != null){
try {
ps.close();
} catch (SQLException ignore){}
}
}
}
What this does is that everytime I pick on a date from the jDateChooser(named it jdc) the table/database calls that date and sorts it out. Which is what I wanted.

An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll

I am using Janus(Third Party) Grid and getting the "System.StackOverflowException". Don't know how to solve it. I would like to appreciate for any help.
private void gridEX1_FormattingRow(object sender, RowLoadEventArgs e)
{
int index = e.Row.RowIndex;
try
{
if (!Convert.IsDBNull(gridEX1.GetRow(index).Cells["HEADER_ORDER_PACKAGE_ROW_ID"].Value))
{
if (Convert.ToInt32(gridEX1.GetRow(index).Cells["HEADER_ORDER_PACKAGE_ROW_ID"].Value) == PARENT_ORDER_PACKAGE_ID)
{
**gridEX1.MoveToRowIndex(index);**
GridEXRow curRow = gridEX1.GetRow();
if (curRow != null)
{
curRow.Expanded = true;
}
}
}
}
catch (Exception ex)
{
}
}
It seems that one of the lines inside your handler invoke the handler itself again. And so on, so you get StackOverflow.

DD anomaly, and cleaning up database resources: is there a clean solution?

Here's a piece of code we've all written:
public CustomerTO getCustomerByCustDel(final String cust, final int del)
throws SQLException {
final PreparedStatement query = getFetchByCustDel();
ResultSet records = null;
try {
query.setString(1, cust);
query.setInt(2, del);
records = query.executeQuery();
return this.getCustomer(records);
} finally {
if (records != null) {
records.close();
}
query.close();
}
}
If you omit the 'finally' block, then you leave database resources dangling, which obviously is a potential problem. However, if you do what I've done here - set the ResultSet to null outside the **try** block, and then set it to the desired value inside the block - PMD reports a 'DD anomaly'. In the documentation, a DD anomaly is described as follows:
DataflowAnomalyAnalysis: The dataflow analysis tracks local definitions, undefinitions and references to variables on different paths on the data flow.From those informations there can be found various problems. [...] DD - Anomaly: A recently defined variable is redefined. This is ominous but don't have to be a bug.
If you declare the ResultSet outside the block without setting a value, you rightly get a 'variable might not have been initialised' error when you do the if (records != null) test.
Now, in my opinion my use here isn't a bug. But is there a way of rewriting cleanly which would not trigger the PMD warning? I don't particularly want to disable PMD's DataFlowAnomalyAnalysis rule, as identifying UR and DU anomalies would be actually useful; but these DD anomalies make me suspect I could be doing something better - and, if there's no better way of doing this, they amount to clutter (and I should perhaps look at whether I can rewrite the PMD rule)
I think this is clearer:
PreparedStatement query = getFetchByCustDel();
try {
query.setString(1, cust);
query.setInt(2, del);
ResultSet records = query.executeQuery();
try {
return this.getCustomer(records);
} finally {
records.close();
}
} finally {
query.close();
}
Also, in your version the query doesn't get closed if records.close() throws an exception.
I think that DD anomaly note is more bug, than a feature
Also, the way you free resources is a bit incomplete, for example
PreparedStatement pstmt = null;
Statement st = null;
try {
...
} catch (final Exception e) {
...
} finally {
try{
if (pstmt != null) {
pstmt.close();
}
} catch (final Exception e) {
e.printStackTrace(System.err);
} finally {
try {
if (st != null) {
st.close();
}
} catch (final Exception e) {
e.printStackTrace(System.err);
}
}
}
moreover this is not right again, cuz you should close resources like that
PreparedStatement pstmt = null;
Throwable th = null;
try {
...
} catch (final Throwable e) {
<something here>
th = e;
throw e;
} finally {
if (th == null) {
pstmt.close();
} else {
try {
if (pstmt != null) {
pstmt.close();
}
} catch (Throwable u) {
}
}
}

Resources