List of usage examples for javax.servlet ServletOutputStream close
public void close() throws IOException
From source file:org.zht.framework.filter.jcaptcha.JCaptchaFilter.java
/** * ???.//from w w w . ja v a 2s .co m */ protected void genernateCaptchaImage(final HttpServletRequest request, final HttpServletResponse response) throws IOException { response.setDateHeader("Expires", 0); response.addHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setContentType("image/jpeg"); ServletOutputStream out = response.getOutputStream(); try { String captchaId = request.getSession(true).getId(); BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId, request.getLocale()); ImageIO.write(challenge, "jpg", out); out.flush(); } catch (CaptchaServiceException e) { logger.error(e.getMessage(), e); } finally { out.close(); } }
From source file:jp.xet.uncommons.web.HtmlCompressionFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { OutputStreamResponseWrapper wrappedResponse = new OutputStreamResponseWrapper(response); filterChain.doFilter(request, wrappedResponse); ByteArrayOutputStream baos = wrappedResponse.getRealOutputStream(); if (enabled && Strings.nullToEmpty(response.getContentType()).startsWith("text/html")) { HtmlCompressor compressor = new HtmlCompressor(); compressor.setEnabled(enabled);//from w w w . j a va 2 s .c o m compressor.setRemoveComments(removeComments); compressor.setRemoveMultiSpaces(removeMultiSpaces); compressor.setRemoveIntertagSpaces(removeIntertagSpaces); compressor.setRemoveQuotes(removeQuotes); compressor.setCompressJavaScript(compressJavaScript); compressor.setCompressCss(compressCss); compressor.setYuiJsNoMunge(yuiJsNoMunge); compressor.setYuiJsPreserveAllSemiColons(yuiJsPreserveAllSemiColons); compressor.setYuiJsDisableOptimizations(yuiJsDisableOptimizations); compressor.setYuiJsLineBreak(yuiJsLineBreak); compressor.setYuiCssLineBreak(yuiCssLineBreak); PrintWriter writer = null; try { String compressed = compressor.compress(baos.toString()); response.setContentLength(compressed.length()); writer = response.getWriter(); writer.write(compressed); } finally { if (writer != null) { writer.close(); } } } else if (baos != null) { ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); outputStream.write(baos.toByteArray()); } finally { if (outputStream != null) { outputStream.close(); } } } }
From source file:ai.h2o.servicebuilder.CompilePojoServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File tmp = null;/*from w w w .j av a 2 s. co m*/ try { //create temp directory tmp = createTempDirectory("compilePojo"); logger.info("tmp dir {}", tmp); // get input files List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); List<String> pojofiles = new ArrayList<String>(); String jarfile = null; for (FileItem i : items) { String field = i.getFieldName(); String filename = i.getName(); if (filename != null && filename.length() > 0) { if (field.equals("pojo")) { pojofiles.add(filename); } if (field.equals("jar")) { jarfile = filename; } FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmp, filename)); } } if (pojofiles.isEmpty() || jarfile == null) throw new Exception("need pojofile(s) and jarfile"); // create output directory File out = new File(tmp.getPath(), "out"); boolean mkDirResult = out.mkdir(); if (!mkDirResult) throw new Exception("Can't create output directory (out)"); if (servletPath == null) throw new Exception("servletPath is null"); copyExtraFile(servletPath, "extra" + File.separator, tmp, "H2OPredictor.java", "H2OPredictor.java"); FileUtils.copyDirectoryToDirectory( new File(servletPath, "extra" + File.separator + "WEB-INF" + File.separator + "lib"), tmp); copyExtraFile(servletPath, "extra" + File.separator, new File(out, "META-INF"), "MANIFEST.txt", "MANIFEST.txt"); // Compile the pojo(s) for (String pojofile : pojofiles) { runCmd(tmp, Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfile + ":lib/*", "-d", "out", pojofile, "H2OPredictor.java"), "Compilation of pojo failed: " + pojofile); } // create jar result file runCmd(out, Arrays.asList("jar", "xf", tmp + File.separator + jarfile), "jar extraction of h2o-genmodel failed"); runCmd(out, Arrays.asList("jar", "xf", tmp + File.separator + "lib" + File.separator + "gson-2.6.2.jar"), "jar extraction of gson failed"); runCmd(out, Arrays.asList("jar", "cfm", tmp + File.separator + "result.jar", "META-INF" + File.separator + "MANIFEST.txt", "."), "jar creation failed"); byte[] resjar = IOUtils.toByteArray(new FileInputStream(tmp + File.separator + "result.jar")); if (resjar == null) throw new Exception("Can't create jar of compiler output"); logger.info("jar created, size {}", resjar.length); // send jar back ServletOutputStream sout = response.getOutputStream(); response.setContentType("application/octet-stream"); String outputFilename = pojofiles.get(0).replace(".java", ""); response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".jar"); response.setContentLength(resjar.length); sout.write(resjar); sout.close(); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { logger.error("post failed", e); // send the error message back String message = e.getMessage(); if (message == null) message = "no message"; logger.error(message); response.getWriter().write(message); response.getWriter().write(Arrays.toString(e.getStackTrace())); response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } finally { // if the temp directory is still there we delete it try { if (tmp != null && tmp.exists()) FileUtils.deleteDirectory(tmp); } catch (IOException e) { logger.error("Can't delete tmp directory"); } } }
From source file:org.inbio.ait.web.ajax.controller.SelectAllController.java
private ModelAndView writeReponse(HttpServletRequest request, HttpServletResponse response, List<Polygon> pList) throws Exception { response.setCharacterEncoding("ISO-8859-1"); response.setContentType("text/xml"); // Binary output ServletOutputStream out = response.getOutputStream(); if (pList != null) { StringBuilder result = new StringBuilder(); result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response>"); for (Polygon p : pList) { result.append("<polygon><id>" + p.getId() + "</id>"); result.append("<name>" + p.getName() + "</name></polygon>"); }/*from w w w . j a v a 2s . co m*/ result.append("</response>"); out.println(result.toString()); } out.flush(); out.close(); return null; }
From source file:eu.freme.broker.tools.internationalization.EInternationalizationFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (!(req instanceof HttpServletRequest) || !(res instanceof HttpServletResponse)) { chain.doFilter(req, res);/* ww w .j av a2s .co m*/ return; } HttpServletRequest httpRequest = (HttpServletRequest) req; HttpServletResponse httpResponse = (HttpServletResponse) res; if (httpRequest.getMethod().equals("OPTIONS")) { chain.doFilter(req, res); return; } String uri = httpRequest.getRequestURI(); for (Pattern pattern : endpointBlacklistRegex) { if (pattern.matcher(uri).matches()) { chain.doFilter(req, res); return; } } String informat = getInformat(httpRequest); String outformat = getOutformat(httpRequest); if (outformat != null && (informat == null || !outformat.equals(informat))) { Exception exception = new BadRequestException("Can only convert to outformat \"" + outformat + "\" when informat is also \"" + outformat + "\""); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } if (outformat != null && !outputFormats.contains(outformat)) { Exception exception = new BadRequestException("\"" + outformat + "\" is not a valid output format"); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } if (informat == null) { chain.doFilter(req, res); return; } boolean roundtripping = false; if (outformat != null) { roundtripping = true; logger.debug("convert from " + informat + " to " + outformat); } else { logger.debug("convert input from " + informat + " to nif"); } // do conversion of informat to nif // create BodySwappingServletRequest String inputQueryString = req.getParameter("input"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (InputStream requestInputStream = inputQueryString == null ? /* * read * data * from * request * body */req.getInputStream() : /* * read data from query string input * parameter */new ReaderInputStream(new StringReader(inputQueryString), "UTF-8")) { // copy request content to buffer IOUtils.copy(requestInputStream, baos); } // create request wrapper that converts the body of the request from the // original format to turtle Reader nif; byte[] baosData = baos.toByteArray(); if (baosData.length == 0) { Exception exception = new BadRequestException("No input data found in request."); exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception); return; } ByteArrayInputStream bais = new ByteArrayInputStream(baosData); try { nif = eInternationalizationApi.convertToTurtle(bais, informat.toLowerCase()); } catch (ConversionException e) { logger.error("Error", e); throw new InternalServerErrorException("Conversion from \"" + informat + "\" to NIF failed"); } BodySwappingServletRequest bssr = new BodySwappingServletRequest((HttpServletRequest) req, nif, roundtripping); if (!roundtripping) { chain.doFilter(bssr, res); return; } ConversionHttpServletResponseWrapper dummyResponse; try { dummyResponse = new ConversionHttpServletResponseWrapper(httpResponse, eInternationalizationApi, new ByteArrayInputStream(baosData), informat, outformat); chain.doFilter(bssr, dummyResponse); ServletOutputStream sos = httpResponse.getOutputStream(); byte[] data = dummyResponse.writeBackToClient(); httpResponse.setContentLength(data.length); sos.write(data); sos.flush(); sos.close(); } catch (ConversionException e) { e.printStackTrace(); // exceptionHandlerService.writeExceptionToResponse((HttpServletResponse)res,new // InternalServerErrorException()); } }
From source file:hudson.jbpm.PluginImpl.java
/** * Draws a JPEG for a process definition * //from w w w . ja v a2s . c om * @param req * @param rsp * @param processDefinition * @throws IOException */ public void doProcessDefinitionImage(StaplerRequest req, StaplerResponse rsp, @QueryParameter("processDefinition") long processDefinition) throws IOException { JbpmContext context = getCurrentJbpmContext(); ProcessDefinition definition = context.getGraphSession().getProcessDefinition(processDefinition); FileDefinition fd = definition.getFileDefinition(); byte[] bytes = fd.getBytes("processimage.jpg"); rsp.setContentType("image/jpeg"); ServletOutputStream output = rsp.getOutputStream(); BufferedImage loaded = ImageIO.read(new ByteArrayInputStream(bytes)); BufferedImage aimg = new BufferedImage(loaded.getWidth(), loaded.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = aimg.createGraphics(); g.drawImage(loaded, null, 0, 0); g.dispose(); ImageIO.write(aimg, "jpg", output); output.flush(); output.close(); }
From source file:org.fenixedu.academic.ui.struts.action.internationalRelatOffice.candidacy.erasmus.ErasmusIndividualCandidacyProcessDA.java
public ActionForward retrieveLearningAgreement(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { MobilityIndividualApplicationProcess process = getProcess(request); final LearningAgreementDocument document = new LearningAgreementDocument(process); byte[] data = ReportsUtils.generateReport(document).getData(); response.setContentLength(data.length); response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=" + document.getReportFileName() + ".pdf"); final ServletOutputStream writer = response.getOutputStream(); writer.write(data);/* w w w . ja va 2s.co m*/ writer.flush(); writer.close(); response.flushBuffer(); return mapping.findForward(""); }
From source file:net.sourceforge.fenixedu.presentationTier.Action.internationalRelatOffice.candidacy.erasmus.ErasmusIndividualCandidacyProcessDA.java
public ActionForward retrieveLearningAgreement(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { MobilityIndividualApplicationProcess process = getProcess(request); final LearningAgreementDocument document = new LearningAgreementDocument(process); byte[] data = ReportsUtils.exportMultipleToPdfAsByteArray(document); response.setContentLength(data.length); response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=" + document.getReportFileName() + ".pdf"); final ServletOutputStream writer = response.getOutputStream(); writer.write(data);/*from www .j a v a2 s .c o m*/ writer.flush(); writer.close(); response.flushBuffer(); return mapping.findForward(""); }
From source file:com.openkm.servlet.admin.StampServlet.java
/** * View image stamp/*from ww w . j a va 2 s.com*/ */ private void imageView(Session session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, DatabaseException { log.debug("imageView({}, {}, {})", new Object[] { session, request, response }); int siId = WebUtils.getInt(request, "si_id"); StampImage si = StampImageDAO.findByPk(siId); response.setContentType(si.getImageMime()); ServletOutputStream sos = response.getOutputStream(); sos.write(SecureStore.b64Decode(si.getImageContent())); sos.flush(); sos.close(); log.debug("imageView: void"); }
From source file:org.kuali.mobility.people.controllers.PeopleController.java
@RequestMapping(value = "/image/{hash}", method = RequestMethod.GET) public void getImage(@PathVariable("hash") String imageKeyHash, Model uiModel, HttpServletRequest request, HttpServletResponse response) throws Exception { byte[] byteArray = (byte[]) request.getSession().getAttribute("People.Image.Email." + imageKeyHash); if (byteArray != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(byteArray.length); baos.write(byteArray);/* www .ja va2 s. c om*/ if (baos != null) { ServletOutputStream sos = null; try { response.setContentLength(baos.size()); sos = response.getOutputStream(); baos.writeTo(sos); sos.flush(); } catch (Exception e) { LOG.error("error creating image file", e); } finally { try { baos.close(); sos.close(); } catch (Exception e1) { LOG.error("error closing output stream", e1); } } } } }