List of usage examples for javax.servlet.http HttpServletResponse flushBuffer
public void flushBuffer() throws IOException;
From source file:cz.zcu.kiv.eegdatabase.logic.pdf.ReservationPDF.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { try {/*from w w w . j a va 2 s .co m*/ if (request.getParameter("type").compareTo("single") == 0) { int id = Integer.parseInt(request.getParameter("reservationId")); Reservation reservation = reservationDao.getReservationById(id); response.setHeader("Content-Type", "application/pdf"); response.setHeader("Content-Disposition", "attachment;filename=reservation-" + id + ".pdf"); Document document = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); document.open(); PDFUtils utils = new PDFUtils(getServletContext().getRealPath("/")); document.add(utils.setHeader(document, "Reservation listing")); /*Paragraph paragraph = new Paragraph("Reservation #" + id, FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, BaseColor.BLACK)); paragraph.setAlignment(Element.ALIGN_CENTER); paragraph.setSpacingBefore(10); paragraph.setSpacingAfter(10); document.add(paragraph);*/ document.add(formatReservation(reservation)); document.close(); response.flushBuffer(); return null; } if (request.getParameter("type").compareTo("range") == 0) { String date = request.getParameter("date") + " 00:00:00"; GregorianCalendar rangeStart = BookingRoomUtils.getCalendar(date); int length = Integer.parseInt(request.getParameter("length")); GregorianCalendar rangeEnd = (GregorianCalendar) rangeStart.clone(); rangeEnd.add(Calendar.DAY_OF_YEAR, length); response.setHeader("Content-Type", "application/pdf"); response.setHeader("Content-Disposition", "attachment;filename=reservations.pdf"); Document document = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); document.open(); PDFUtils utils = new PDFUtils(getServletContext().getRealPath("/")); document.add(utils.setHeader(document, "Reservations listing")); java.util.List<Reservation> reservations = reservationDao.getReservationsBetween(rangeStart, rangeEnd, "", 0); int count = 0; for (Reservation reservation : reservations) { document.add(formatReservation(reservation)); if (++count % 6 == 0) { document.newPage(); document.add(utils.setHeader(document, "Reservations listing")); } } document.close(); response.flushBuffer(); return null; } return null; } catch (Exception e) { ModelAndView mav = new ModelAndView(getFormView()); Map data = new HashMap<String, Object>(); data.put("error", e.getMessage()); mav.addAllObjects(data); return mav; } }
From source file:com.redblackit.web.server.EchoServlet.java
/** * doEcho/* ww w. ja v a 2 s . c o m*/ * * <ul> * <li>Log method, URL, headers, body</li> * <li>Replicate request headers, except for setting location to received * URL</li> * <li>Replicate request body in response</li> * </ul> * * @param req * @param resp * @param method */ @SuppressWarnings("rawtypes") private void doEcho(HttpServletRequest req, HttpServletResponse resp, String method) throws IOException { String reqURI = req.getRequestURI(); logger.debug(this.getClass().getName() + ":" + method + " - " + reqURI); for (Enumeration hdrse = req.getHeaderNames(); hdrse.hasMoreElements();) { String headerName = (String) hdrse.nextElement(); int hnct = 0; for (Enumeration hdre = req.getHeaders(headerName); hdre.hasMoreElements();) { String headerValue = (String) hdre.nextElement(); logger.debug( this.getClass().getName() + ": header[" + headerName + "," + hnct + "]=" + headerValue); if (!headerName.equals("Location")) { resp.addHeader(headerName, headerValue); } hnct++; } if (hnct == 0) { resp.setHeader(headerName, ""); logger.info(this.getClass().getName() + ": header[" + headerName + "," + hnct + "]='' (empty)"); } } resp.setHeader("Location", reqURI); resp.setStatus(HttpServletResponse.SC_OK); if (req.getContentLength() > 0 && !(method.equals("HEAD") || method.equals("DELETE"))) { String body = FileCopyUtils.copyToString(req.getReader()); logger.debug(this.getClass().getName() + ": body>>\n" + body + "\nbody<<"); FileCopyUtils.copy(body, resp.getWriter()); resp.flushBuffer(); resp.setContentLength(req.getContentLength()); } else { logger.debug(this.getClass().getName() + ": body is empty"); resp.setContentLength(0); } }
From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java
public void handleMove(HttpServletRequest request, HttpServletResponse response, String pathInContext, Resource resource) throws ServletException, IOException { if (!resource.exists() || !passConditionalHeaders(request, response, resource)) return;/*from www . ja v a2 s. c om*/ String newPath = URI.canonicalPath(request.getHeader("new-uri")); if (newPath == null) { response.sendError(HttpResponse.__400_Bad_Request, "No new-uri"); return; } String contextPath = _httpContext.getContextPath(); if (contextPath != null && !newPath.startsWith(contextPath)) { response.sendError(HttpResponse.__405_Method_Not_Allowed, "Not in context"); return; } try { String newInfo = newPath; if (contextPath != null) newInfo = newInfo.substring(contextPath.length()); Resource newFile = _httpContext.getBaseResource().addPath(newInfo); resource.renameTo(newFile); response.setStatus(HttpResponse.__204_No_Content); response.flushBuffer(); } catch (Exception ex) { log.warn(LogSupport.EXCEPTION, ex); response.sendError(HttpResponse.__500_Internal_Server_Error, "Error:" + ex); return; } }
From source file:org.jasig.cas.support.pac4j.web.flow.ClientAction.java
/** * {@inheritDoc}//from w w w .java 2 s . c om */ @Override protected Event doExecute(final RequestContext context) throws Exception { final HttpServletRequest request = WebUtils.getHttpServletRequest(context); final HttpServletResponse response = WebUtils.getHttpServletResponse(context); final HttpSession session = request.getSession(); // web context final WebContext webContext = new J2EContext(request, response); // get client final String clientName = request.getParameter(this.clients.getClientNameParameter()); logger.debug("clientName: {}", clientName); // it's an authentication if (StringUtils.isNotBlank(clientName)) { // get client final BaseClient<Credentials, CommonProfile> client = (BaseClient<Credentials, CommonProfile>) this.clients .findClient(clientName); logger.debug("client: {}", client); // Only supported protocols final Mechanism mechanism = client.getMechanism(); if (!SUPPORTED_PROTOCOLS.contains(mechanism)) { throw new TechnicalException("Only CAS, OAuth, OpenID and SAML protocols are supported: " + client); } // get credentials final Credentials credentials; try { credentials = client.getCredentials(webContext); logger.debug("credentials: {}", credentials); } catch (final RequiresHttpAction e) { logger.debug("requires http action: {}", e); response.flushBuffer(); final ExternalContext externalContext = ExternalContextHolder.getExternalContext(); externalContext.recordResponseComplete(); return new Event(this, "stop"); } // retrieve parameters from web session final Service service = (Service) session.getAttribute(SERVICE); context.getFlowScope().put(SERVICE, service); logger.debug("retrieve service: {}", service); if (service != null) { request.setAttribute(SERVICE, service.getId()); } restoreRequestAttribute(request, session, THEME); restoreRequestAttribute(request, session, LOCALE); restoreRequestAttribute(request, session, METHOD); // credentials not null -> try to authenticate if (credentials != null) { final TicketGrantingTicket tgt = this.centralAuthenticationService .createTicketGrantingTicket(new ClientCredential(credentials)); WebUtils.putTicketGrantingTicketInScopes(context, tgt); return success(); } } // no or aborted authentication : go to login page prepareForLoginPage(context); return error(); }
From source file:architecture.ee.web.spring.controller.DownloadController.java
@RequestMapping(value = "/images/{imageId:[\\p{Digit}]+}/{filename:.+}", method = RequestMethod.GET) @ResponseBody//from ww w.ja va2s. c o m public void donwloadImage(@PathVariable("imageId") Long imageId, @PathVariable("filename") String filename, @RequestParam(value = "width", defaultValue = "0", required = false) Integer width, @RequestParam(value = "height", defaultValue = "0", required = false) Integer height, HttpServletResponse response) throws IOException { try { if (imageId > 0 && StringUtils.isNotEmpty(filename)) { Image image = imageManager.getImage(imageId); User user = SecurityHelper.getUser(); if (hasPermissions(image, user) && StringUtils.equals(filename, image.getName())) { InputStream input; String contentType; int contentLength; if (width > 0 && width > 0) { input = imageManager.getImageThumbnailInputStream(image, width, height); contentType = image.getThumbnailContentType(); contentLength = image.getThumbnailSize(); } else { input = imageManager.getImageInputStream(image); contentType = image.getContentType(); contentLength = image.getSize(); } response.setContentType(contentType); response.setContentLength(contentLength); IOUtils.copy(input, response.getOutputStream()); response.flushBuffer(); } else { throw new NotFoundException(); } } else { throw new NotFoundException(); } } catch (NotFoundException e) { response.sendError(404); } }
From source file:org.apache.sling.auth.core.impl.HttpBasicAuthenticationHandler.java
/** * Sends status <code>401</code> (Unauthorized) with a * <code>WWW-Authenticate</code> requesting standard HTTP header * authentication with the <code>Basic</code> scheme and the configured * realm name./*from w w w . ja v a2 s.c o m*/ * * @param response The response object to which to send the request * @return <code>true</code> if the 401/UNAUTHORIZED method has successfully * been sent and the response has been committed. */ boolean sendUnauthorized(HttpServletResponse response) { if (response.isCommitted()) { log.error("sendUnauthorized: Cannot send 401/UNAUTHORIZED; response is already committed"); } else { response.resetBuffer(); /* * TODO: Check whether we have to redirect * If this is a GET request not targeted at the registration path * for which this handler is selected we have to redirect to the * registration path using either the provided resource attribute * or parameter or the current URL as the "resource" parameter * for the redirect and also setting the "sling:authRequestLogin" * parameter to "BASIC" to get the 401 response for the registration * path and redirect back to actual path afterwards. */ // just set the status because this may be called as part of an // error handler in which case sendError would result in an error // handler loop and thus be ignored. response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setHeader(HEADER_WWW_AUTHENTICATE, AUTHENTICATION_SCHEME_BASIC + " realm=\"" + this.realm + "\""); try { response.flushBuffer(); return true; } catch (IOException ioe) { log.error("sendUnauthorized: Failed requesting authentication", ioe); } } return false; }
From source file:org.eclipse.vorto.repository.web.ModelRepositoryController.java
@ApiOperation(value = "Getting all mapped Resources") @RequestMapping(value = "/mapping/zip/{namespace}/{name}/{version:.+}/{targetPlatform}", method = RequestMethod.GET) public void getMappingResources( @ApiParam(value = "Namespace", required = true) final @PathVariable String namespace, @ApiParam(value = "Name", required = true) final @PathVariable String name, @ApiParam(value = "Version", required = true) final @PathVariable String version, @ApiParam(value = "Target Platform", required = true) final @PathVariable String targetPlatform, @ApiParam(value = "Response", required = true) final HttpServletResponse response) { Objects.requireNonNull(namespace, "namespace must not be null"); Objects.requireNonNull(name, "name must not be null"); Objects.requireNonNull(version, "version must not be null"); final ModelId modelId = new ModelId(name, namespace, version); List<ModelResource> mappingResources = modelRepository.getMappingModelsForTargetPlatform(modelId, targetPlatform);// www . ja v a 2 s . co m ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); final ContentType contentType = ContentType.DSL; try { for (ModelResource mappingResource : mappingResources) { addModelToZip(zos, mappingResource.getId(), contentType); } zos.close(); baos.close(); } catch (Exception ex) { throw new RuntimeException(ex); } response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + modelId.getNamespace() + "_" + modelId.getName() + "_" + modelId.getVersion() + ".zip"); response.setContentType(APPLICATION_OCTET_STREAM); try { IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream()); response.flushBuffer(); } catch (IOException e) { throw new RuntimeException("Error copying file.", e); } }
From source file:info.magnolia.rendering.engine.RenderingFilter.java
@Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { final AggregationState aggregationState = MgnlContext.getAggregationState(); String templateName = aggregationState.getTemplateName(); if (StringUtils.isNotEmpty(templateName)) { try {//from w ww .ja v a 2 s . c o m // don't reset any existing status code, see MAGNOLIA-2005 // response.setStatus(HttpServletResponse.SC_OK); if (response != MgnlContext.getWebContext().getResponse()) { log.warn("Context response not synced. This may lead to discrepancies in rendering."); } Node content = aggregationState.getMainContent().getJCRNode(); // if the content isn't visible output a 404 if (!isVisible(content, request, response, aggregationState)) { if (!response.isCommitted()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { log.info("Unable to redirect to 404 page for {}, response is already committed", request.getRequestURI()); } return; } render(content, templateName, response); try { response.flushBuffer(); } catch (IOException e) { // don't log at error level since tomcat typically throws a // org.apache.catalina.connector.ClientAbortException if the user stops loading the page log.debug("Exception flushing response " + e.getClass().getName() + ": " + e.getMessage(), e); } } catch (RenderException e) { // TODO better handling of rendering exception // TODO dlipp: why not move this section up to the actual call to render() -> that's the only place where a RenderException could occur... log.error(e.getMessage(), e); throw new ServletException(e); } catch (Exception e) { // TODO dlipp: there's no other checked exceptions thrown in the code above - is it correct to react like that??? log.error(e.getMessage(), e); if (!response.isCommitted()) { response.setContentType("text/html"); } throw new RuntimeException(e); } } else { // direct request handleResourceRequest(aggregationState, request, response); } // TODO don't make it a dead end // currently we can't process the chain because there is no content/nop servlet // chain.doFilter(request, response); }
From source file:org.apache.chemistry.opencmis.server.impl.browser.CmisBrowserBindingServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // set default headers response.addHeader("Cache-Control", "private, max-age=0"); response.addHeader("Server", ServerVersion.OPENCMIS_SERVER); // create a context object, dispatch and handle exceptions CallContext context = null;/*from w w w .ja va 2 s .c o m*/ try { context = HttpUtils.createContext(request, response, getServletContext(), CallContext.BINDING_BROWSER, callContextHandler, tempDir, memoryThreshold); dispatch(context, request, response); } catch (Exception e) { if (e instanceof CmisPermissionDeniedException) { if ((context == null) || (context.getUsername() == null)) { response.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required"); } else { printError(e, request, response, context); } } else { printError(e, request, response, context); } } // we are done. response.flushBuffer(); }
From source file:com.flipkart.aesop.runtime.spring.web.RelayController.java
/** * Request handling for metrics snapshot *///w w w . j a v a2s . com @RequestMapping(value = { "/metrics-json" }, method = RequestMethod.GET) public @ResponseBody void metricsJSON(HttpServletRequest request, HttpServletResponse response) { try { // set appropriate headers for a stream response.setHeader("Content-Type", "application/json"); response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); response.setHeader("Pragma", "no-cache"); DefaultRelay relay = null; for (ServerContainer serverContainer : this.runtimeRegistry.getRuntimes()) { if (DefaultRelay.class.isAssignableFrom(serverContainer.getClass())) { relay = (DefaultRelay) serverContainer; break; } } if (relay != null) { if (request.getParameterMap().containsKey("full")) { Map<String, Object> map = new HashMap<String, Object>(); map.put("inbound", relay.getInboundEventStatisticsCollector()); map.put("outbound", relay.getOutboundEventStatisticsCollector()); map.put("http", relay.getHttpStatisticsCollector()); response.getWriter().print(mapper.writeValueAsString(map)); } else { response.getWriter().print(relay.getMetricsCollector().getJson()); } } else { response.getWriter().println("{}"); } response.flushBuffer(); } catch (IOException e) { logger.info("Client Disconnected: " + request.getSession().getId()); } catch (Exception e) { logger.error("Client Disconnected: " + request.getSession().getId() + " (Unknown Exception)", e); } }