Example usage for javax.servlet ServletInputStream setReadListener

List of usage examples for javax.servlet ServletInputStream setReadListener

Introduction

In this page you can find the example usage for javax.servlet ServletInputStream setReadListener.

Prototype

public abstract void setReadListener(ReadListener readListener);

Source Link

Document

Instructs the ServletInputStream to invoke the provided ReadListener when it is possible to read

Usage

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 {//from www. jav  a2 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.sample.nonblocking.ReadTestServlet.java

/**
 * Processes requests for both HTTP//w  ww.  ja  v  a 2 s . co  m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter output = response.getWriter()) {
        output.println("<html>");
        output.println("<head>");
        output.println("<title>Servlet ReadTestServlet</title>");
        output.println("</head>");
        output.println("<body>");
        output.println("<h1>Servlet ReadTestServlet at " + request.getContextPath() + "</h1>");

        AsyncContext context = request.startAsync();
        ServletInputStream input = request.getInputStream();
        input.setReadListener(new MyReadListener(input, context));

        output.println("</body>");
        output.println("</html>");
    }
}

From source file:com.intuit.autumn.web.InputStreamHttpServletRequestWrapperTest.java

@Test(expected = RuntimeException.class)
public void testGetInputStreamSetReadListener() throws IOException {
    ServletInputStream is = inputStreamHttpServletRequestWrapper.getInputStream();

    is.setReadListener(readListener);
}

From source file:com.intuit.autumn.web.InputStreamHttpServletRequestWrapperTest.java

@Test
public void testGetInputStreamSetReadListenerDetail() throws Exception {
    ServletInputStream is = inputStreamHttpServletRequestWrapper.getInputStream();

    try {/* w ww . ja  va  2 s .  c om*/
        is.setReadListener(readListener);
    } catch (RuntimeException e) {
        assertThat(e.getMessage(), is("Not implemented"));
    }
}

From source file:com.kolich.curacao.examples.controllers.NonBlockingIOExampleController.java

@PUT("/api/nonblocking")
public final void nonblocking(final AsyncContext context, final HttpServletRequest request,
        final HttpServletResponse response, final ServletInputStream input, final ServletOutputStream output)
        throws Exception {

    final Queue<Option<String>> queue = new ConcurrentLinkedQueue<Option<String>>();

    final WriteListener writer = new StupidWriteListener(context, queue, output);

    final ReadListener reader = new StupidReadListener(queue, input, output, writer,
            request.getContentLength());

    // Producer/*w w  w.jav  a  2  s . c o m*/
    input.setReadListener(reader);
    logger__.info("Tomcat, is input ready?: " + input.isReady());
    reader.onDataAvailable();

    // Consumer
    output.setWriteListener(writer);
    logger__.info("Tomcat, is input ready?: " + output.isReady());
    writer.onWritePossible();

}

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  ww  .  ja v a  2  s. c  om*/
@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");
        }
    });

}