List of usage examples for javax.servlet ReadListener ReadListener
ReadListener
From source file:be.solidx.hot.utils.IOUtils.java
public static Promise<byte[], Exception, Void> asyncRead(final HttpServletRequest req, final ExecutorService executorService, final ExecutorService promiseResolver) { final DeferredObject<byte[], Exception, Void> deferredObject = new DeferredObject<>(); try {/*w w w. j a v a 2 s . c om*/ final ServletInputStream servletInputStream = req.getInputStream(); servletInputStream.setReadListener(new ReadListener() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); @Override public void onError(final Throwable t) { promiseResolver.execute(new Runnable() { @Override public void run() { deferredObject.reject(new Exception(t)); } }); } @Override public void onDataAvailable() throws IOException { executorService.execute(new Runnable() { @Override public void run() { byte b[] = new byte[2048]; int len = 0; try { while (servletInputStream.isReady() && (len = servletInputStream.read(b)) != -1) { baos.write(b, 0, len); } } catch (IOException e) { LOGGER.error("", e); } } }); } @Override public void onAllDataRead() throws IOException { promiseResolver.execute(new Runnable() { @Override public void run() { deferredObject.resolve(baos.toByteArray()); } }); } }); } catch (final IOException e2) { promiseResolver.execute(new Runnable() { @Override public void run() { deferredObject.reject(new Exception(e2)); } }); } catch (final IllegalStateException exception) { promiseResolver.execute(new Runnable() { @Override public void run() { deferredObject.resolve("".getBytes()); } }); } // executorService.execute(new Runnable() { // @Override // public void run() { // final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // try { // IOUtils.toOutputStreamBuffered(req.getInputStream(), outputStream); // promiseResolver.execute(new Runnable() { // @Override // public void run() { // deferredObject.resolve(outputStream.toByteArray()); // } // }); // } catch (final IOException e) { // promiseResolver.execute(new Runnable() { // @Override // public void run() { // deferredObject.reject(e); // } // }); // } // } // }); return deferredObject.promise(); }
From source file:org.synchronoss.cloud.nio.multipart.example.web.MultipartController.java
/** * <p> This is an example how the NIO Parser can be used in a plain Servlet 3.1 fashion. * * @param request The {@code HttpServletRequest} * @throws IOException if an IO exception happens *//*from w w w. ja va 2 s.c o m*/ @RequestMapping(value = "/nio/multipart", method = RequestMethod.POST) public @ResponseBody void nioMultipart(final HttpServletRequest request) throws IOException { assertRequestIsMultipart(request); final VerificationItems verificationItems = new VerificationItems(); final AsyncContext asyncContext = switchRequestToAsyncIfNeeded(request); final ServletInputStream inputStream = request.getInputStream(); final AtomicInteger synchronizer = new AtomicInteger(0); final NioMultipartParserListener listener = new NioMultipartParserListener() { Metadata metadata; @Override public void onPartFinished(final StreamStorage partBodyStreamStorage, final Map<String, List<String>> headersFromPart) { if (log.isInfoEnabled()) log.info("PARSER LISTENER - onPartFinished"); final String fieldName = MultipartUtils.getFieldName(headersFromPart); final ChecksumStreamStorage checksumPartStreams = getChecksumStreamStorageOrThrow( partBodyStreamStorage); if (METADATA_FIELD_NAME.equals(fieldName)) { metadata = unmarshalMetadataOrThrow(checksumPartStreams); } else { VerificationItem verificationItem = buildVerificationItem(checksumPartStreams, fieldName); verificationItems.getVerificationItems().add(verificationItem); } } @Override public void onNestedPartStarted(final Map<String, List<String>> headersFromParentPart) { if (log.isInfoEnabled()) log.info("PARSER LISTENER - onNestedPartStarted"); } @Override public void onNestedPartFinished() { if (log.isInfoEnabled()) log.info("PARSER LISTENER - onNestedPartFinished"); } @Override public void onFormFieldPartFinished(String fieldName, String fieldValue, Map<String, List<String>> headersFromPart) { if (log.isInfoEnabled()) log.info("PARSER LISTENER - onFormFieldPartFinished"); if (METADATA_FIELD_NAME.equals(fieldName)) { metadata = unmarshalMetadataOrThrow(fieldValue); } } @Override public void onAllPartsFinished() { if (log.isInfoEnabled()) log.info("PARSER LISTENER - onAllPartsFinished"); processVerificationItems(verificationItems, metadata, true); sendResponseOrSkip(synchronizer, asyncContext, verificationItems); } @Override public void onError(String message, Throwable cause) { // Probably invalid data... throw new IllegalStateException("Encountered an error during the parsing: " + message, cause); } synchronized Metadata unmarshalMetadataOrThrow(final String json) { if (metadata != null) { throw new IllegalStateException("Found two metadata fields"); } return unmarshalMetadata(json); } synchronized Metadata unmarshalMetadataOrThrow(final ChecksumStreamStorage checksumPartStreams) { if (metadata != null) { throw new IllegalStateException("Found more than one metadata fields"); } return unmarshalMetadata(checksumPartStreams.getInputStream()); } }; final MultipartContext ctx = getMultipartContext(request); final NioMultipartParser parser = multipart(ctx) .usePartBodyStreamStorageFactory(partBodyStreamStorageFactory).forNIO(listener); // Add a listener to ensure the parser is closed. asyncContext.addListener(new AsyncListener() { @Override public void onComplete(AsyncEvent event) throws IOException { parser.close(); } @Override public void onTimeout(AsyncEvent event) throws IOException { parser.close(); } @Override public void onError(AsyncEvent event) throws IOException { parser.close(); } @Override public void onStartAsync(AsyncEvent event) throws IOException { // Nothing to do. } }); inputStream.setReadListener(new ReadListener() { @Override public void onDataAvailable() throws IOException { if (log.isInfoEnabled()) log.info("NIO READ LISTENER - onDataAvailable"); int bytesRead; byte bytes[] = new byte[2048]; while (inputStream.isReady() && (bytesRead = inputStream.read(bytes)) != -1) { parser.write(bytes, 0, bytesRead); } if (log.isInfoEnabled()) log.info("Epilogue bytes..."); } @Override public void onAllDataRead() throws IOException { if (log.isInfoEnabled()) log.info("NIO READ LISTENER - onAllDataRead"); sendResponseOrSkip(synchronizer, asyncContext, verificationItems); } @Override public void onError(Throwable throwable) { log.error("onError", throwable); IOUtils.closeQuietly(parser); sendErrorOrSkip(synchronizer, asyncContext, "Unknown error"); } }); }