List of usage examples for javax.servlet ServletOutputStream close
public void close() throws IOException
From source file:util.RelatorioUtil.java
public void criaRelatoriodb(Map parameters, String caminhorelatorio, Connection conn) throws IOException, JRException { FacesContext fcontext = FacesContext.getCurrentInstance(); ServletContext scontext = (ServletContext) fcontext.getExternalContext().getContext(); String relJasper = scontext.getRealPath(caminhorelatorio); //InputStream inputStream = getClass().getResourceAsStream(relJasper); HttpServletResponse response = (HttpServletResponse) fcontext.getExternalContext().getResponse(); ServletOutputStream responseStream = response.getOutputStream(); // JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(listas); //Map parameters = new HashMap(); response.setHeader("Content-Disposition", "inline; filename=rel_quantitativo"); response.setHeader("Cache-Control", "no-cache"); response.setContentType("application/pdf"); JasperPrint jasperPrint = JasperFillManager.fillReport(relJasper, parameters, conn); JasperExportManager.exportReportToPdfStream(jasperPrint, responseStream); byte x1[] = JasperExportManager.exportReportToPdf(jasperPrint); response.getOutputStream().write(x1); responseStream.flush();/*www . j av a 2 s.co m*/ responseStream.close(); fcontext.renderResponse(); fcontext.responseComplete(); }
From source file:org.apache.stratos.theme.mgt.ui.servlets.ThemeResourceServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//from w w w . j a va2 s . co m ThemeMgtServiceClient client = new ThemeMgtServiceClient(servletConfig, request.getSession()); String path = request.getParameter("path"); String viewImage = request.getParameter("viewImage"); if (path == null) { String msg = "Could not get the resource content. Path is not specified."; log.error(msg); response.setStatus(400); return; } ContentDownloadBean bean = client.getContentDownloadBean(path); InputStream contentStream = null; if (bean.getContent() != null) { contentStream = bean.getContent().getInputStream(); } else { String msg = "The resource content was empty."; log.error(msg); response.setStatus(204); return; } response.setDateHeader("Last-Modified", bean.getLastUpdatedTime().getTime().getTime()); String ext = "jpg"; if (path.lastIndexOf(".") < path.length() - 1 && path.lastIndexOf(".") > 0) { ext = path.substring(path.lastIndexOf(".") + 1); } if (viewImage != null && viewImage.equals("1")) { response.setContentType("img/" + ext); } else { if (bean.getMediatype() != null && bean.getMediatype().length() > 0) { response.setContentType(bean.getMediatype()); } else { response.setContentType("application/download"); } if (bean.getResourceName() != null) { response.setHeader("Content-Disposition", "attachment; filename=\"" + bean.getResourceName() + "\""); } } if (contentStream != null) { ServletOutputStream servletOutputStream = null; try { servletOutputStream = response.getOutputStream(); byte[] contentChunk = new byte[1024]; int byteCount; while ((byteCount = contentStream.read(contentChunk)) != -1) { servletOutputStream.write(contentChunk, 0, byteCount); } response.flushBuffer(); servletOutputStream.flush(); } finally { contentStream.close(); if (servletOutputStream != null) { servletOutputStream.close(); } } } } catch (Exception e) { String msg = "Failed to get resource content. " + e.getMessage(); log.error(msg, e); response.setStatus(500); } }
From source file:au.org.ala.biocache.web.MapController.java
/** * This method creates and renders a density map legend for a species. * //from w ww .j a v a 2s .co m * @throws Exception */ @RequestMapping(value = "/density/legend", method = RequestMethod.GET) public @ResponseBody void speciesDensityLegend(SpatialSearchRequestParams requestParams, @RequestParam(value = "forceRefresh", required = false, defaultValue = "false") boolean forceRefresh, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("image/png"); File baseDir = new File(heatmapOutputDir); String outputHMFile = getOutputFile(request); //Does file exist on disk? File f = new File(baseDir + "/" + "legend_" + outputHMFile); if (!f.isFile() || !f.exists() || forceRefresh) { //If not, generate logger.debug("regenerating heatmap legend"); generateStaticHeatmapImages(requestParams, true, false, 0, "0000ff", null, null, 1.0f, request); } else { logger.debug("legend file already exists on disk, sending file back to user"); } //read file off disk and send back to user try { File file = new File(baseDir + "/" + "legend_" + outputHMFile); //only send the image back if it actually exists - a legend won't exist if we create the map based on points if (file.exists()) { BufferedImage img = ImageIO.read(file); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(img, "png", outputStream); ServletOutputStream outStream = response.getOutputStream(); outStream.write(outputStream.toByteArray()); outStream.flush(); outStream.close(); } } catch (Exception e) { logger.error("Unable to write image.", e); } }
From source file:au.org.ala.biocache.web.MapController.java
/** * This method creates and renders a density map for a species. * /*from ww w . java2s . c om*/ * @throws Exception */ @RequestMapping(value = { "/density/map", "/occurrences/static" }, method = RequestMethod.GET) public @ResponseBody void speciesDensityMap(SpatialSearchRequestParams requestParams, @RequestParam(value = "forceRefresh", required = false, defaultValue = "false") boolean forceRefresh, @RequestParam(value = "forcePointsDisplay", required = false, defaultValue = "false") boolean forcePointsDisplay, @RequestParam(value = "pointColour", required = false, defaultValue = "0000ff") String pointColour, @RequestParam(value = "colourByFq", required = false, defaultValue = "") String colourByFqCSV, @RequestParam(value = "colours", required = false, defaultValue = "") String coloursCSV, @RequestParam(value = "pointHeatMapThreshold", required = false, defaultValue = "500") Integer pointHeatMapThreshold, @RequestParam(value = "opacity", required = false, defaultValue = "1.0") Float opacity, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("image/png"); File outputDir = new File(heatmapOutputDir); if (!outputDir.exists()) { FileUtils.forceMkdir(outputDir); } //output heatmap path String outputHMFile = getOutputFile(request); String[] facetValues = null; String[] facetColours = null; if (StringUtils.trimToNull(colourByFqCSV) != null && StringUtils.trimToNull(coloursCSV) != null) { facetValues = colourByFqCSV.split(","); facetColours = coloursCSV.split(","); if (facetValues.length == 0 || facetValues.length != facetColours.length) { throw new IllegalArgumentException( String.format("Mismatch in facet values and colours. Values: %d, Colours: %d", facetValues.length, facetColours.length)); } } //Does file exist on disk? File f = new File(outputDir + "/" + outputHMFile); if (!f.isFile() || !f.exists() || forceRefresh) { logger.debug("Regenerating heatmap image"); //If not, generate generateStaticHeatmapImages(requestParams, false, forcePointsDisplay, pointHeatMapThreshold, pointColour, facetValues, facetColours, opacity, request); } else { logger.debug("Heatmap file already exists on disk, sending file back to user"); } try { //read file off disk and send back to user File file = new File(outputDir + "/" + outputHMFile); BufferedImage img = ImageIO.read(file); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(img, "png", outputStream); ServletOutputStream outStream = response.getOutputStream(); outStream.write(outputStream.toByteArray()); outStream.flush(); outStream.close(); } catch (Exception e) { logger.error("Unable to write image.", e); } }
From source file:net.sourceforge.fenixedu.presentationTier.Action.student.onlineTests.StudentTestsAction.java
public ActionForward exportChecksum(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { final String logId = request.getParameter("logId"); final User userView = getUserView(request); if (logId != null && logId.length() != 0) { StudentTestLog studentTestLog = FenixFramework.getDomainObject(logId); if (studentTestLog.getStudent().getPerson().equals(userView.getPerson())) { List<StudentTestLog> studentTestLogs = new ArrayList<StudentTestLog>(); studentTestLogs.add(studentTestLog); byte[] data = ReportsUtils.exportToPdfFileAsByteArray( "net.sourceforge.fenixedu.domain.onlineTests.StudentTestLog.checksumReport", null, studentTestLogs);//from w w w. j ava 2 s .c om response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=" + studentTestLog.getStudent().getNumber() + ".pdf"); response.setContentLength(data.length); ServletOutputStream writer = response.getOutputStream(); writer.write(data); writer.flush(); writer.close(); response.flushBuffer(); return mapping.findForward(""); } } return null; }
From source file:org.fenixedu.academic.ui.struts.action.student.onlineTests.StudentTestsAction.java
public ActionForward exportChecksum(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { final String logId = request.getParameter("logId"); final User userView = getUserView(request); if (logId != null && logId.length() != 0) { StudentTestLog studentTestLog = FenixFramework.getDomainObject(logId); if (studentTestLog.getStudent().getPerson().equals(userView.getPerson())) { List<StudentTestLog> studentTestLogs = new ArrayList<StudentTestLog>(); studentTestLogs.add(studentTestLog); byte[] data = ReportsUtils .generateReport("org.fenixedu.academic.domain.onlineTests.StudentTestLog.checksumReport", null, studentTestLogs) .getData();//from www . ja v a2 s . c om response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=" + studentTestLog.getStudent().getNumber() + ".pdf"); response.setContentLength(data.length); ServletOutputStream writer = response.getOutputStream(); writer.write(data); writer.flush(); writer.close(); response.flushBuffer(); return mapping.findForward(""); } } return null; }
From source file:org.webguitoolkit.ui.util.export.XMLTableExport.java
public void writeTo(Table table, HttpServletResponse response) { TableExportOptions exportOptions = table.getExportOptions(); String filename = exportOptions.getFileName(); if (StringUtils.isEmpty(filename) && table instanceof Table) { filename = StringUtils.isNotEmpty(((Table) table).getTitle()) ? ((Table) table).getTitle() : "sheet"; }/* w w w.j ava 2s. co m*/ try { ServletOutputStream out = response.getOutputStream(); response.setContentType("application/xml"); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + ".xls\""); try { writeTo(table, out); } catch (RuntimeException e1) { logger.error("Error in xml export", e1); response.sendError(500, e1.getMessage()); return; } finally { out.flush(); out.close(); } } catch (IOException e) { logger.error("Error in xml export", e); } }
From source file:ai.h2o.servicebuilder.MakePythonWarServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Long startTime = System.currentTimeMillis(); File tmpDir = null;/*from w ww . java 2s . com*/ try { //create temp directory tmpDir = createTempDirectory("makeWar"); logger.debug("tmpDir " + tmpDir); // create output directories File webInfDir = new File(tmpDir.getPath(), "WEB-INF"); if (!webInfDir.mkdir()) throw new Exception("Can't create output directory (WEB-INF)"); File outDir = new File(webInfDir.getPath(), "classes"); if (!outDir.mkdir()) throw new Exception("Can't create output directory (WEB-INF/classes)"); File libDir = new File(webInfDir.getPath(), "lib"); if (!libDir.mkdir()) throw new Exception("Can't create output directory (WEB-INF/lib)"); // get input files List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); String pojofile = null; String jarfile = null; String mojofile = null; String pythonfile = null; String predictorClassName = null; String pythonenvfile = null; ArrayList<String> pojos = new ArrayList<String>(); ArrayList<String> rawfiles = new ArrayList<String>(); for (FileItem i : items) { String field = i.getFieldName(); String filename = i.getName(); if (filename != null && filename.length() > 0) { if (field.equals("pojo")) { // pojo file name, use this or a mojo file pojofile = filename; pojos.add(pojofile); predictorClassName = filename.replace(".java", ""); FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename)); logger.info("added pojo model {}", filename); } if (field.equals("jar")) { jarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename; FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename)); } if (field.equals("python")) { pythonfile = "WEB-INF" + File.separator + "python.py"; FileUtils.copyInputStreamToFile(i.getInputStream(), new File(webInfDir, "python.py")); } if (field.equals("pythonextra")) { // optional extra files for python pythonfile = "WEB-INF" + File.separator + "lib" + File.separator + filename; FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename)); } if (field.equals("mojo")) { // a raw model zip file, a mojo file (optional) mojofile = filename; rawfiles.add(mojofile); predictorClassName = filename.replace(".zip", ""); FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename)); logger.info("added mojo model {}", filename); } if (field.equals("envfile")) { // optional conda environment file pythonenvfile = filename; FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename)); logger.debug("using conda environment file {}", pythonenvfile); } } } logger.debug("jar {} pojo {} mojo {} python {} envfile {}", jarfile, pojofile, mojofile, pythonfile, pythonenvfile); if ((pojofile == null || jarfile == null) && (mojofile == null || jarfile == null)) throw new Exception("need either pojo and genmodel jar, or raw file and genmodel jar "); if (pojofile != null) { // Compile the pojo runCmd(tmpDir, Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfile, "-d", outDir.getPath(), pojofile), "Compilation of pojo failed"); logger.info("compiled pojo {}", pojofile); } if (servletPath == null) throw new Exception("servletPath is null"); FileUtils.copyDirectoryToDirectory(new File(servletPath, "extra"), tmpDir); String extraPath = "extra" + File.separator; String webInfPath = extraPath + File.separator + "WEB-INF" + File.separator; String srcPath = extraPath + "src" + File.separator; copyExtraFile(servletPath, extraPath, tmpDir, "pyindex.html", "index.html"); copyExtraFile(servletPath, extraPath, tmpDir, "jquery.js", "jquery.js"); copyExtraFile(servletPath, extraPath, tmpDir, "predict.js", "predict.js"); copyExtraFile(servletPath, extraPath, tmpDir, "custom.css", "custom.css"); copyExtraFile(servletPath, webInfPath, webInfDir, "web-pythonpredict.xml", "web.xml"); FileUtils.copyDirectoryToDirectory(new File(servletPath, webInfPath + "lib"), webInfDir); FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "bootstrap"), tmpDir); FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "fonts"), tmpDir); // change the class name in the predictor template file to the predictor we have String modelCode = null; if (!pojos.isEmpty()) { FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), pojos); modelCode = "null"; } else if (!rawfiles.isEmpty()) { FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), rawfiles); modelCode = "MojoModel.load(fileName)"; } InstantiateJavaTemplateFile(tmpDir, modelCode, predictorClassName, "null", pythonenvfile == null ? "" : pythonenvfile, srcPath + "ServletUtil-TEMPLATE.java", "ServletUtil.java"); copyExtraFile(servletPath, srcPath, tmpDir, "PredictPythonServlet.java", "PredictPythonServlet.java"); copyExtraFile(servletPath, srcPath, tmpDir, "InfoServlet.java", "InfoServlet.java"); copyExtraFile(servletPath, srcPath, tmpDir, "StatsServlet.java", "StatsServlet.java"); copyExtraFile(servletPath, srcPath, tmpDir, "PingServlet.java", "PingServlet.java"); copyExtraFile(servletPath, srcPath, tmpDir, "Transform.java", "Transform.java"); copyExtraFile(servletPath, srcPath, tmpDir, "Logging.java", "Logging.java"); // compile extra runCmd(tmpDir, Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", "WEB-INF/lib/*:WEB-INF/classes:extra/WEB-INF/lib/*", "-d", outDir.getPath(), "InfoServlet.java", "StatsServlet.java", "PredictPythonServlet.java", "ServletUtil.java", "PingServlet.java", "Transform.java", "Logging.java"), "Compilation of servlet failed"); // create the war jar file Collection<File> filesc = FileUtils.listFilesAndDirs(webInfDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); filesc.add(new File(tmpDir, "index.html")); filesc.add(new File(tmpDir, "jquery.js")); filesc.add(new File(tmpDir, "predict.js")); filesc.add(new File(tmpDir, "custom.css")); filesc.add(new File(tmpDir, "modelnames.txt")); for (String m : pojos) { filesc.add(new File(tmpDir, m)); } for (String m : rawfiles) { filesc.add(new File(tmpDir, m)); } Collection<File> dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "bootstrap"), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); filesc.addAll(dirc); dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "fonts"), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); filesc.addAll(dirc); File[] files = filesc.toArray(new File[] {}); if (files.length == 0) throw new Exception("Can't list compiler output files (out)"); byte[] resjar = createJarArchiveByteArray(files, tmpDir.getPath() + File.separator); if (resjar == null) throw new Exception("Can't create war of compiler output"); logger.info("war created from {} files, size {}", files.length, resjar.length); // send jar back ServletOutputStream sout = response.getOutputStream(); response.setContentType("application/octet-stream"); String outputFilename = predictorClassName.length() > 0 ? predictorClassName : "h2o-predictor"; response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".war"); response.setContentLength(resjar.length); sout.write(resjar); sout.close(); response.setStatus(HttpServletResponse.SC_OK); Long elapsedMs = System.currentTimeMillis() - startTime; logger.info("Done python war creation in {}", elapsedMs); } catch (Exception e) { logger.error("doPost failed", e); // send the error message back String message = e.getMessage(); if (message == null) message = "no message"; logger.error(message); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().write(message); response.getWriter().write(Arrays.toString(e.getStackTrace())); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } finally { // if the temp directory is still there we delete it if (tmpDir != null && tmpDir.exists()) { try { FileUtils.deleteDirectory(tmpDir); } catch (IOException e) { logger.error("Can't delete tmp directory"); } } } }
From source file:web.CuidadorManager.java
public void download(String url) { String filename = FilenameUtils.getName(url); File file = new File(url); HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext() .getResponse();// ww w. j av a 2 s. c o m response.setHeader("Content-Disposition", "attachment;filename=" + filename); response.setContentLength((int) file.length()); ServletOutputStream out = null; try { FileInputStream input = new FileInputStream(file); byte[] buffer = new byte[1024]; out = response.getOutputStream(); int i = 0; while ((i = input.read(buffer)) != -1) { out.write(buffer); out.flush(); } FacesContext.getCurrentInstance().getResponseComplete(); } catch (IOException err) { err.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException err) { err.printStackTrace(); } } }
From source file:edu.umn.cs.spatialHadoop.visualization.HadoopvizServer.java
/** * This method will handle each time a file need to be fetched from HDFS. * //from w ww.j a va 2 s. c om * @param request * @param response */ private void handleHDFSFetch(HttpServletRequest request, HttpServletResponse response) { try { FileSystem fs = outputPath.getFileSystem(commonParams); String path = request.getRequestURI().replace("/hdfs", ""); Path filePath = new Path(path); LOG.info("Fetching from " + path); FSDataInputStream resource; resource = fs.open(filePath); if (resource == null) { reportError(response, "Cannot load resource '" + filePath + "'", null); return; } byte[] buffer = new byte[1024 * 1024]; ServletOutputStream outResponse = response.getOutputStream(); int size; while ((size = resource.read(buffer)) != -1) { outResponse.write(buffer, 0, size); } resource.close(); outResponse.close(); response.setStatus(HttpServletResponse.SC_OK); if (filePath.toString().endsWith("png")) { response.setContentType("image/png"); } } catch (Exception e) { System.out.println("error happened"); e.printStackTrace(); response.setContentType("text/plain;charset=utf-8"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }