List of usage examples for javax.servlet ServletOutputStream write
public abstract void write(int b) throws IOException;
From source file:dijalmasilva.controllers.ControladorIdolo.java
@RequestMapping("/image/{id}") public void carregaImagem(@PathVariable Long id, HttpServletResponse resp) { ServletOutputStream out = null; try {// ww w . j av a 2s. co m Idolo idolo = serviceIdolo.buscar(id); out = resp.getOutputStream(); out.write(idolo.getFoto()); out.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
From source file:com.jaspersoft.jasperserver.war.themes.ThemeResolverServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Check if we can find a resource in the current theme //String resPath = req.getRequestURI().substring((req.getContextPath() + req.getServletPath()).length()); String resPath = req.getRequestURI().substring(req.getContextPath().length() + 1); ThemeResource themeResource = themeCache.getThemeResource(resPath); if (themeResource == null) { resp.sendError(404);/*from ww w . j av a 2 s. c o m*/ return; } // Set contentType String filename = resPath; if (filename.indexOf("/") >= 0) { filename = filename.substring(filename.lastIndexOf("/") + 1); } String contentType = servletContext.getMimeType(filename); if (contentType == null) { log.error("Cannot detect a response content type for the file : " + filename); resp.sendError(404); return; } resp.setContentType(contentType); // Get Last Modified date Date lastModified = themeResource.getLastModified(); // Get rid of ms lastModified.setTime(lastModified.getTime() / 1000 * 1000); // Set cache controlling HTTP Response Headers DateFormat df = getFormat(req.getLocale()); resp.setHeader("Cache-Control", "max-age=" + expiresInSecs + ", public"); resp.setHeader("Pragma", ""); resp.setHeader("Last-Modified", df.format(lastModified)); resp.setHeader("Expires", df.format(new Date(new Date().getTime() + expiresInSecs * 1000))); // Send 304 if resource has not been modified since last time requested String ifModSince = req.getHeader("If-Modified-Since"); try { Date modDate = df.parse(ifModSince); if (!lastModified.after(modDate)) { resp.setStatus(304); return; } } catch (Exception e) { } // Send the full content resp.setContentLength(themeResource.getContent().length); ServletOutputStream os = resp.getOutputStream(); os.write(themeResource.getContent()); os.flush(); os.close(); }
From source file:tilt.handler.get.TiltImageHandler.java
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws TiltException { try {/* w ww . j av a 2 s. c om*/ imageType = ImageType.read(request.getParameter(Params.PICTYPE)); docid = request.getParameter(Params.DOCID); pageid = request.getParameter(Params.PAGEID); url = request.getParameter(Params.URL); if ((docid != null && pageid != null) || url != null) { if (url == null || url.length() == 0) url = Utils.getUrl(request.getServerName(), docid, pageid); Picture p = PictureRegistry.get(url); if (p == null) { TextIndex text = null; PictureRegistry.prune(); Double[][] coords = getCropRect(request.getServerName(), docid, pageid); Options opts = Options.get(request.getServerName(), docid); String imageUrl = Utils.getUrl(request.getServerName(), docid, pageid); String url = composeTextUrl(request, docid, pageid); String textParam = Utils.getFromUrl(url); if (textParam != null) text = new TextIndex(textParam, "en_GB"); InetAddress poster = getIPAddress(request); p = new Picture(opts, imageUrl, text, coords, poster); } byte[] pic = null; switch (imageType) { case load: p.load(); case original: pic = p.getOrigData(); break; case preflight: pic = p.getPreflightData(); break; case greyscale: pic = p.getGreyscaleData(); break; case twotone: pic = p.getTwoToneData(); break; case cleaned: pic = p.getCleanedData(); break; case reconstructed: pic = p.getReconstructedData(); break; case baselines: pic = p.getBaselinesData(); break; case words: pic = p.getWordsData(); break; case link: pic = p.getGreyscaleData(); break; } if (pic != null) { ByteArrayInputStream bis = new ByteArrayInputStream(pic); String mimeType = URLConnection.guessContentTypeFromStream(bis); response.setContentType(mimeType); ServletOutputStream sos = response.getOutputStream(); sos.write(pic); sos.close(); } else { response.getOutputStream().println("<p>image " + docid + " not found</p>"); } } else response.getOutputStream().println("<p>please specify a docid and pageid, or a url</p>"); } catch (Exception e) { throw new ImageException(e); } }
From source file:be.fedict.eid.dss.webapp.DocumentViewerServlet.java
private void handleDownloadRequest(String resourceId, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { LOG.debug("handle download: " + resourceId); HttpSession httpSession = request.getSession(); DocumentRepository documentRepository = new DocumentRepository(httpSession); String contentType = documentRepository.getDocumentContentType(); if (null == contentType) { response.setContentType("text/plain"); PrintWriter printWriter = response.getWriter(); printWriter.println("No document to be signed."); return;// ww w .j a v a 2 s .c om } byte[] documentData = documentRepository.getDocument(); DSSDocumentService documentService = super.findDocumentService(contentType); if (null != documentService) { DocumentVisualization documentVisualization; try { documentVisualization = documentService.findDocument(documentData, resourceId); } catch (Exception e) { throw new ServletException("error finding the document: " + e.getMessage(), e); } if (null != documentVisualization) { contentType = documentVisualization.getBrowserContentType(); documentData = documentVisualization.getBrowserData(); } } setResponseHeaders(request, response); response.setContentType(contentType); response.setContentLength(documentData.length); ServletOutputStream out = response.getOutputStream(); out.write(documentData); out.flush(); }
From source file:gxu.software_engineering.shen10.market.core.MappingJacksonJsonpView.java
@Override public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception { // utf8/*from w w w. j a v a2 s. com*/ // String charset = response.getCharacterEncoding(); // if (charset == null || charset.length() == 0) { // response.setCharacterEncoding(DEFAULT_CHARSET); // } if (request.getMethod().toUpperCase().equals("GET")) { if (request.getParameterMap().containsKey("callback")) { ServletOutputStream ostream = response.getOutputStream(); // try ostream.write(new String("try{" + request.getParameter("callback") + "(").getBytes()); super.render(model, request, response); ostream.write(new String(");}catch(e){}").getBytes()); // ????closeflushspring? // ? ostream.flush(); ostream.close(); } else { super.render(model, request, response); } } else { super.render(model, request, response); } }
From source file:com.ningpai.common.util.CaptchaController.java
@RequestMapping("/captcha") public void writeCaptcha(HttpServletRequest request, HttpServletResponse response) { byte[] captchaChallengeAsJpeg = null; // the output stream to render the captcha image as jpeg into ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream(); try {/*from w ww .j a v a 2 s . c om*/ // get the session id that will identify the generated captcha. // the same id must be used to validate the response, the session id is a good candidate! String captchaId = request.getSession().getId(); BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale()); try { ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream); } catch (IOException e) { } } catch (IllegalArgumentException e) { try { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (IOException e1) { } return; } catch (CaptchaServiceException e) { try { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (IOException e1) { } return; } captchaChallengeAsJpeg = jpegOutputStream.toByteArray(); // flush it in the response response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT); ServletOutputStream responseOutputStream; try { responseOutputStream = response.getOutputStream(); responseOutputStream.write(captchaChallengeAsJpeg); responseOutputStream.flush(); responseOutputStream.close(); } catch (IOException e) { } }
From source file:org.toobsframework.servlet.filters.export.XLSExportFilter.java
/** * Pipe the fetched *.xls <fo> xml output from the ComponentLayoutManager * through the FO transformer in order to get a viable pdf file. Set the * response headers, response stream, and the browser should pick the pdf up * and handle it properly.//from ww w . j a v a 2 s .com */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { this.config.getServletContext().log("XLSFilter - doFilter(...)"); log.debug("ENTER doFilter(...)"); HttpServletResponse httpResponse = (HttpServletResponse) response; HttpServletRequest httpRequest = (HttpServletRequest) request; // set headers so browser knows it's looking at a pdf // httpResponse.setHeader("Content-Disposition", "attachment"); // first chain the filters... ie do everything else first... this filter // will work on the data that comes back after the transform has already // been run FilterResponseWrapper wrapper = new FilterResponseWrapper(httpResponse); chain.doFilter(request, wrapper); String fileName; String exportMode = httpRequest.getParameter("exportMode"); if ("table".equals(exportMode)) { fileName = httpRequest.getParameter("component") + ".xls"; } else { fileName = httpRequest.getRequestURI().substring(contextName.length() + 1).replace("xxls", "xls"); } // set headers so browser knows it's looking at a pdf httpResponse.setContentType("application/vnd.ms-excel"); httpResponse.setHeader("Pragma", "public"); httpResponse.setDateHeader("Expires", 0); httpResponse.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); httpResponse.setHeader("Cache-Control", "public"); httpResponse.setHeader("Content-Description", "File Transfer"); httpResponse.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // now fetch the output stream and response data ServletOutputStream httpOutputStream = httpResponse.getOutputStream(); byte[] responseData = wrapper.getData(); httpOutputStream.write(responseData); if (log.isDebugEnabled()) { log.debug("EXIT doFilter(...)"); } }
From source file:com.webpagebytes.cms.utility.HttpServletToolbox.java
public void writeBodyResponseAsJson(HttpServletResponse response, String data, Map<String, String> errors) { try {/* w w w .j a v a 2s . c o m*/ org.json.JSONObject jsonResponse = new org.json.JSONObject(); org.json.JSONObject jsonErrors = new org.json.JSONObject(); if (errors == null || errors.keySet().size() == 0) { jsonResponse.put("status", "OK"); } else { jsonResponse.put("status", "FAIL"); for (String key : errors.keySet()) { jsonErrors.put(key, errors.get(key)); } } jsonResponse.put("errors", jsonErrors); jsonResponse.put("payload", data); String jsonString = jsonResponse.toString(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); ServletOutputStream writer = response.getOutputStream(); byte[] utf8bytes = jsonString.getBytes("UTF-8"); writer.write(utf8bytes); response.setContentLength(utf8bytes.length); writer.flush(); } catch (Exception e) { try { String errorResponse = "{\"status\":\"FAIL\",\"payload\":\"{}\",\"errors\":{\"reason\":\"WB_UNKNOWN_ERROR\"}}"; ServletOutputStream writer = response.getOutputStream(); response.setContentType("application/json"); byte[] utf8bytes = errorResponse.getBytes("UTF-8"); response.setContentLength(utf8bytes.length); writer.write(utf8bytes); writer.flush(); } catch (IOException ioe) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
From source file:com.webpagebytes.cms.utility.HttpServletToolbox.java
public void writeBodyResponseAsJson(HttpServletResponse response, org.json.JSONObject data, Map<String, String> errors) { try {//from ww w . jav a2 s .c o m org.json.JSONObject jsonResponse = new org.json.JSONObject(); org.json.JSONObject jsonErrors = new org.json.JSONObject(); if (errors == null || errors.keySet().size() == 0) { jsonResponse.put("status", "OK"); } else { jsonResponse.put("status", "FAIL"); for (String key : errors.keySet()) { jsonErrors.put(key, errors.get(key)); } } jsonResponse.put("errors", jsonErrors); jsonResponse.put("payload", data); String jsonString = jsonResponse.toString(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); ServletOutputStream writer = response.getOutputStream(); byte[] utf8bytes = jsonString.getBytes("UTF-8"); writer.write(utf8bytes); response.setContentLength(utf8bytes.length); writer.flush(); } catch (Exception e) { try { String errorResponse = "{\"status\":\"FAIL\",\"payload\":\"{}\",\"errors\":{\"reason\":\"WB_UNKNOWN_ERROR\"}}"; ServletOutputStream writer = response.getOutputStream(); response.setContentType("application/json"); byte[] utf8bytes = errorResponse.getBytes("UTF-8"); response.setContentLength(utf8bytes.length); writer.write(utf8bytes); writer.flush(); } catch (IOException ioe) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
From source file:org.b5chat.crossfire.web.FaviconServlet.java
/** * Writes out a <code>byte</code> to the ServletOuputStream. * * @param bytes the bytes to write to the <code>ServletOutputStream</code>. *///from w ww . j a v a 2 s .c om private void writeBytesToStream(byte[] bytes, HttpServletResponse response) { response.setContentType(CONTENT_TYPE); // Send image try { ServletOutputStream sos = response.getOutputStream(); sos.write(bytes); sos.flush(); sos.close(); } catch (IOException e) { // Do nothing } }