List of usage examples for javax.servlet ServletOutputStream write
public abstract void write(int b) throws IOException;
From source file:org.xsystem.http.RestApiTemplate.java
protected static void write(byte b[], ServletOutputStream out) throws IOException { out.write(b); }
From source file:org.xsystem.http.RestApiTemplate.java
protected static void write(String s, ServletOutputStream out) throws IOException { out.write(s.getBytes("UTF-8")); }
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/>//from www .j a v a 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/* www . j a v a 2 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:strutter.helper.WSActionHelper.java
public static void writeBody(byte[] val) throws Exception { ServletOutputStream writer = ActionHelper.getResponse().getOutputStream(); writer.write(val); writer.close();/*w w w . j a v a 2 s.co m*/ }
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 ww w .j a v a 2 s .co m * @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); os.flush();/*from w w w . ja v a 2 s . c o m*/ os.close(); }
From source file:org.openmrs.module.idcards.web.servlet.PrintEmptyIdcardsServlet.java
/** * Write the pdf to the given response//from w w w . ja va 2s . 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); } }
From source file:pt.ua.dicoogle.server.web.IndexerServlet.java
/** * Writes the specified XML document in String form to a HttpServletResponse * object./* www . j a va 2s . c o m*/ * * @param xml * a XML document in String form. * @param response * a HttpServletResponse. * @throws IOException * if a error has occurred while writing the response. */ private static void writeXMLToResponse(String xml, HttpServletResponse response, boolean allowCache) throws IOException { // get the returned xml as a UTF-8 byte array byte[] data = xml.getBytes("UTF-8"); if (data == null) { response.sendError(500, "Could generate the resulting XML document!"); return; } if (!allowCache) { response.addHeader("Cache-Control", "no-cache, must-revalidate"); response.addHeader("Pragma", "no-cache"); } response.setContentType("application/xml"); // set the appropriate type // for the XML file response.setContentLength(data.length); // set the document size // response.setCharacterEncoding("UTF-8"); // set the apropriate // encoding type // write the XML data to the response output ServletOutputStream out = response.getOutputStream(); out.write(data); out.close(); }
From source file:com.soolr.core.web.Servlets.java
public static void output(HttpServletResponse response, String contentType, Object content) throws IOException { ServletOutputStream output = response.getOutputStream(); try {/*from w ww. j a va2s. c o m*/ response.setContentType(contentType); if (content instanceof byte[]) { byte[] temp = (byte[]) content; output.write(temp); } else if (content instanceof String) { output.print(String.valueOf(content)); } } finally { output.flush(); output.close(); } }