List of usage examples for javax.servlet ServletOutputStream flush
public void flush() throws IOException
From source file:org.myjerry.util.ResponseUtil.java
public static final ModelAndView sendFileToDownload(HttpServletResponse response, String fileToDownload, String fileName, String contentType, boolean isHttp11) throws IOException { response.reset();/*w w w . j a v a 2 s.c o m*/ setNoCache(response, isHttp11); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentType(contentType); ServletOutputStream out; out = response.getOutputStream(); out.print(fileToDownload); out.flush(); out.close(); return null; }
From source file:com.octo.captcha.module.web.image.ImageToJpegHelper.java
/** * retrieve a new ImageCaptcha using ImageCaptchaService and flush it to the response.<br/> Captcha are localized * using request locale.<br/>/* w ww.j a va 2 s .co m*/ * <p/> * This method returns a 404 to the client instead of the image if the request isn't correct (missing parameters, * etc...)..<br/> The log may be null.<br/> * * @param theRequest the request * @param theResponse the response * @param log a commons logger * @param service an ImageCaptchaService instance * * @throws java.io.IOException if a problem occurs during the jpeg generation process */ public static void flushNewCaptchaToResponse(HttpServletRequest theRequest, HttpServletResponse theResponse, Log log, ImageCaptchaService service, String id, Locale locale) throws IOException { // call the ImageCaptchaService method to retrieve a captcha byte[] captchaChallengeAsJpeg = null; ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try { BufferedImage challenge = service.getImageChallengeForID(id, locale); // the output stream to render the captcha image as jpeg into ImageIO.write(challenge, "jpg", jpegOutputStream); } catch (IllegalArgumentException e) { // log a security warning and return a 404... if (log != null && log.isWarnEnabled()) { log.warn("There was a try from " + theRequest.getRemoteAddr() + " to render an captcha with invalid ID :'" + id + "' or with a too long one"); theResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); // render the captcha challenge as a JPEG image in the response theResponse.setHeader("Cache-Control", "no-store"); theResponse.setHeader("Pragma", "no-cache"); theResponse.setDateHeader("Expires", 0); theResponse.setContentType("image/jpeg"); ServletOutputStream responseOutputStream = theResponse.getOutputStream(); responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush(); responseOutputStream.close(); }
From source file:com.octo.captcha.module.web.sound.SoundToWavHelper.java
/** * retrieve a new SoundCaptcha using SoundCaptchaService and flush it to the response. <br/> Captcha are localized * using request locale. <br/>This method returns a 404 to the client instead of the image if the request isn't * correct (missing parameters, etc...).. <br/>The log may be null. <br/> * * @param theRequest the request/*ww w. ja v a2 s. c o m*/ * @param theResponse the response * @param log a commons logger * @param service an SoundCaptchaService instance * * @throws java.io.IOException if a problem occurs during the jpeg generation process */ public static void flushNewCaptchaToResponse(HttpServletRequest theRequest, HttpServletResponse theResponse, Log log, SoundCaptchaService service, String id, Locale locale) throws IOException { // call the ImageCaptchaService method to retrieve a captcha byte[] captchaChallengeAsWav = null; ByteArrayOutputStream wavOutputStream = new ByteArrayOutputStream(); try { AudioInputStream stream = service.getSoundChallengeForID(id, locale); // call the ImageCaptchaService method to retrieve a captcha AudioSystem.write(stream, AudioFileFormat.Type.WAVE, wavOutputStream); //AudioSystem.(pAudioInputStream, AudioFileFormat.Type.WAVE, pFile); } catch (IllegalArgumentException e) { // log a security warning and return a 404... if (log != null && log.isWarnEnabled()) { log.warn("There was a try from " + theRequest.getRemoteAddr() + " to render an captcha with invalid ID :'" + id + "' or with a too long one"); theResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } catch (CaptchaServiceException e) { // log and return a 404 instead of an image... if (log != null && log.isWarnEnabled()) { log.warn( "Error trying to generate a captcha and " + "render its challenge as JPEG", e); } theResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } captchaChallengeAsWav = wavOutputStream.toByteArray(); // render the captcha challenge as a JPEG image in the response theResponse.setHeader("Cache-Control", "no-store"); theResponse.setHeader("Pragma", "no-cache"); theResponse.setDateHeader("Expires", 0); theResponse.setContentType("audio/x-wav"); ServletOutputStream responseOutputStream = theResponse.getOutputStream(); responseOutputStream.write(captchaChallengeAsWav); responseOutputStream.flush(); responseOutputStream.close(); }
From source file:org.apache.jena.fuseki.servlets.ResponseJson.java
private static void output(HttpAction action, String contentType, String charset, OutputContent proc) { try {//w ww .ja va 2 s . c om setHttpResponse(action.request, action.response, contentType, charset); action.response.setStatus(HttpSC.OK_200); ServletOutputStream out = action.response.getOutputStream(); try { proc.output(out); out.flush(); } catch (QueryCancelledException ex) { // Bother. Status code 200 already sent. xlog.info(format("[%d] Query Cancelled - results truncated (but 200 already sent)", action.id)); out.println(); out.println("## Query cancelled due to timeout during execution ##"); out.println("## **** Incomplete results **** ##"); out.flush(); // No point raising an exception - 200 was sent already. //errorOccurred(ex) ; } // Includes client gone. } catch (IOException ex) { ServletOps.errorOccurred(ex); } // Do not call httpResponse.flushBuffer(); here - Jetty closes the stream if it is a gzip stream // then the JSON callback closing details can't be added. }
From source file:ch.ralscha.extdirectspring.util.ExtDirectSpringUtil.java
/** * Checks etag and sends back HTTP status 304 if not modified. If modified sets * content type and content length, adds cache headers ( * {@link #addCacheHeaders(HttpServletResponse, String, Integer)}), writes the data * into the {@link HttpServletResponse#getOutputStream()} and flushes it. * * @param request the HTTP servlet request * @param response the HTTP servlet response * @param data the response data//from w ww . ja v a2s .c om * @param contentType the content type of the data (i.e. * "application/javascript;charset=UTF-8") * @throws IOException */ public static void handleCacheableResponse(HttpServletRequest request, HttpServletResponse response, byte[] data, String contentType) throws IOException { String ifNoneMatch = request.getHeader("If-None-Match"); String etag = "\"0" + DigestUtils.md5DigestAsHex(data) + "\""; if (etag.equals(ifNoneMatch)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } response.setContentType(contentType); response.setContentLength(data.length); addCacheHeaders(response, etag, 6); @SuppressWarnings("resource") ServletOutputStream out = response.getOutputStream(); out.write(data); out.flush(); }
From source file:org.jivesoftware.openfire.reporting.graph.GraphServlet.java
private static void writeImageContent(HttpServletResponse response, byte[] imageData, String contentType) throws IOException { ServletOutputStream os = response.getOutputStream(); response.setContentType(contentType); os.write(imageData);/*www.j a v a2 s.c om*/ os.flush(); os.close(); }
From source file:org.apache.jena.fuseki.servlets.ResponseResultSet.java
private static void output(HttpAction action, String contentType, String charset, OutputContent proc) { try {// w ww. j av a2 s.c om setHttpResponse(action.request, action.response, contentType, charset); action.response.setStatus(HttpSC.OK_200); ServletOutputStream out = action.response.getOutputStream(); try { proc.output(out); out.flush(); } catch (QueryCancelledException ex) { // Bother. Status code 200 already sent. slog.info(format("[%d] Query Cancelled - results truncated (but 200 already sent)", action.id)); out.println(); out.println("## Query cancelled due to timeout during execution ##"); out.println("## **** Incomplete results **** ##"); out.flush(); // No point raising an exception - 200 was sent already. //errorOccurred(ex) ; } // Includes client gone. } catch (IOException ex) { errorOccurred(ex); } // Do not call httpResponse.flushBuffer(); here - Jetty closes the stream if it is a gzip stream // then the JSON callback closing details can't be added. }
From source file:com.ikon.util.WebUtils.java
/** * Send file to client browser./*from w w w . j ava 2 s.c o m*/ * * @throws IOException If there is a communication error. */ public static void sendFile(HttpServletRequest request, HttpServletResponse response, String fileName, String mimeType, boolean inline, InputStream is) throws IOException { log.debug("sendFile({}, {}, {}, {}, {}, {})", new Object[] { request, response, fileName, mimeType, inline, is }); prepareSendFile(request, response, fileName, mimeType, inline); // Set length response.setContentLength(is.available()); log.debug("File: {}, Length: {}", fileName, is.available()); ServletOutputStream sos = response.getOutputStream(); IOUtils.copy(is, sos); sos.flush(); sos.close(); }
From source file:com.ikon.util.WebUtils.java
/** * Send file to client browser./*from ww w.ja v a2 s . co m*/ * * @throws IOException If there is a communication error. */ public static void sendFile(HttpServletRequest request, HttpServletResponse response, String fileName, String mimeType, boolean inline, File input) throws IOException { log.debug("sendFile({}, {}, {}, {}, {}, {})", new Object[] { request, response, fileName, mimeType, inline, input }); prepareSendFile(request, response, fileName, mimeType, inline); // Set length response.setContentLength((int) input.length()); log.debug("File: {}, Length: {}", fileName, input.length()); ServletOutputStream sos = response.getOutputStream(); FileUtils.copy(input, sos); sos.flush(); sos.close(); }
From source file:org.openmrs.module.idcards.web.servlet.PrintEmptyIdcardsServlet.java
/** * Write the pdf to the given response/*from w ww .ja v a2s .c o m*/ */ @SuppressWarnings("unchecked") public static void generateOutputForIdentifiers(IdcardsTemplate card, String baseURL, HttpServletResponse response, List<String> identifiers, String password) throws ServletException, IOException { Properties props = new Properties(); props.setProperty(RuntimeConstants.RESOURCE_LOADER, "class"); props.setProperty("class.resource.loader.description", "VelocityClasspathResourceLoader"); props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); props.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.NullLogSystem"); // do the velocity magic Writer writer = new StringWriter(); try { // Allow images to be served from Unix servers. try { java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(); } catch (Throwable t) { log.warn( "Unable to get graphics environment. " + "Make sure that -Djava.awt.headless=true is defined as a JAVA OPT during startup", t); } Velocity.init(props); VelocityContext velocityContext = new VelocityContext(); velocityContext.put("locale", Context.getLocale()); velocityContext.put("identifiers", identifiers); velocityContext.put("baseURL", baseURL); Velocity.evaluate(velocityContext, writer, PrintEmptyIdcardsServlet.class.getName(), card.getXml()); } catch (ParseErrorException e) { throw new ServletException("Error parsing template: ", e); } catch (MethodInvocationException e) { throw new ServletException("Error parsing template: ", e); } catch (ResourceNotFoundException e) { throw new ServletException("Error parsing template: ", e); } catch (Exception e) { throw new ServletException("Error initializing Velocity engine", e); } finally { System.gc(); } try { //Setup a buffer to obtain the content length ByteArrayOutputStream out = new ByteArrayOutputStream(); FopFactory fopFactory = FopFactory.newInstance(); //fopFactory supports customization with a config file //Load the config file before creating the user agent. String userConfigFile = Context.getAdministrationService() .getGlobalProperty("idcards.fopConfigFilePath"); if (userConfigFile != null) { try { fopFactory.setUserConfig(new java.io.File(userConfigFile)); log.debug("Successfully loaded config file |" + userConfigFile + "|"); } catch (Exception e) { log.error("Could not initialize fopFactory user config with file at " + userConfigFile + ". Error message:" + e.getMessage()); } } FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); foUserAgent.getRendererOptions().put("encryption-params", new PDFEncryptionParams(password, null, true, false, false, false)); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); //Setup Transformer Source xsltSrc = new StreamSource(new StringReader(card.getXslt())); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(xsltSrc); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Setup input String xml = writer.toString(); Source src = new StreamSource(new StringReader(xml)); //Start the transformation and rendering process transformer.transform(src, res); //Prepare response String time = new SimpleDateFormat("yyyy-MM-dd_Hms").format(new Date()); String filename = card.getName().replace(" ", "_") + "-" + time + ".pdf"; response.setHeader("Content-Disposition", "attachment; filename=" + filename); response.setContentType("application/pdf"); response.setContentLength(out.size()); //Send content to Browser ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(out.toByteArray()); outputStream.flush(); } catch (FOPException e) { throw new ServletException("Error generating report", e); } catch (TransformerConfigurationException e) { throw new ServletException("Error generating report", e); } catch (TransformerException e) { throw new ServletException("Error generating report", e); } }