List of usage examples for javax.servlet ServletInputStream isReady
public abstract boolean isReady();
From source file:jp.opencollector.guacamole.auth.delegated.DelegatedAuthenticationProvider.java
private static Optional<GuacamoleConfiguration> buildConfigurationFromRequest(HttpServletRequest req) throws GuacamoleException { try {//from w w w .ja v a2 s .co m if (req.getClass().getName().equals("org.glyptodon.guacamole.net.basic.rest.APIRequest")) { final GuacamoleConfiguration config = new GuacamoleConfiguration(); final String protocol = req.getParameter("protocol"); if (protocol == null) throw new GuacamoleException("required parameter \"protocol\" is missing"); config.setProtocol(protocol); for (Map.Entry<String, String[]> param : req.getParameterMap().entrySet()) { String[] values = param.getValue(); if (values.length > 0) config.setParameter(param.getKey(), values[0]); } return Optional.of(config); } else { final ServletInputStream is = req.getInputStream(); if (!is.isReady()) { MediaType contentType = MediaType.parse(req.getContentType()); boolean invalidContentType = true; if (contentType.type().equals("application")) { if (contentType.subtype().equals("json")) { invalidContentType = false; } else if (contentType.subtype().equals("x-www-form-urlencoded") && req.getParameter("token") != null) { return Optional.<GuacamoleConfiguration>absent(); } } if (invalidContentType) throw new GuacamoleException(String.format("expecting application/json, got %s", contentType.withoutParameters())); final GuacamoleConfiguration config = new GuacamoleConfiguration(); try { final ObjectMapper mapper = new ObjectMapper(); JsonNode root = (JsonNode) mapper.readTree( createJsonParser(req.getInputStream(), contentType.charset().or(UTF_8), mapper)); { final JsonNode protocol = root.get("protocol"); if (protocol == null) throw new GuacamoleException("required parameter \"protocol\" is missing"); final JsonNode parameters = root.get("parameters"); if (parameters == null) throw new GuacamoleException("required parameter \"parameters\" is missing"); config.setProtocol(protocol.asText()); { for (Iterator<Entry<String, JsonNode>> i = parameters.fields(); i.hasNext();) { Entry<String, JsonNode> member = i.next(); config.setParameter(member.getKey(), member.getValue().asText()); } } } } catch (ClassCastException e) { throw new GuacamoleException("error occurred during parsing configuration", e); } return Optional.of(config); } else { return Optional.<GuacamoleConfiguration>absent(); } } } catch (IOException e) { throw new GuacamoleException("error occurred during retrieving configuration from the request body", e); } }
From source file:com.intuit.autumn.web.InputStreamHttpServletRequestWrapperTest.java
@Test public void testGetInputStreamIsReady() throws IOException { ServletInputStream is = inputStreamHttpServletRequestWrapper.getInputStream(); assertThat(is.isReady(), is(true)); }
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 av a2 s .c o m 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: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// ww w . j a v a 2 s . c om 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.springframework.reactive.web.servlet.RequestBodyPublisher.java
@Override public void onDataAvailable() throws IOException { ServletInputStream input = this.synchronizer.getInputStream(); while (true) { logger.debug("Demand: " + this.demand); if (!demand.hasDemand()) { break; }/* w w w .j a v a 2 s . c o m*/ boolean ready = input.isReady(); logger.debug("Input " + ready + "/" + input.isFinished()); if (!ready) { break; } int read = input.read(buffer); logger.debug("Input read:" + read); if (read == -1) { break; } else if (read > 0) { this.demand.decrement(); byte[] copy = Arrays.copyOf(this.buffer, read); // logger.debug("Next: " + new String(copy, UTF_8)); this.subscriber.onNext(copy); } } }
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. j a 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"); } }); }