Socket read IOException not being caught? - java

In grails, can the socket read failed or ioexception be caught? The following error is triggered even though i have wrapped the error part in try catch block.
ERROR 2021-03-28 08:34:10,170 [ajp-bio-8109-exec-39783] errors.GrailsExceptionResolver: IOException occurred when processing request: [POST] /race/results/
Socket read failed. Stacktrace follows:
java.io.IOException: Socket read failed
at java.io.FilterInputStream.read(FilterInputStream.java:133)
at java.io.PushbackInputStream.read(PushbackInputStream.java:186)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.Reader.read(Reader.java:140)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1485)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1461)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1436)
at org.apache.commons.io.IOUtils.toString(IOUtils.java:585)
at grails.converters.JSON.parse(JSON.java:312)
at grails.converters.JSON.parse(JSON.java:347)
At the point where the error is thrown i have wrapped it within try catch block as shown below.
def results(){
def results
try {
results = request.JSON
} catch (IOException e1) {
log.error "ERROR WHILE request.json in /results******************************************************************"
render contentType: "text/json", text: '{"status":"fail"}'
return
}
The error is thrown at this point
results = request.JSON
I appreciate any insights. I am using Grails 2.2.
Thanks!
UPDATE:
Here is the full stacktrace. Thanks!
ERROR 2021-03-28 08:34:10,170 [ajp-bio-8109-exec-39783] errors.GrailsExceptionResolver: IOException occurred when processing request: [POST] /race/results/
Socket read failed. Stacktrace follows:
java.io.IOException: Socket read failed
at java.io.FilterInputStream.read(FilterInputStream.java:133)
at java.io.PushbackInputStream.read(PushbackInputStream.java:186)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.Reader.read(Reader.java:140)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1485)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1461)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1436)
at org.apache.commons.io.IOUtils.toString(IOUtils.java:585)
at grails.converters.JSON.parse(JSON.java:312)
at grails.converters.JSON.parse(JSON.java:347)
at race.results(VirtualRaceController.groovy:2011)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

You'll probably find it is throwing ConverterException, not IOException. Here is the code:
class ConvertersExtension {
static getJSON(HttpServletRequest request) {
JSON.parse(request)
}
}
public class JSON {
public static Object parse(HttpServletRequest request) throws ConverterException {
// blah blah
try {
/// blah blah
}
catch (IOException e) {
throw new ConverterException("Error parsing JSON", e);
}
}
}
If you're using an IDE, right click on the API in question and select "GO To declaration", or whatever the equivilent is in your IDE until you trace your way up to see what throws what.

Related

Exception is thrown with Mockito but it is not caught in JUnit

I have a problem with a test case and cannot pass through it, tried to change some things but in any case the result is the same. I am pretty new to Mockito and to this kind of tests - so cannot understand what may be wrong.
Tried to do this way with a try catch block
#Test
public void shouldFailToRead_URLFileNotFound() throws IOException {
URLConnection urlConnection = mock(URLConnection.class);
fakedUrlStreamHandler.addConnection(URL_FILE_NOT_FOUND, urlConnection);
FileNotFoundException fileNotFoundException = new FileNotFoundException("There is no such a file " + URL_FILE_NOT_FOUND);
when(urlConnection.getInputStream()).thenThrow(fileNotFoundException);
try {
fileUpdater.downloadFile(fileUpdateListener, URL_FILE_NOT_FOUND);
fail("Was expecting a RuntimeException with FileNotFoundException");
} catch (RuntimeException e) {
assertThat(e.getCause(), equalTo(fileNotFoundException));
}
}
The method that checks if an URL is alive
private boolean isUrlFileExists(final URL urlToDownload) {
try {
URLConnection connection = urlToDownload.openConnection();
connection.getInputStream();
return true;
} catch (IOException e) {
error("There is no file at " + urlToDownload + ". No Connection: " + e.getMessage(), e);
throw new RuntimeException(e);
}
}
The line with fileUpdater.downloadFile have a nested call of methods until it get to isUrlFileExists.
Tried to do using expected keyword
(expected = FileNotFoundException.class)
Also tried it with #Rule annotation
#Rule
public ExpectedException exceptionRule = ExpectedException.none();
exceptionRule.expect(FileNotFoundException.class);
In any case I get the same error message
Exception in thread "FileDownloadThread" java.lang.RuntimeException: java.io.FileNotFoundException: There is no such a file http://somehost.com/download/file-not-found.zip
at com.files.impl.FileUpdater$DownloadWorker.isUrlFileExists(FileUpdater.java:263)
at com.files.impl.FileUpdater$DownloadWorker.makeDownloadAttempt(FileUpdater.java:285)
at com.files.impl.FileUpdater$DownloadWorker.run(FileUpdater.java:324)
Caused by: java.io.FileNotFoundException: There is no such a file http://somehost.com/download/file-not-found.zip
at java.net.URL.openStream(URL.java:1045)
at com.files.impl.FileUpdater$DownloadWorker.isUrlFileExists(FileUpdater.java:258)
... 2 more
java.lang.AssertionError: Was expecting a RuntimeException with FileNotFoundException
So in the end exception is thrown but it cannot be caught in my Test case, what I do wrong in here?
Originally tried to write the test this way, and register a URLStreamHandlerFactory for that using this post as an example, I am using Mockito 1.6 and locked in to this version.

Vertx HttpClientRequest - Unable to catch timeout exception

I have been unable to catch time out exception that happens in my vertx HttpClientRequest. I have enclosed my connection and request creation code in try-catch block. Also I have added exceptionHandler and endHandler. But none of them gets fired when the time out happens. All I receive is the below error message which gets printed on the console. Please give me idea how to catch this exception, so that I can call the caller back with relevant info.
io.vertx.core.http.impl.HttpClientRequestImpl
SEVERE: io.netty.channel.ConnectTimeoutException: connection timed out:
The code below is what I use to make request to server. As you can see I have used try-catch and added exceptionHandler as well.
try{
HttpClient httpClient = Vert.x.createHttpClient(new HttpClientOptions().setSsl(true).setTrustAll(true).setVerifyHost(false));
HttpClientRequest request = httpClient.get(port, host, uri.getRawPath(), event-> {
event.exceptionHandler(e -> {
log.error(" Error:: " + e);
});
event.handler(handler -> {
//code
});
});
request.putHeader(HttpHeaders.Names.AUTHORIZATION, "Basic "+authEnc);
request.end();
} catch(Exception e){
log.error(" Exception :: " + e);
}
Due to the async programing model you won't be able to use try-catch since your method has long been terminated before you get the timeout event. In order to catch it you need to setup an exception handler like:
request.exceptionHandler(t -> {
// where t is a throwable
// do something with it...
}
If you're interested in catching response exceptions same concept applies.

Open javamail folder failed

I developed an email website using javamail and apache-james and it works well mostly. But some user got Open failed Exception and cannot receive new mail.
The code of receive email:
Session mailSession = Session.getInstance(System.getProperties(), null);
mailSession.setDebug(false);
Store store = null;
Folder folder = null; //javax.mail.Folder
try {
store = mailSession.getStore(SParam.PROTOCOL);
store.connect(Property.getPop3(), userName, password);
logger.info("trying to receive emails from james server...");
folder = store.getFolder("INBOX");
try {
if (!folder.isOpen()) {
folder.open(Folder.READ_WRITE); //the point of throwing the exception
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//receive email from james server.
} catch (Exception e) {
logger.error("Email Receive Error!" + StackTraceStr.st2str(e));
try {
folder.close(true);
} catch (Exception e2) {
}
} finally {
try {
store.close();
} catch (Exception cloex) {
}
}
In most cases, it works just fine. But still got the error occasionally:
javax.mail.MessagingException: Open failed;
nested exception is:
java.io.IOException: STAT command failed: null
at com.sun.mail.pop3.POP3Folder.open(POP3Folder.java:228)
at com.csc.mail.jsh.mail.core.ReceiveMail.receive(ReceiveMail.java:82)
at com.csc.mail.jsh.mail.core.ReceiveMail.run(ReceiveMail.java:222)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.io.IOException: STAT command failed: null
at com.sun.mail.pop3.Protocol.stat(Protocol.java:366)
at com.sun.mail.pop3.POP3Folder.open(POP3Folder.java:203)
... 3 more
Waiting your help and thanks a lot!
I debug and debug, finally found the STAT command failed! when STAT command got an error, there's an exception of james, but that makes no sence!
21/11/12 14:39:16 ERROR pop3server: Exception during connection from 127.0.0.1
(127.0.0.1) : An exception occurred getting a database connection.
org.apache.avalon.framework.CascadingRuntimeException: An exception occurred getting a database connection.
at org.apache.james.userrepository.AbstractJdbcUsersRepository.openConnection(AbstractJdbcUsersRepository.java:617)
at org.apache.james.userrepository.AbstractJdbcUsersRepository.getUserByName(AbstractJdbcUsersRepository.java:521)
at org.apache.james.userrepository.AbstractUsersRepository.test(AbstractUsersRepository.java:270)
at org.apache.james.core.LocalUsersRepository.test(LocalUsersRepository.java:90)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.avalon.phoenix.components.application.BlockInvocationHandler.invoke(BlockInvocationHandler.java:134)
at $Proxy4.test(Unknown Source)
at org.apache.james.pop3server.POP3Handler.doPASS(POP3Handler.java:537)
at org.apache.james.pop3server.POP3Handler.parseCommand(POP3Handler.java:479)
at org.apache.james.pop3server.POP3Handler.handleConnection(POP3Handler.java:277)
at org.apache.james.util.connection.ServerConnection$ClientConnectionRunner.run(ServerConnection.java:432)
at org.apache.excalibur.thread.impl.ExecutableRunnable.execute(ExecutableRunnable.java:55)
at org.apache.excalibur.thread.impl.WorkerThread.run(WorkerThread.java:116)
Caused by: java.sql.SQLException: Listener refused the connection with the following error:
ORA-12519, TNS:no appropriate service handler found
The Connection descriptor used by the client was: 192.168.250.23:1521:csmis
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:261)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:387)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:439)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:37)
at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:290)
at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:771)
at org.apache.commons.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:95)
at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:540)
at org.apache.james.util.dbcp.JdbcDataSource.getConnection(JdbcDataSource.java:220)
at org.apache.james.userrepository.AbstractJdbcUsersRepository.openConnection(AbstractJdbcUsersRepository.java:614)
... 15 more
All application runs on the same server, and there's only a few users online(when I test it, only me use it). The error just appear occasionally. Why?
It seems to be a mail server issue. STAT command is used to show number of messages. Normally STAT is the first command to run after successfully connected to the mail server.
Try to use mailSession.setDebug(true) to enter debug mode to get more error logs.
I had contact with Apache James and finally found the answer. You can find it at here: STAT command failed occasionally. At the end of the page, the thread had been listed.

How to deal with SocketTimeoutException inside Java Code / Webservices

This is my Method code shown below
Actually this serves as a Webservices Method .
public Response getData(ServiceRequest request)
{
try
{
final boolean toProceedorNot = validate(legdata);
if (!toProceedorNot) {
status.setErrorText(errorText);
return response;
}
else {
// Some Processing is done here
response.setMessage(result);
}
}
catch(Exception e)
{
errorText = e.getMessage().toString();
status.setErrorText(errorText);
response.setStatus(status);
}
return response;
}
If the execution of the Method takes longer time , an SocketTimeoutException will be thrown by the Apache CXF Framework
at java.lang.Thread.run(Thread.java:662)
Caused by: java.net.SocketTimeoutException: Read timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:258)
at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:695)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:640)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1195)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:2034)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:2013)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1938)
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:66)
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:626)
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
My Question is that, even though an SocketTimeoutException is thrown, it is not coming inside the Exception block.
I am not sure whether this Exception , should be handled by whom ( The client or inside the Webservices Implementation method )
But as a Webservice provider , please tell me how to deal with this Exception ??

Why is UnknownHostException not caught in Exception (java)?

My code looks like this :
try
{
String htmlPageText=readFromHtml("http://www.yahoo.com");
}
catch (Exception e)
{
System.out.println("===Here===");
}
Method readFromHtml() will take a URL and return an HTML page. Normally it works fine. But I'm trying to simulate a "site down" situation, so I unplugged the Internet connection. I thought, the error should be caught and the result will be "===Here===", but instead, it returned:
java.net.UnknownHostException: http://www.yahoo.com"
and never printed out "===Here===". UnknownHostException is an extension of java.lang.Exception, so why was it not caught in the catch clause? Do I need a catch (UnknownHostException ex) to get it?
What is the readFromHTML method source code ? My guess is that this method throws some kind of exception but not UnknownHostException... Somewhere else in your code the exception is left unhandled.

Categories