Unable to handle Exception properly in spring boot pubsub app - spring-boot

This is my code where i have problem:
try {
publisher.publish(payload).get();
} catch (com.google.api.gax.rpc.DeadlineExceededException e) {
LOGGER.error("com.google.api.gax.rpc.DeadlineExceededException occured: " + e.getCause());
} catch (com.google.api.gax.rpc.NotFoundException e) {
LOGGER.error("com.google.api.gax.rpc.NotFoundException occured: " + e.getCause());
} catch (com.google.api.gax.rpc.ApiException e) {
LOGGER.error("com.google.api.gax.rpc.ApiException occured: " + e.getCause());
} catch (io.grpc.StatusRuntimeException e) {
LOGGER.error("io.grpc.StatusRuntimeException occured: " + e.getCause());
} catch (java.lang.RuntimeException e) {
LOGGER.error("RuntimeException occured: " + e.getCause());
} catch (java.util.concurrent.ExecutionException e) {
LOGGER.error("java.util.concurrent.ExecutionException occured: " + e.getCause()); // my program cursor always come to this point
} catch (Exception e) {
LOGGER.error("Exception occured: " + e.getCause());
}
And the getCause of ExecutionException catch is:
java.util.concurrent.ExecutionException occured:
com.google.api.gax.rpc.NotFoundException:
io.grpc.StatusRuntimeException: NOT_FOUND: Resource not found
If you see I already put the catch for "com.google.api.gax.rpc.NotFoundException" in second catch, so why it went into the ExcutionException catch.
Due to this nature I am not able to write proper message for the client to address.
Thanks in advance if anyone can help.

When publisher.publish(payload).get() would have been executed it would have thrown java.util.concurrent.ExecutionException ex= new com.google.api.gax.rpc.NotFoundException() i.e reference of java.util.concurrent.ExecutionException but object of com.google.api.gax.rpc.NotFoundException. So in try catch , when reference was checking which catch block to go, it could not get through api.gax.rpc.NotFoundException() as cactch only catches same or super class so it got catch later but since object was madeup of com.google.api.gax.rpc.NotFoundException so getCause got overridden and when you executed it object method was called.
Resolution: eg
try{
}
catch(Exception e){
throw (e.getClass()).cast(e);
}
where you can put this catch block in java.util.concurrent.ExecutionException.

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);
}

Unable to write to disk using GridFSFile in springboot 2.0.2

Trying to use code in:
http://javasampleapproach.com/spring-framework/spring-data/springdata-mongodb-gridfstemplate-save-retrieve-delete-binary-files-image-text-files
with springboot 1.5.13.
In this code to retrieve an image use GridFSDBFile like this:
GridFSDBFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(imageFileId)));
and later to save in filesystem use this:
imageFile.writeTo
Baeldung has the same code:
http://www.baeldung.com/spring-data-mongodb-gridfs
I have my project in springboot 2.0.2 and this line:
GridFSDBFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(imageFileId)));
throws an error:
Type mismatch: cannot convert from GridFSFile to GridFSDBFile
so, once I have changed to:
GridFSFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(imageFileId)));
no errors, but now I have not available the method:
writeTo
to write to disk.
UPDATE 1:
imageFileId = "5b0bff8b7cc45b32f43b47f4";
GridFSFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(imageFileId)));
try {
File file = new File("c:/JSA/retrieve/" + imageFile.getFilename());
FileOutputStream streamToDownloadTo = new FileOutputStream(file);
//This line doesn't works
gridFSBucket.downloadToStream(imageFile.getId(), streamToDownloadTo);
streamToDownloadTo.close();
} catch (IOException e) {
// handle exception
System.out.println("error: " + e.getMessage());
} catch (Exception e1) {
System.out.println("error1: " + e1.getMessage());
}
UPDATE 2:
try {
File file = new File("c:/JSA/retrieve/" + imageFile.getFilename());
FileOutputStream streamToDownloadTo = new FileOutputStream(file);
System.out.println("imageFile.getId(): " + imageFile.getId());
System.out.println("streamToDownloadTo: " + streamToDownloadTo.toString());
gridFSBucket.downloadToStream(imageFile.getId(), streamToDownloadTo);
streamToDownloadTo.close();
} catch (IOException e) {
// handle exception
System.out.println("error: " + e.getMessage());
} catch (Exception e1) {
System.out.println("error1: " + e1.getMessage());
}
Console
imageFile.getId(): BsonObjectId{value=5b0bff8b7cc45b32f43b47f4}
streamToDownloadTo: java.io.FileOutputStream#3b20c8e2
This line thrown an exception:
gridFSBucket.downloadToStream(imageFile.getId(), streamToDownloadTo);
and return null
Solved
Inject:
#Autowired
MongoGridFsTemplate mongoGridFsTemplate;
GridFSBucket gridFSBucket = GridFSBuckets.create(mongoGridFsTemplate.mongoDbFactory().getDb());
imageFileId = "5b0bff8b7cc45b32f43b47f4";
GridFSFile imageFile = gridOperations.findOne(new Query(Criteria.where("_id").is(new ObjectId(imageFileId))));
try {
File file = new File("c:/JSA/retrieve/" + imageFile.getFilename());
FileOutputStream streamToDownloadTo = new FileOutputStream(file);
gridFSBucket.downloadToStream(imageFile.getId(), streamToDownloadTo);
streamToDownloadTo.close();
} catch (IOException e) {
// handle exception
System.out.println("error: " + e.getMessage());
} catch (Exception e1) {
e1.printStackTrace();
}

How to create a SDO_Geometry over Oracle-JDBC

I want to create an Oracle Spatial Geometry over JDBC with the following Statement:
//insert vorbereiten
try {
preStatement = conn.prepareStatement("insert into way(id, shape) "
+ "values(? ,SDO_GEOMETRY(2002,NULL,NULL,SDO_ELEM_INFO_ARRAY(1,2,1), SDO_ORDINATE_ARRAY(?)))");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("setString:");
preStatement.setString(1, "1");
Array a=conn.createArrayOf("double", new Object[]{9.23, 52.45, 9.67, 52.54});
preStatement.setArray(2, a);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But this does not work. Can someone please tell me how I can set the SDO_ORDINATE_ARRAY(?)-Values ?

How to fix error thrown during update of scroll sensitive resultset?

I'm trying to update a row in ResultSet, but it is throwing an error. I passed the constant value ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE to createStatement.
this is my code :
public void modifyPrice(float percentage) throws SQLException {
try {
con = util.connectdb();
con.setAutoCommit(false);
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("select * from " + util.dbName
+ ".COFFEES");
while (rs.next()) {
float f = rs.getFloat("PRICE");
rs.updateFloat("PRICE", f * percentage);
rs.updateRow();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (st != null) {
st.close();
con.close();
}
}
}
When I executed this code block, the stack below got printed on console.
java.sql.SQLException: Invalid operation for read only resultset: updateFloat
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:131)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:197)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:261)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:269)
at oracle.jdbc.driver.BaseResultSet.updateFloat(BaseResultSet.java:236)
at oracle.jdbc.driver.OracleResultSet.updateFloat(OracleResultSet.java:677)
at tutorial.ModifyResultSet.modifyPrice(ModifyResultSet.java:29)
at tutorial.ModifyResultSet.main(ModifyResultSet.java:15)
Can anyone help me fix this error?
According to these links
http://www.coderanch.com/t/301466/JDBC/databases/Invalid-operation-read-only-resultset
http://www.coderanch.com/t/295932/JDBC/databases/updateXXX-function-ResultSet
instead of "select * from" you should use "select my_column_name from" statement.
See if it makes any difference.

Set Field Text, Java

I have two classes. MetaDataExtractor(GUI) and MetaData.
MetaData has the method which extracts the metadata from an image. MetaDataExtractor is designed to display the data in a JTextPane. (Please excuse the class names. I know it's a little confusing. I'm fairly new to Java).
MetaDataExtractor:
LongitudeField.setText("" + MetaDataTags.getLongitude());
MetaData:
public String getLongitude() {
try {
Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
if (metadata.containsDirectory(GpsDirectory.class)) {
GpsDirectory gpsDir = (GpsDirectory) metadata.getDirectory(GpsDirectory.class);
GpsDescriptor gpsDesc = new GpsDescriptor(gpsDir);
String Longitude = "" + gpsDesc.getGpsLongitudeDescription();
}
} catch (ImageProcessingException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 1");
} catch (IOException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 2");
}
return longitude;
}
If I set the longitude to be displayed in the JTextPane, it returns "null". If however, I set it to print out on the command line, it prints the longitude fine?
Please excuse me if its a simple solution. I'm still getting to grips with Java.
Java is case sensitive and declare firstly your variable outside of try & catch statement.
Use a IDE like Eclipse to reduce syntax errors like these.
so you should have :
public String getLongitude() {
String longitudeDesc ="";
try {
Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
if (metadata.containsDirectory(GpsDirectory.class)) {
GpsDirectory gpsDir = (GpsDirectory) metadata.getDirectory(GpsDirectory.class);
GpsDescriptor gpsDesc = new GpsDescriptor(gpsDir);
longitudeDesc = "" + gpsDesc.getGpsLongitudeDescription();
}
} catch (ImageProcessingException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 1");
} catch (IOException ex) {
Logger.getLogger(MetaData.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error 2");
}
return longitudeDesc ;
}

Resources