List of usage examples for javax.servlet AsyncListener AsyncListener
AsyncListener
From source file:io.atrato.pubsubserver.PubsubRestProvider.java
@GET @Path("topics/{topic}") @Produces(MediaType.APPLICATION_JSON)// ww w . jav a2 s . com public PubsubBroker.TimedTopicData getTopicData(@PathParam("topic") String topic, @QueryParam("laterThan") Long timestamp, @QueryParam("poll") Boolean poll, @Context HttpServletRequest request) { if (timestamp == null) { timestamp = -1L; } //LOG.debug("topic: {} poll: {}", topic, poll); PubsubBroker.TimedTopicData data = PubsubServer.getBroker().getLatestTopicData(topic, timestamp); if (data == null) { if (BooleanUtils.isTrue(poll)) { AsyncContext asyncContext = request.startAsync(); PubsubServer.getBroker().oneTimeSubscribe(asyncContext, topic); asyncContext.addListener(new AsyncListener() { @Override public void onComplete(AsyncEvent asyncEvent) throws IOException { PubsubServer.getBroker().invalidateOneTimeSubscriber(asyncEvent.getAsyncContext()); } @Override public void onTimeout(AsyncEvent asyncEvent) throws IOException { PubsubServer.getBroker().invalidateOneTimeSubscriber(asyncEvent.getAsyncContext()); } @Override public void onError(AsyncEvent asyncEvent) throws IOException { PubsubServer.getBroker().invalidateOneTimeSubscriber(asyncEvent.getAsyncContext()); } @Override public void onStartAsync(AsyncEvent asyncEvent) throws IOException { } }); return null; } else { throw new NotFoundException(); } } LOG.debug("topic: {} poll: {} data: {}", topic, poll, (data != null ? data.getData() : data)); return data; }
From source file:com.sishuok.chapter3.web.controller.StreamingController.java
@RequestMapping("/async3") public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Connection", "Keep-Alive"); resp.addHeader("Cache-Control", "private"); resp.addHeader("Pragma", "no-cache"); resp.setContentType("text/html;charset=utf-8"); resp.flushBuffer();//from w w w. j a va2 s . c o m //1?? final AsyncContext asyncContext = req.startAsync(); asyncContext.addListener(new AsyncListener() { @Override public void onComplete(final AsyncEvent event) throws IOException { queue.remove(event.getAsyncContext()); } @Override public void onTimeout(final AsyncEvent event) throws IOException { event.getAsyncContext().complete(); queue.remove(event.getAsyncContext()); } @Override public void onError(final AsyncEvent event) throws IOException { queue.remove(event.getAsyncContext()); } @Override public void onStartAsync(final AsyncEvent event) throws IOException { } }); //???? queue.add(asyncContext); }
From source file:com.cisco.oss.foundation.http.server.MonitoringFilter.java
@Override public void doFilterImpl(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { regiterMonitoring();//from w w w . j a va2 s. c o m final long startTime = System.currentTimeMillis(); HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; String tempMethodName = httpServletRequest.getMethod(); if (uniqueUriMonitoringEnabled) { tempMethodName += ":" + httpServletRequest.getRequestURI(); } boolean reportToMonitoring = true; try { LOGGER.trace("Monitoring filter: Request processing started at: {}", startTime); // methodName = httpServletRequest.getMethod() + ":" + httpServletRequest.getRequestURI().toString(); tempMethodName = updateMethodName(httpServletRequest, tempMethodName); LOGGER.trace("transaction method name is: {}", tempMethodName); CommunicationInfo.getCommunicationInfo().transactionStarted(serviceDetails, tempMethodName, threadPool != null ? threadPool.getThreads() : -1); } catch (Exception e) { LOGGER.error("can't report monitoring data as it has failed on:" + e); reportToMonitoring = false; } final String methodName = tempMethodName; try { chain.doFilter(httpServletRequest, httpServletResponse); if (request.isAsyncStarted()) { AsyncContext async = request.getAsyncContext(); async.addListener(new AsyncListener() { @Override public void onComplete(AsyncEvent event) throws IOException { final long endTime = System.currentTimeMillis(); final int processingTime = (int) (endTime - startTime); LOGGER.debug("Processing time: {} milliseconds", processingTime); } @Override public void onTimeout(AsyncEvent event) throws IOException { } @Override public void onError(AsyncEvent event) throws IOException { Throwable throwable = event.getThrowable(); if (throwable != null) { CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, true, throwable.toString()); } } @Override public void onStartAsync(AsyncEvent event) throws IOException { } }); } else { final long endTime = System.currentTimeMillis(); final int processingTime = (int) (endTime - startTime); LOGGER.debug("Processing time: {} milliseconds", processingTime); } } catch (Exception e) { CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, true, e.toString()); throw e; } if (reportToMonitoring) { try { int status = httpServletResponse.getStatus(); if (status >= 400) { CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, true, httpServletResponse.getStatus() + ""); } else { CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, false, ""); } } catch (Exception e) { LOGGER.error("can't report monitoring data as it has failed on:" + e); } } }
From source file:org.apache.vysper.xmpp.extension.xep0124.BoshBackedSessionContext.java
protected void addContinuationExpirationListener(final AsyncContext context) { // listen the continuation to be notified when the request expires context.addListener(new AsyncListener() { public void onTimeout(AsyncEvent event) throws IOException { requestExpired(context);//from ww w. j a v a2s . c o m } public void onStartAsync(AsyncEvent event) throws IOException { // ignore } public void onError(AsyncEvent event) throws IOException { handleAsyncEventError(event); } public void onComplete(AsyncEvent event) throws IOException { // ignore } }); }
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 *///w w w. j a va 2 s .co 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"); } }); }