List of usage examples for javax.servlet AsyncContext setTimeout
public void setTimeout(long timeout);
From source file:org.apache.karaf.services.mavenproxy.internal.MavenProxyServletTest.java
@Test public void testDownloadMetadata() throws Exception { final String old = System.getProperty("karaf.data"); System.setProperty("karaf.data", new File("target").getCanonicalPath()); FileUtils.deleteDirectory(new File("target/tmp")); Server server = new Server(0); server.setHandler(new AbstractHandler() { @Override/*from w w w . j a v a 2s . c o m*/ public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String result = null; if ("/repo1/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) { result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata>\n" + " <groupId>org.apache.camel</groupId>\n" + " <artifactId>camel-core</artifactId>\n" + " <versioning>\n" + " <latest>2.14.0</latest>\n" + " <release>2.14.0</release>\n" + " <versions>\n" + " <version>1.6.1</version>\n" + " <version>1.6.2</version>\n" + " <version>1.6.3</version>\n" + " <version>1.6.4</version>\n" + " <version>2.0-M2</version>\n" + " <version>2.0-M3</version>\n" + " <version>2.0.0</version>\n" + " <version>2.1.0</version>\n" + " <version>2.2.0</version>\n" + " <version>2.3.0</version>\n" + " <version>2.4.0</version>\n" + " <version>2.5.0</version>\n" + " <version>2.6.0</version>\n" + " <version>2.7.0</version>\n" + " <version>2.7.1</version>\n" + " <version>2.7.2</version>\n" + " <version>2.7.3</version>\n" + " <version>2.7.4</version>\n" + " <version>2.7.5</version>\n" + " <version>2.8.0</version>\n" + " <version>2.8.1</version>\n" + " <version>2.8.2</version>\n" + " <version>2.8.3</version>\n" + " <version>2.8.4</version>\n" + " <version>2.8.5</version>\n" + " <version>2.8.6</version>\n" + " <version>2.9.0-RC1</version>\n" + " <version>2.9.0</version>\n" + " <version>2.9.1</version>\n" + " <version>2.9.2</version>\n" + " <version>2.9.3</version>\n" + " <version>2.9.4</version>\n" + " <version>2.9.5</version>\n" + " <version>2.9.6</version>\n" + " <version>2.9.7</version>\n" + " <version>2.9.8</version>\n" + " <version>2.10.0</version>\n" + " <version>2.10.1</version>\n" + " <version>2.10.2</version>\n" + " <version>2.10.3</version>\n" + " <version>2.10.4</version>\n" + " <version>2.10.5</version>\n" + " <version>2.10.6</version>\n" + " <version>2.10.7</version>\n" + " <version>2.11.0</version>\n" + " <version>2.11.1</version>\n" + " <version>2.11.2</version>\n" + " <version>2.11.3</version>\n" + " <version>2.11.4</version>\n" + " <version>2.12.0</version>\n" + " <version>2.12.1</version>\n" + " <version>2.12.2</version>\n" + " <version>2.12.3</version>\n" + " <version>2.12.4</version>\n" + " <version>2.13.0</version>\n" + " <version>2.13.1</version>\n" + " <version>2.13.2</version>\n" + " <version>2.14.0</version>\n" + " </versions>\n" + " <lastUpdated>20140918132816</lastUpdated>\n" + " </versioning>\n" + "</metadata>\n" + "\n"; } else if ("/repo2/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) { result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata modelVersion=\"1.1.0\">\n" + " <groupId>org.apache.camel</groupId>\n" + " <artifactId>camel-core</artifactId>\n" + " <versioning>\n" + " <latest>2.14.0.redhat-620034</latest>\n" + " <release>2.14.0.redhat-620034</release>\n" + " <versions>\n" + " <version>2.10.0.redhat-60074</version>\n" + " <version>2.12.0.redhat-610312</version>\n" + " <version>2.12.0.redhat-610328</version>\n" + " <version>2.12.0.redhat-610355</version>\n" + " <version>2.12.0.redhat-610378</version>\n" + " <version>2.12.0.redhat-610396</version>\n" + " <version>2.12.0.redhat-610399</version>\n" + " <version>2.12.0.redhat-610401</version>\n" + " <version>2.12.0.redhat-610402</version>\n" + " <version>2.12.0.redhat-611403</version>\n" + " <version>2.12.0.redhat-611405</version>\n" + " <version>2.12.0.redhat-611406</version>\n" + " <version>2.12.0.redhat-611408</version>\n" + " <version>2.12.0.redhat-611409</version>\n" + " <version>2.12.0.redhat-611410</version>\n" + " <version>2.12.0.redhat-611411</version>\n" + " <version>2.12.0.redhat-611412</version>\n" + " <version>2.14.0.redhat-620031</version>\n" + " <version>2.14.0.redhat-620033</version>\n" + " <version>2.14.0.redhat-620034</version>\n" + " </versions>\n" + " <lastUpdated>20141019130841</lastUpdated>\n" + " </versioning>\n" + "</metadata>\n" + "\n"; } if (result == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); baseRequest.setHandled(true); response.getOutputStream().close(); } else { response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getOutputStream().write(result.getBytes()); response.getOutputStream().close(); } } }); server.start(); try { int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort(); // TODO: local repo should point to target/tmp MavenResolver resolver = createResolver("target/tmp", "http://relevant.not/repo1@id=repo1,http://relevant.not/repo2@id=repo2", "http", "localhost", localPort, "fuse", "fuse", null); MavenProxyServlet servlet = new MavenProxyServlet(resolver, 5, null, null, null); AsyncContext context = EasyMock.createMock(AsyncContext.class); HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class); EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/maven-metadata.xml"); // EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/LATEST/camel-core-LATEST.jar"); EasyMock.expect(request.startAsync()).andReturn(context); context.setTimeout(EasyMock.anyInt()); EasyMock.expectLastCall(); HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() { @Override public void write(int b) throws IOException { baos.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { baos.write(b, off, len); } }).anyTimes(); response.setStatus(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentLength(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentType((String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong()); EasyMock.expectLastCall().anyTimes(); response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); final CountDownLatch latch = new CountDownLatch(1); context.complete(); EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { latch.countDown(); return null; } }); EasyMock.makeThreadSafe(context, true); EasyMock.replay(request, response, context); servlet.init(); servlet.doGet(request, response); latch.await(); shaded.org.apache.maven.artifact.repository.metadata.Metadata m = new MetadataXpp3Reader() .read(new ByteArrayInputStream(baos.toByteArray()), false); assertEquals("2.14.0.redhat-620034", m.getVersioning().getLatest()); assertTrue(m.getVersioning().getVersions().contains("2.10.4")); assertTrue(m.getVersioning().getVersions().contains("2.12.0.redhat-610399")); EasyMock.verify(request, response, context); } finally { server.stop(); if (old != null) { System.setProperty("karaf.data", old); } } }
From source file:org.apache.karaf.services.mavenproxy.internal.MavenProxyServletTest.java
private void testDownload(Handler serverHandler) throws Exception { final String old = System.getProperty("karaf.data"); System.setProperty("karaf.data", new File("target").getCanonicalPath()); FileUtils.deleteDirectory(new File("target/tmp")); Server server = new Server(0); server.setHandler(serverHandler);//from w w w . j a va 2 s.co m server.start(); try { int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort(); // TODO: local repo should point to target/tmp MavenResolver resolver = createResolver("target/tmp", "http://relevant.not/maven2@id=central", "http", "localhost", localPort, "fuse", "fuse", null); MavenProxyServlet servlet = new MavenProxyServlet(resolver, 5, null, null, null); AsyncContext context = EasyMock.createMock(AsyncContext.class); HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class); EasyMock.expect(request.getPathInfo()) .andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar"); EasyMock.expect(request.startAsync()).andReturn(context); context.setTimeout(EasyMock.anyInt()); EasyMock.expectLastCall(); HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() { @Override public void write(int b) throws IOException { baos.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { baos.write(b, off, len); } }).anyTimes(); response.setStatus(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentLength(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentType((String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong()); EasyMock.expectLastCall().anyTimes(); response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); final CountDownLatch latch = new CountDownLatch(1); context.complete(); EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() { @Override public Object answer() throws Throwable { latch.countDown(); return null; } }); EasyMock.makeThreadSafe(context, true); EasyMock.replay(request, response, context); servlet.init(); servlet.doGet(request, response); latch.await(); Assert.assertArrayEquals(new byte[] { 0x42 }, baos.toByteArray()); EasyMock.verify(request, response, context); } finally { server.stop(); if (old != null) { System.setProperty("karaf.data", old); } } }
From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java
private synchronized void initializeServer(final ProcessContext context) throws Exception { if (initialized.get()) { return;//from ww w .j ava 2 s . c o m } this.containerQueue = new LinkedBlockingQueue<>(context.getProperty(CONTAINER_QUEUE_SIZE).asInteger()); final String host = context.getProperty(HOSTNAME).getValue(); final int port = context.getProperty(PORT).asInteger(); final SSLContextService sslService = context.getProperty(SSL_CONTEXT) .asControllerService(SSLContextService.class); final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue(); final boolean need; final boolean want; if (CLIENT_NEED.equals(clientAuthValue)) { need = true; want = false; } else if (CLIENT_WANT.equals(clientAuthValue)) { need = false; want = true; } else { need = false; want = false; } final SslContextFactory sslFactory = (sslService == null) ? null : createSslFactory(sslService, need, want); final Server server = new Server(port); // create the http configuration final HttpConfiguration httpConfiguration = new HttpConfiguration(); if (sslFactory == null) { // create the connector final ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration)); // set host and port if (StringUtils.isNotBlank(host)) { http.setHost(host); } http.setPort(port); // add this connector server.setConnectors(new Connector[] { http }); } else { // add some secure config final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration); httpsConfiguration.setSecureScheme("https"); httpsConfiguration.setSecurePort(port); httpsConfiguration.addCustomizer(new SecureRequestCustomizer()); // build the connector final ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslFactory, "http/1.1"), new HttpConnectionFactory(httpsConfiguration)); // set host and port if (StringUtils.isNotBlank(host)) { https.setHost(host); } https.setPort(port); // add this connector server.setConnectors(new Connector[] { https }); } final Set<String> allowedMethods = new HashSet<>(); if (context.getProperty(ALLOW_GET).asBoolean()) { allowedMethods.add("GET"); } if (context.getProperty(ALLOW_POST).asBoolean()) { allowedMethods.add("POST"); } if (context.getProperty(ALLOW_PUT).asBoolean()) { allowedMethods.add("PUT"); } if (context.getProperty(ALLOW_DELETE).asBoolean()) { allowedMethods.add("DELETE"); } if (context.getProperty(ALLOW_HEAD).asBoolean()) { allowedMethods.add("HEAD"); } if (context.getProperty(ALLOW_OPTIONS).asBoolean()) { allowedMethods.add("OPTIONS"); } final String additionalMethods = context.getProperty(ADDITIONAL_METHODS).getValue(); if (additionalMethods != null) { for (final String additionalMethod : additionalMethods.split(",")) { final String trimmed = additionalMethod.trim(); if (!trimmed.isEmpty()) { allowedMethods.add(trimmed.toUpperCase()); } } } final String pathRegex = context.getProperty(PATH_REGEX).getValue(); final Pattern pathPattern = (pathRegex == null) ? null : Pattern.compile(pathRegex); server.setHandler(new AbstractHandler() { @Override public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { final String requestUri = request.getRequestURI(); if (!allowedMethods.contains(request.getMethod().toUpperCase())) { getLogger().info( "Sending back METHOD_NOT_ALLOWED response to {}; method was {}; request URI was {}", new Object[] { request.getRemoteAddr(), request.getMethod(), requestUri }); response.sendError(Status.METHOD_NOT_ALLOWED.getStatusCode()); return; } if (pathPattern != null) { final URI uri; try { uri = new URI(requestUri); } catch (final URISyntaxException e) { throw new ServletException(e); } if (!pathPattern.matcher(uri.getPath()).matches()) { response.sendError(Status.NOT_FOUND.getStatusCode()); getLogger().info("Sending back NOT_FOUND response to {}; request was {} {}", new Object[] { request.getRemoteAddr(), request.getMethod(), requestUri }); return; } } // If destination queues full, send back a 503: Service Unavailable. if (context.getAvailableRelationships().isEmpty()) { response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return; } // Right now, that information, though, is only in the ProcessSession, not the ProcessContext, // so it is not known to us. Should see if it can be added to the ProcessContext. final AsyncContext async = baseRequest.startAsync(); async.setTimeout(Long.MAX_VALUE); // timeout is handled by HttpContextMap final boolean added = containerQueue.offer(new HttpRequestContainer(request, response, async)); if (added) { getLogger().debug("Added Http Request to queue for {} {} from {}", new Object[] { request.getMethod(), requestUri, request.getRemoteAddr() }); } else { getLogger().info("Sending back a SERVICE_UNAVAILABLE response to {}; request was {} {}", new Object[] { request.getRemoteAddr(), request.getMethod(), request.getRemoteAddr() }); response.sendError(Status.SERVICE_UNAVAILABLE.getStatusCode()); response.flushBuffer(); async.complete(); } } }); this.server = server; server.start(); getLogger().info("Server started and listening on port " + getPort()); initialized.set(true); }
From source file:org.apache.vysper.xmpp.extension.xep0124.BoshBackedSessionContext.java
/** * Suspends and enqueues an HTTP request to be used later when an asynchronous message needs to be sent from * the connection manager to the BOSH client. * // w ww .j a v a 2s . c o m * @param req the HTTP request */ public void insertRequest(final BoshRequest br) { final Stanza boshOuterBody = br.getBody(); final Long rid = br.getRid(); LOGGER.debug("SID = " + getSessionId() + " - rid = {} - inserting new BOSH request", rid); // reset the inactivity currentInactivitySeconds = inactivitySeconds; final HttpServletRequest request = br.getHttpServletRequest(); request.setAttribute(BOSH_REQUEST_ATTRIBUTE, br); final AsyncContext context = request.startAsync(); addContinuationExpirationListener(context); context.setTimeout(this.wait * 1000); // allow two more parallel request, be generous in what you receive final int maxToleratedParallelRequests = parallelRequestsCount + 2; synchronized (requestsWindow) { // only allow 'parallelRequestsCount' request to be queued final long highestContinuousRid = requestsWindow.getHighestContinuousRid(); if (highestContinuousRid != -1 && rid > highestContinuousRid + maxToleratedParallelRequests) { LOGGER.warn( "SID = " + getSessionId() + " - rid = {} - received RID >= the permitted window of concurrent requests ({})", rid, highestContinuousRid); // don't queue // queueRequest(br); sendError(br, "item-not-found"); return; } // resend missed responses final boolean resend = rid <= requestsWindow.getCurrentProcessingRequest(); if (resend) { // OLD: if (highestContinuousRid != null && rid <= highestContinuousRid) { synchronized (sentResponses) { if (LOGGER.isInfoEnabled()) { final String pendingRids = requestsWindow.logRequestWindow(); final String sentRids = logSentResponsesBuffer(); LOGGER.info("SID = " + getSessionId() + " - rid = {} - resend request. sent buffer: {} - req.win.: " + pendingRids, rid, sentRids); } if (sentResponses.containsKey(rid)) { LOGGER.info("SID = " + getSessionId() + " - rid = {} (re-sending)", rid); // Resending the old response resendResponse(br); } else { // not in sent responses, try alternatives: backlog and requestWindow final BoshResponse response = sentResponsesBacklog.lookup(rid); if (response != null) { LOGGER.warn( "SID = " + getSessionId() + " - rid = {} - BOSH response retrieved from sentResponsesBacklog", rid); resendResponse(br, rid, response); return; // no error } // rid not in sent responses, nor backlog. check to see if rid is still in requests window boolean inRequestsWindow = requestsWindow.containsRid(rid); if (!inRequestsWindow) { if (LOGGER.isWarnEnabled()) { final String sentRids = logSentResponsesBuffer(); LOGGER.warn( "SID = " + getSessionId() + " - rid = {} - BOSH response not in buffer error - " + sentRids, rid); } } else { if (LOGGER.isWarnEnabled()) { final String sentRids = logSentResponsesBuffer(); LOGGER.warn("SID = " + getSessionId() + " - rid = {} - BOSH response still in requests window - " + sentRids, rid); } } sendError(br, "item-not-found"); } } return; } // check for too many parallel requests final boolean terminate = "terminate".equals(boshOuterBody.getAttributeValue("type")); final boolean pause = boshOuterBody.getAttributeValue("pause") != null; final boolean bodyIsEmpty = boshOuterBody.getInnerElements().isEmpty(); final int distinctRIDs = requestsWindow.getDistinctRIDs(); if (distinctRIDs >= maxToleratedParallelRequests && !terminate && !pause) { LOGGER.warn("SID = " + getSessionId() + " - rid = {} - BOSH Overactivity: Too many simultaneous requests, max = {} " + logRIDSequence(), rid, maxToleratedParallelRequests); sendError(br, "policy-violation"); return; } // check for new request comes early if (distinctRIDs + 1 == maxToleratedParallelRequests && !terminate && !pause && bodyIsEmpty) { final long millisSinceLastCalls = Math .abs(br.getTimestamp() - requestsWindow.getLatestAddionTimestamp()); if (millisSinceLastCalls < pollingSeconds * 1000 && !rid.equals(requestsWindow.getLatestRID())) { LOGGER.warn("SID = " + getSessionId() + " - rid = {} - BOSH Overactivity: Too frequent requests, millis since requests = {}, " + logRIDSequence(), rid, millisSinceLastCalls); sendError(br, "policy-violation"); return; } } // check if ((wait == 0 || hold == 0) && bodyIsEmpty) { final long millisBetweenEmptyReqs = Math .abs(br.getTimestamp() - latestEmptyPollingRequestTimestamp); if (millisBetweenEmptyReqs < pollingSeconds * 1000 && !rid.equals(requestsWindow.getLatestRID())) { LOGGER.warn("SID = " + getSessionId() + " - rid = {} - BOSH Overactivity for polling: Too frequent requests, millis since requests = {}, " + logRIDSequence(), rid, millisBetweenEmptyReqs); sendError(br, "policy-violation"); return; } latestEmptyPollingRequestTimestamp = br.getTimestamp(); } queueRequest(br); } if (isClientAcknowledgements()) { synchronized (sentResponses) { if (boshOuterBody.getAttribute("ack") == null) { // if there is no ack attribute present then the client confirmed it received all the responses to all the previous requests // and we clear the cache sentResponsesBacklog.addAll(sentResponses); sentResponses.clear(); } else if (!sentResponses.isEmpty()) { // After receiving a request with an 'ack' value less than the 'rid' of the last request that it has already responded to, // the connection manager MAY inform the client of the situation. In this case it SHOULD include a 'report' attribute set // to one greater than the 'ack' attribute it received from the client, and a 'time' attribute set to the number of milliseconds // since it sent the response associated with the 'report' attribute. long ack = Long.parseLong(boshOuterBody.getAttributeValue("ack")); if (ack < sentResponses.lastKey() && sentResponses.containsKey(ack + 1)) { long delta = System.currentTimeMillis() - sentResponses.get(ack + 1).getTimestamp(); if (delta >= brokenConnectionReportTimeoutMillis) { sendBrokenConnectionReport(ack + 1, delta); return; } } } } } // we cannot pause if there are missing requests, this is tested with // br.getRid().equals(requestsWindow.lastKey()) && highestContinuousRid.equals(br.getRid()) synchronized (requestsWindow) { final String pauseAttribute = boshOuterBody.getAttributeValue("pause"); if (pauseAttribute != null && rid.equals(requestsWindow.getLatestRID()) && rid.equals(requestsWindow.getHighestContinuousRid())) { int pause; try { pause = Integer.parseInt(pauseAttribute); } catch (NumberFormatException e) { queueRequest(br); sendError("bad-request"); return; } pause = Math.max(0, pause); pause = Math.min(pause, maxpauseSeconds); respondToPause(pause); return; } } // If there are delayed responses waiting to be sent to the BOSH client, then we wrap them all in // a <body/> element and send them as a HTTP response to the current HTTP request. Stanza delayedResponse; ArrayList<Stanza> mergeCandidates = null; // do not create until there is a delayed response while ((delayedResponse = delayedResponseQueue.poll()) != null) { if (mergeCandidates == null) mergeCandidates = new ArrayList<Stanza>(); mergeCandidates.add(delayedResponse); } Stanza mergedResponse = BoshStanzaUtils.mergeResponses(mergeCandidates); if (mergedResponse != null) { LOGGER.debug("SID = " + getSessionId() + " - writing merged response. stanzas merged = " + mergeCandidates.size()); writeBoshResponse(mergedResponse); return; } // If there are more suspended enqueued requests than it is allowed by the BOSH 'hold' parameter, // than we release the oldest one by sending an empty response. if (requestsWindow.size() > hold) { writeBoshResponse(BoshStanzaUtils.EMPTY_BOSH_RESPONSE); } }
From source file:org.apache.vysper.xmpp.extension.xep0124.BoshBackedSessionContextTest.java
@Test public void testWrite0() { HttpServletRequest httpServletRequest = mocksControl.createMock(HttpServletRequest.class); AsyncContext asyncContext = mocksControl.createMock(AsyncContext.class); expect(httpServletRequest.startAsync()).andReturn(asyncContext); expectLastCall().atLeastOnce();//from w ww . ja va 2s . c o m expect(httpServletRequest.getAsyncContext()).andReturn(asyncContext); expectLastCall().atLeastOnce(); asyncContext.setTimeout(anyLong()); asyncContext.dispatch(); expectLastCall().atLeastOnce(); httpServletRequest.setAttribute(eq(BOSH_REQUEST_ATTRIBUTE), EasyMock.<BoshRequest>notNull()); asyncContext.addListener(EasyMock.<AsyncListener>anyObject()); Capture<BoshResponse> captured = new Capture<BoshResponse>(); httpServletRequest.setAttribute(eq(BOSH_RESPONSE_ATTRIBUTE), EasyMock.<BoshResponse>capture(captured)); mocksControl.replay(); BoshBackedSessionContext boshBackedSessionContext = new BoshBackedSessionContext(serverRuntimeContext, null, inactivityChecker); Stanza body = BoshStanzaUtils.EMPTY_BOSH_RESPONSE; boshBackedSessionContext.insertRequest(new BoshRequest(httpServletRequest, body, 1L)); boshBackedSessionContext.writeBoshResponse(body); mocksControl.verify(); BoshResponse boshResponse = captured.getValue(); assertEquals(BoshServlet.XML_CONTENT_TYPE, boshResponse.getContentType()); assertEquals(new Renderer(body).getComplete(), new String(boshResponse.getContent())); }
From source file:org.apache.vysper.xmpp.extension.xep0124.BoshBackedSessionContextTest.java
@Test public void testRequestExpired() throws IOException { Stanza emtpyStanza = BoshStanzaUtils.EMPTY_BOSH_RESPONSE; // addRequest HttpServletRequest httpServletRequest = mocksControl.createMock(HttpServletRequest.class); AsyncContext asyncContext = mocksControl.createMock(AsyncContext.class); expect(httpServletRequest.startAsync()).andReturn(asyncContext).atLeastOnce(); expect(httpServletRequest.getAsyncContext()).andReturn(asyncContext).atLeastOnce(); asyncContext.setTimeout(anyLong()); httpServletRequest.setAttribute(eq(BOSH_REQUEST_ATTRIBUTE), EasyMock.<BoshRequest>notNull()); expect(asyncContext.getRequest()).andReturn(httpServletRequest).atLeastOnce(); asyncContext.dispatch();//from w ww .j av a2 s.c o m expectLastCall().atLeastOnce(); Capture<AsyncListener> listenerCaptured = new Capture<AsyncListener>(); asyncContext.addListener(EasyMock.<AsyncListener>capture(listenerCaptured)); AsyncEvent asyncEvent = mocksControl.createMock(AsyncEvent.class); BoshRequest br = new BoshRequest(httpServletRequest, emtpyStanza, 1L); // requestExpired expect(httpServletRequest.getAttribute(BOSH_REQUEST_ATTRIBUTE)).andReturn(br); Capture<BoshResponse> responseCaptured = new Capture<BoshResponse>(); httpServletRequest.setAttribute(eq(BOSH_RESPONSE_ATTRIBUTE), EasyMock.<BoshResponse>capture(responseCaptured)); // write0 mocksControl.replay(); BoshBackedSessionContext boshBackedSessionContext = new BoshBackedSessionContext(serverRuntimeContext, null, inactivityChecker); boshBackedSessionContext.insertRequest(br); listenerCaptured.getValue().onTimeout(asyncEvent); mocksControl.verify(); assertEquals(new Renderer(emtpyStanza).getComplete(), new String(responseCaptured.getValue().getContent())); assertEquals(BoshServlet.XML_CONTENT_TYPE, responseCaptured.getValue().getContentType()); }
From source file:org.apache.vysper.xmpp.extension.xep0124.BoshBackedSessionContextTest.java
@Test public void testAddRequest() { // addRequest HttpServletRequest httpServletRequest1 = mocksControl.createMock(HttpServletRequest.class); HttpServletRequest httpServletRequest2 = mocksControl.createMock(HttpServletRequest.class); AsyncContext asyncContext1 = mocksControl.createMock(AsyncContext.class); AsyncContext asyncContext2 = mocksControl.createMock(AsyncContext.class); BoshStanzaUtils boshStanzaUtils = mocksControl.createMock(BoshStanzaUtils.class); expect(httpServletRequest1.startAsync()).andReturn(asyncContext1).atLeastOnce(); expect(httpServletRequest1.getAsyncContext()).andReturn(asyncContext1).atLeastOnce(); expect(httpServletRequest2.startAsync()).andReturn(asyncContext2).atLeastOnce(); expect(httpServletRequest2.getAsyncContext()).andReturn(asyncContext2).anyTimes(); asyncContext1.setTimeout(anyLong()); Capture<BoshRequest> br1 = new Capture<BoshRequest>(); httpServletRequest1.setAttribute(eq(BOSH_REQUEST_ATTRIBUTE), EasyMock.<BoshRequest>capture(br1)); asyncContext2.setTimeout(anyLong()); Capture<BoshRequest> br2 = new Capture<BoshRequest>(); httpServletRequest2.setAttribute(eq(BOSH_REQUEST_ATTRIBUTE), EasyMock.<BoshRequest>capture(br2)); asyncContext1.addListener(EasyMock.<AsyncListener>anyObject()); asyncContext2.addListener(EasyMock.<AsyncListener>anyObject()); asyncContext1.dispatch();//from w w w.j ava2 s. c o m expectLastCall().atLeastOnce(); Stanza body = BoshStanzaUtils.EMPTY_BOSH_RESPONSE; // write0 Capture<BoshResponse> captured = new Capture<BoshResponse>(); httpServletRequest1.setAttribute(eq(BOSH_RESPONSE_ATTRIBUTE), EasyMock.<BoshResponse>capture(captured)); mocksControl.replay(); BoshBackedSessionContext boshBackedSessionContext = new BoshBackedSessionContext(serverRuntimeContext, null, inactivityChecker); boshBackedSessionContext.setHold(2); // consecutive writes with RID 1 and 2 long maxRID = 2L; boshBackedSessionContext.insertRequest(new BoshRequest(httpServletRequest1, body, 1L)); boshBackedSessionContext.insertRequest(new BoshRequest(httpServletRequest2, body, maxRID)); boshBackedSessionContext.writeBoshResponse(body); mocksControl.verify(); assertEquals(httpServletRequest1, br1.getValue().getHttpServletRequest()); assertEquals(httpServletRequest2, br2.getValue().getHttpServletRequest()); // expect ack for newest/largest RID final Stanza ackedResponse = BoshStanzaUtils.addAttribute(body, "ack", Long.toString(maxRID)); assertEquals(new Renderer(ackedResponse).getComplete(), new String(captured.getValue().getContent())); assertEquals(BoshServlet.XML_CONTENT_TYPE, captured.getValue().getContentType()); }
From source file:org.apache.vysper.xmpp.extension.xep0124.BoshBackedSessionContextTest.java
@Test public void testAddRequestWithDelayedResponses() { HttpServletRequest httpServletRequest = mocksControl.createMock(HttpServletRequest.class); AsyncContext asyncContext = mocksControl.createMock(AsyncContext.class); expect(httpServletRequest.startAsync()).andReturn(asyncContext).atLeastOnce(); expect(httpServletRequest.getAsyncContext()).andReturn(asyncContext).atLeastOnce(); asyncContext.setTimeout(anyLong()); httpServletRequest.setAttribute(eq(BOSH_REQUEST_ATTRIBUTE), EasyMock.<BoshRequest>notNull()); asyncContext.addListener(EasyMock.<AsyncListener>anyObject()); asyncContext.dispatch();/* www . j ava2 s .com*/ expectLastCall().atLeastOnce(); Stanza body = BoshStanzaUtils.createBoshStanzaBuilder().startInnerElement("presence").endInnerElement() .build(); Capture<BoshResponse> captured = new Capture<BoshResponse>(); httpServletRequest.setAttribute(eq(BOSH_RESPONSE_ATTRIBUTE), EasyMock.<BoshResponse>capture(captured)); mocksControl.replay(); BoshBackedSessionContext boshBackedSessionContext = new BoshBackedSessionContext(serverRuntimeContext, null, inactivityChecker); boshBackedSessionContext.writeBoshResponse(body); // queued for merging boshBackedSessionContext.writeBoshResponse(body); // queued for merging boshBackedSessionContext.writeBoshResponse(body); // queued for merging boshBackedSessionContext.insertRequest(new BoshRequest(httpServletRequest, body, 1L)); mocksControl.verify(); final String mergedAllBodiesStanza = new String(captured.getValue().getContent()); assertEquals(3, StringUtils.countMatches(mergedAllBodiesStanza, "<presence")); }
From source file:org.haiku.haikudepotserver.job.controller.JobController.java
/** * <p>This URL can be used to download job data that has resulted from a job being run.</p> *//*from w w w .j a va 2 s .c o m*/ @RequestMapping(value = "/" + SEGMENT_JOBDATA + "/{" + KEY_GUID + "}/" + SEGMENT_DOWNLOAD, method = RequestMethod.GET) public void downloadGeneratedData(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = KEY_GUID) String guid) throws IOException { Preconditions.checkArgument(PATTERN_GUID.matcher(guid).matches(), "the supplied guid does not match the required pattern"); ObjectContext context = serverRuntime.newContext(); JobSnapshot job = jobService.tryGetJobForData(guid).orElseThrow(() -> { LOGGER.warn("attempt to access job data {} for which no job exists", guid); return new JobDataAuthorizationFailure(); }); // If there is no user who is assigned to the job then the job is for nobody in particular and is thereby // secured by the GUID of the job's data; if you know the GUID then you can have the data. if (!Strings.isNullOrEmpty(job.getOwnerUserNickname())) { User user = tryObtainAuthenticatedUser(context).orElseThrow(() -> { LOGGER.warn("attempt to obtain job data {} with no authenticated user", guid); return new JobDataAuthorizationFailure(); }); User ownerUser = User.tryGetByNickname(context, job.getOwnerUserNickname()).orElseThrow(() -> { LOGGER.warn("owner of job does not seem to exist; {}", job.getOwnerUserNickname()); return new JobDataAuthorizationFailure(); }); if (!authorizationService.check(context, user, ownerUser, Permission.USER_VIEWJOBS)) { LOGGER.warn("attempt to access jobs view for; {}", job.toString()); throw new JobDataAuthorizationFailure(); } } else { LOGGER.debug("access to job [{}] allowed for unauthenticated access", job.toString()); } JobDataWithByteSource jobDataWithByteSink = jobService.tryObtainData(guid).orElseThrow(() -> { LOGGER.warn("requested job data {} not found", guid); return new JobDataAuthorizationFailure(); }); // finally access has been checked and the logic can move onto actual // delivery of the material. JobData jobData = jobDataWithByteSink.getJobData(); if (!Strings.isNullOrEmpty(jobData.getMediaTypeCode())) { response.setContentType(jobData.getMediaTypeCode()); } else { response.setContentType(MediaType.OCTET_STREAM.toString()); } response.setContentType(MediaType.CSV_UTF_8.toString()); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + jobService.deriveDataFilename(guid)); response.setDateHeader(HttpHeaders.EXPIRES, 0); response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache"); // now switch to async for the delivery of the data. AsyncContext async = request.startAsync(); async.setTimeout(TIMEOUT_DOWNLOAD_MILLIS); ServletOutputStream outputStream = response.getOutputStream(); outputStream.setWriteListener(new JobDataWriteListener(guid, jobService, async, outputStream)); LOGGER.info("did start async stream job data; {}", guid); }
From source file:org.springframework.http.server.reactive.ServletHttpHandlerAdapter.java
@Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (DispatcherType.ASYNC.equals(request.getDispatcherType())) { Throwable ex = (Throwable) request.getAttribute(WRITE_ERROR_ATTRIBUTE_NAME); throw new ServletException("Write publisher error", ex); }/*from ww w. j a v a 2 s . com*/ // Start async before Read/WriteListener registration AsyncContext asyncContext = request.startAsync(); asyncContext.setTimeout(-1); ServerHttpRequest httpRequest = createRequest(((HttpServletRequest) request), asyncContext); ServerHttpResponse httpResponse = createResponse(((HttpServletResponse) response), asyncContext); if (HttpMethod.HEAD.equals(httpRequest.getMethod())) { httpResponse = new HttpHeadResponseDecorator(httpResponse); } AtomicBoolean isCompleted = new AtomicBoolean(); HandlerResultAsyncListener listener = new HandlerResultAsyncListener(isCompleted); asyncContext.addListener(listener); HandlerResultSubscriber subscriber = new HandlerResultSubscriber(asyncContext, isCompleted); this.httpHandler.handle(httpRequest, httpResponse).subscribe(subscriber); }