Problem:
While developing a utility to merge multiple pdf streams to a single output stream, I am getting SocketException while reading data from an input stream out of a list of input streams i.e at this line [ byte[] bytes = toByteArray(input) ]. This causes data from only some input streams to get merged into a single pdf and few input streams which threw exception don't get merged.
Note: The input streams in inputStreamList in the code below are created by calling openStream() method on various URLs.
This error occurs only sometimes on few environments and not all environments. These environments are hosted on different servers.
Block of code:
public void doMergeIntoFile(List<InputStream> inputStreamList, final String fileName) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PDFMergerUtility merger = new PDFMergerUtility();
merger.setDestinationStream(outputStream);
merger.setDocumentMergeMode(OPTIMIZE_RESOURCES_MODE);
for (InputStream input : inputStreamList) {
try {
byte[] bytes = toByteArray(input); // gives Socket exception sometimes
PDDocument.load(bytes).close();
merger.addSource(new ByteArrayInputStream(bytes));
} catch (IOException ioExcep) {
log.error("An exception was encountered while parsing input stream : {0}", ioExcep);
continue;
}
}
merger.mergeDocuments(setupMainMemoryOnly());
outputStream.flush();
outputStream.close();
generatePdf(outputStream.toByteArray(), fileName);
}
}
Exception message:
ERROR [origo.bimta.web.action.pdf.PDFAction] (default task-27) An exception was encountered while parsing input stream : {0}: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at sun.net.www.MeteredStream.read(MeteredStream.java:134)
at java.io.FilterInputStream.read(FilterInputStream.java:133)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3393)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3386)
at com.google.common.io.ByteStreams.copy(ByteStreams.java:207)
at com.google.common.io.ByteStreams.toByteArray(ByteStreams.java:252)
at origo.bimta.web.action.pdf.PDFAction.doMergeIntoFile(PDFAction.java:482)
Request a resolution:
Could anyone suggest a way to resolve this issue so that this socket exception can be prevented or a way so that all the input streams in the list of input streams get read successfully and eventually get successfully merged into a single pdf?
Why do you want to convert to a byte array? You should directly use inputstream instead.