List of usage examples for javax.servlet.http HttpServletRequest startAsync
public AsyncContext startAsync() throws IllegalStateException;
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 w w . j ava2 s. c om*/ 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());/*w ww . j a va 2 s . c om*/ httpServletRequest.setAttribute(eq(BOSH_REQUEST_ATTRIBUTE), EasyMock.<BoshRequest>notNull()); expect(asyncContext.getRequest()).andReturn(httpServletRequest).atLeastOnce(); asyncContext.dispatch(); 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();/* ww w . ja va 2 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());/*from www . jav a2 s. c o m*/ httpServletRequest.setAttribute(eq(BOSH_REQUEST_ATTRIBUTE), EasyMock.<BoshRequest>notNull()); asyncContext.addListener(EasyMock.<AsyncListener>anyObject()); asyncContext.dispatch(); 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 ww w . j a v a2s . co 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.structr.pdf.servlet.PdfServlet.java
@Override protected void renderAsyncOutput(HttpServletRequest request, HttpServletResponse response, App app, RenderContext renderContext, DOMNode rootElement) throws IOException { final AsyncContext async = request.startAsync(); final ServletOutputStream out = async.getResponse().getOutputStream(); final AtomicBoolean finished = new AtomicBoolean(false); final DOMNode rootNode = rootElement; response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment;filename=\"FileName.pdf\""); threadPool.submit(new Runnable() { @Override//from w w w .ja va2 s .co m public void run() { try (final Tx tx = app.tx()) { // render rootNode.render(renderContext, 0); finished.set(true); tx.success(); } catch (Throwable t) { t.printStackTrace(); logger.warn("Error while rendering page {}: {}", rootNode.getName(), t.getMessage()); try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); finished.set(true); } catch (IOException ex) { logger.warn("", ex); } } } }); // start output write listener out.setWriteListener(new WriteListener() { @Override public void onWritePossible() throws IOException { try { final Queue<String> queue = renderContext.getBuffer().getQueue(); String pageContent = ""; while (out.isReady()) { String buffer = null; synchronized (queue) { buffer = queue.poll(); } if (buffer != null) { pageContent += buffer; } else { if (finished.get()) { // TODO: implement parameters for wkhtmltopdf in settings Pdf pdf = new Pdf(); pdf.addPageFromString(pageContent); out.write(pdf.getPDF()); async.complete(); // prevent this block from being called again break; } Thread.sleep(1); } } } catch (EofException ee) { logger.warn( "Could not flush the response body content to the client, probably because the network connection was terminated."); } catch (IOException | InterruptedException t) { logger.warn("Unexpected exception", t); } } @Override public void onError(Throwable t) { if (t instanceof EofException) { logger.warn( "Could not flush the response body content to the client, probably because the network connection was terminated."); } else { logger.warn("Unexpected exception", t); } } }); }
From source file:org.structr.web.servlet.HtmlServlet.java
@Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) { final Authenticator auth = getConfig().getAuthenticator(); List<Page> pages = null; boolean requestUriContainsUuids = false; SecurityContext securityContext;//from ww w. j av a 2 s .c om final App app; try { final String path = request.getPathInfo(); // check for registration (has its own tx because of write access if (checkRegistration(auth, request, response, path)) { return; } // check for registration (has its own tx because of write access if (checkResetPassword(auth, request, response, path)) { return; } // isolate request authentication in a transaction try (final Tx tx = StructrApp.getInstance().tx()) { securityContext = auth.initializeAndExamineRequest(request, response); tx.success(); } app = StructrApp.getInstance(securityContext); try (final Tx tx = app.tx()) { // Ensure access mode is frontend securityContext.setAccessMode(AccessMode.Frontend); request.setCharacterEncoding("UTF-8"); // Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4 response.setCharacterEncoding("UTF-8"); boolean dontCache = false; logger.log(Level.FINE, "Path info {0}", path); // don't continue on redirects if (response.getStatus() == 302) { tx.success(); return; } final Principal user = securityContext.getUser(false); if (user != null) { // Don't cache if a user is logged in dontCache = true; } final RenderContext renderContext = RenderContext.getInstance(securityContext, request, response); renderContext.setResourceProvider(config.getResourceProvider()); final EditMode edit = renderContext.getEditMode(user); DOMNode rootElement = null; AbstractNode dataNode = null; final String[] uriParts = PathHelper.getParts(path); if ((uriParts == null) || (uriParts.length == 0)) { // find a visible page rootElement = findIndexPage(securityContext, pages, edit); logger.log(Level.FINE, "No path supplied, trying to find index page"); } else { if (rootElement == null) { rootElement = findPage(securityContext, pages, path, edit); } else { dontCache = true; } } if (rootElement == null) { // No page found // Look for a file final File file = findFile(securityContext, request, path); if (file != null) { streamFile(securityContext, file, request, response, edit); tx.success(); return; } // store remaining path parts in request final Matcher matcher = threadLocalUUIDMatcher.get(); for (int i = 0; i < uriParts.length; i++) { request.setAttribute(uriParts[i], i); matcher.reset(uriParts[i]); // set to "true" if part matches UUID pattern requestUriContainsUuids |= matcher.matches(); } if (!requestUriContainsUuids) { // Try to find a data node by name dataNode = findFirstNodeByName(securityContext, request, path); } else { dataNode = findNodeByUuid(securityContext, PathHelper.getName(path)); } //if (dataNode != null && !(dataNode instanceof Linkable)) { if (dataNode != null) { // Last path part matches a data node // Remove last path part and try again searching for a page // clear possible entry points request.removeAttribute(POSSIBLE_ENTRY_POINTS_KEY); rootElement = findPage(securityContext, pages, StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP), edit); renderContext.setDetailsDataObject(dataNode); // Start rendering on data node if (rootElement == null && dataNode instanceof DOMNode) { rootElement = ((DOMNode) dataNode); } } } // look for pages with HTTP Basic Authentication (must be done as superuser) if (rootElement == null) { final HttpBasicAuthResult authResult = checkHttpBasicAuth(request, response, path); switch (authResult.authState()) { // Element with Basic Auth found and authentication succeeded case Authenticated: final Linkable result = authResult.getRootElement(); if (result instanceof Page) { rootElement = (DOMNode) result; securityContext = authResult.getSecurityContext(); renderContext.pushSecurityContext(securityContext); } else if (result instanceof File) { streamFile(authResult.getSecurityContext(), (File) result, request, response, EditMode.NONE); tx.success(); return; } break; // Page with Basic Auth found but not yet authenticated case MustAuthenticate: tx.success(); return; // no Basic Auth for given path, go on case NoBasicAuth: break; } } // Still nothing found, do error handling if (rootElement == null) { rootElement = notFound(response, securityContext); } if (rootElement == null) { tx.success(); return; } // check dont cache flag on page (if root element is a page) // but don't modify true to false dontCache |= rootElement.getProperty(Page.dontCache); if (EditMode.WIDGET.equals(edit) || dontCache) { setNoCacheHeaders(response); } if (!securityContext.isVisible(rootElement)) { rootElement = notFound(response, securityContext); if (rootElement == null) { tx.success(); return; } } else { if (!EditMode.WIDGET.equals(edit) && !dontCache && notModifiedSince(request, response, rootElement, dontCache)) { ServletOutputStream out = response.getOutputStream(); out.flush(); //response.flushBuffer(); out.close(); } else { // prepare response response.setCharacterEncoding("UTF-8"); String contentType = rootElement.getProperty(Page.contentType); if (contentType == null) { // Default contentType = "text/html;charset=UTF-8"; } if (contentType.equals("text/html")) { contentType = contentType.concat(";charset=UTF-8"); } response.setContentType(contentType); setCustomResponseHeaders(response); final boolean createsRawData = rootElement.getProperty(Page.pageCreatesRawData); // async or not? if (isAsync && !createsRawData) { final AsyncContext async = request.startAsync(); final ServletOutputStream out = async.getResponse().getOutputStream(); final AtomicBoolean finished = new AtomicBoolean(false); final DOMNode rootNode = rootElement; threadPool.submit(new Runnable() { @Override public void run() { try (final Tx tx = app.tx()) { //final long start = System.currentTimeMillis(); // render rootNode.render(renderContext, 0); finished.set(true); //final long end = System.currentTimeMillis(); //System.out.println("Done in " + (end-start) + " ms"); tx.success(); } catch (Throwable t) { t.printStackTrace(); final String errorMsg = t.getMessage(); try { //response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMsg); finished.set(true); } catch (IOException ex) { ex.printStackTrace(); } } } }); // start output write listener out.setWriteListener(new WriteListener() { @Override public void onWritePossible() throws IOException { try { final Queue<String> queue = renderContext.getBuffer().getQueue(); while (out.isReady()) { String buffer = null; synchronized (queue) { buffer = queue.poll(); } if (buffer != null) { out.print(buffer); } else { if (finished.get()) { async.complete(); response.setStatus(HttpServletResponse.SC_OK); // prevent this block from being called again break; } Thread.sleep(1); } } } catch (Throwable t) { t.printStackTrace(); } } @Override public void onError(Throwable t) { t.printStackTrace(); } }); } else { final StringRenderBuffer buffer = new StringRenderBuffer(); renderContext.setBuffer(buffer); // render rootElement.render(renderContext, 0); try { response.getOutputStream().write(buffer.getBuffer().toString().getBytes("utf-8")); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (IOException ioex) { ioex.printStackTrace(); } } } } tx.success(); } catch (FrameworkException fex) { fex.printStackTrace(); logger.log(Level.SEVERE, "Exception while processing request", fex); } } catch (IOException | FrameworkException t) { t.printStackTrace(); logger.log(Level.SEVERE, "Exception while processing request", t); UiAuthenticator.writeInternalServerError(response); } }