List of usage examples for javax.servlet ServletOutputStream flush
public void flush() throws IOException
From source file:edu.cornell.mannlib.vitro.webapp.controller.harvester.FileHarvestController.java
private void doDownloadTemplatePost(HttpServletRequest request, HttpServletResponse response) { VitroRequest vreq = new VitroRequest(request); FileHarvestJob job = getJob(vreq, vreq.getParameter(PARAMETER_JOB)); File fileToSend = new File(job.getTemplateFilePath()); response.setContentType("application/octet-stream"); response.setContentLength((int) (fileToSend.length())); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileToSend.getName() + "\""); try {/*from w w w. j av a2s .c o m*/ byte[] byteBuffer = new byte[(int) (fileToSend.length())]; DataInputStream inStream = new DataInputStream(new FileInputStream(fileToSend)); ServletOutputStream outputStream = response.getOutputStream(); for (int length = inStream.read(byteBuffer); length != -1; length = inStream.read(byteBuffer)) { outputStream.write(byteBuffer, 0, length); } inStream.close(); outputStream.flush(); outputStream.close(); } catch (IOException e) { log.error(e, e); } }
From source file:org.jspresso.framework.util.resources.server.ResourceProviderServlet.java
/** * {@inheritDoc}/*from w w w .j a v a 2 s. co m*/ */ @SuppressWarnings("unchecked") @Override public void doPost(HttpServletRequest request, HttpServletResponse response) { try { HttpRequestHolder.setServletRequest(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); response.setContentType("text/xml"); ServletOutputStream out = response.getOutputStream(); for (FileItem item : items) { if (!item.isFormField()) { out.print("<resource"); IResourceBase uploadResource = new UploadResourceAdapter("application/octet-stream", item); String resourceId = ResourceManager.getInstance().register(uploadResource); out.print(" id=\"" + resourceId); // Sometimes prevents the browser to parse back the result // out.print("\" name=\"" + HtmlHelper.escapeForHTML(item.getName())); out.println("\" />"); } } out.flush(); out.close(); } catch (Exception ex) { LOG.error("An unexpected error occurred while uploading the content.", ex); } finally { HttpRequestHolder.setServletRequest(null); } }
From source file:com.mbv.web.rest.controller.DeliveryController.java
@RequestMapping(value = "/printExpress", method = RequestMethod.GET) public void printExpress(HttpServletRequest request, HttpServletResponse response) throws MbvException { Long degId = Long.parseLong(request.getParameter("degId")); int printCount = Integer.parseInt(request.getParameter("printCount")); String tspComCode = (String) request.getParameter("tspComCode"); DeliveryBean delivery = deliveryService.getDeliveryBeanById(degId); HttpSession session = request.getSession(); String warehCode = (String) session.getAttribute(MbvConstant.WAREH_CODE); VpSenderEntity sendAddress = deliveryService.getSendAddressByWarehCode(warehCode); if (sendAddress != null) { if (!"sto".equals(tspComCode) && !"yto".equals(tspComCode)) { String province = sendAddress.getProvince(); String city = sendAddress.getCity(); String district = sendAddress.getDistrict(); String address = sendAddress.getAddress(); sendAddress.setAddress(province + " " + city + " " + district + " " + address); }//from w ww . j a v a 2s. c o m } List jasperPrintList = new ArrayList<JasperReport>(); if (!"sto".equals(tspComCode) && !"yto".equals(tspComCode)) { String province = delivery.getProvince(); String city = delivery.getCity(); String district = delivery.getDistrict(); String address = delivery.getDelivAddress(); delivery.setDelivAddress(province + " " + city + " " + district + " " + address); } try { for (int i = 0; i < printCount; i++) { String templateName = tspComCode + "_express.jrxml"; String imageName = tspComCode + ".jpg"; String jasperPath = request.getSession().getServletContext() .getRealPath("/reports/" + templateName); String imageurl = request.getSession().getServletContext().getRealPath("/images/" + imageName); List tmpList = new ArrayList(); Map<String, Object> pram = new HashMap<String, Object>(); pram.put("name", delivery.getConsignee() == null ? "" : delivery.getConsignee()); pram.put("phone", delivery.getMoblie() == null ? "" : delivery.getMoblie()); pram.put("code", delivery.getDelivPstd() == null ? "" : delivery.getDelivPstd()); pram.put("province", delivery.getProvince() == null ? "" : delivery.getProvince()); pram.put("city", delivery.getCity() == null ? "" : delivery.getCity()); pram.put("district", delivery.getDistrict() == null ? "" : delivery.getDistrict()); pram.put("company", ""); pram.put("address", delivery.getDelivAddress() == null ? "" : delivery.getDelivAddress()); pram.put("sendName", sendAddress == null ? "" : sendAddress.getConsignor()); pram.put("sendPhone", sendAddress == null ? "" : sendAddress.getMobile()); pram.put("sendCode", sendAddress == null ? "" : sendAddress.getZip()); pram.put("sendAddress", sendAddress == null ? "" : sendAddress.getAddress()); pram.put("sendProvince", sendAddress == null ? "" : sendAddress.getProvince()); pram.put("sendCity", sendAddress == null ? "" : sendAddress.getCity()); pram.put("sendDistrict", sendAddress == null ? "" : sendAddress.getDistrict()); pram.put("sendCompany", ""); pram.put("docCode", delivery.getDocCode() == null ? "" : delivery.getDocCode()); pram.put("imageurl", imageurl); tmpList.add(pram); JasperReport jasperReport = JasperCompileManager.compileReport(jasperPath); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, pram, new JRBeanCollectionDataSource(tmpList)); request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint); jasperPrintList.add(jasperPrint); } //byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint); //?? ByteArrayOutputStream baos = new ByteArrayOutputStream(); JRPdfExporter exporter = new JRPdfExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrintList); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos); exporter.exportReport(); byte[] bytes = baos.toByteArray(); response.setContentType("application/pdf"); response.setContentLength(bytes.length); ServletOutputStream out = response.getOutputStream(); out.write(bytes); out.flush(); //end } catch (IOException ioe) { System.err.println(ioe.getMessage()); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.mbv.web.rest.controller.DeliveryController.java
@RequestMapping(value = "/printExpressBatch", method = RequestMethod.GET) public void printExpressBatch(HttpServletRequest request, HttpServletResponse response) throws MbvException { HttpSession session = request.getSession(); String warehCode = (String) session.getAttribute(MbvConstant.WAREH_CODE); VpSenderEntity sendAddress = deliveryService.getSendAddressByWarehCode(warehCode); String tspComCode = (String) request.getParameter("tspComCode"); if (sendAddress != null) { if (!"sto".equals(tspComCode) && !"yto".equals(tspComCode)) { String province = sendAddress.getProvince(); String city = sendAddress.getCity(); String district = sendAddress.getDistrict(); String address = sendAddress.getAddress(); sendAddress.setAddress(province + " " + city + " " + district + " " + address); }/* ww w .j av a2 s. c o m*/ } String degIdStr = request.getParameter("degIds"); String[] degIds = degIdStr.split(","); List jasperPrintList = new ArrayList<JasperReport>(); try { for (String degStr : degIds) { Long degId = Long.parseLong(degStr); DeliveryBean delivery = deliveryService.getDeliveryBeanById(degId); if (!"sto".equals(tspComCode) && !"yto".equals(tspComCode)) { String province = delivery.getProvince(); String city = delivery.getCity(); String district = delivery.getDistrict(); String address = delivery.getDelivAddress(); delivery.setDelivAddress(province + " " + city + " " + district + " " + address); } String templateName = tspComCode + "_express.jrxml"; String imageName = tspComCode + ".jpg"; String jasperPath = request.getSession().getServletContext() .getRealPath("/reports/" + templateName); String imageurl = request.getSession().getServletContext().getRealPath("/images/" + imageName); List tmpList = new ArrayList(); Map<String, Object> pram = new HashMap<String, Object>(); pram.put("name", delivery.getConsignee() == null ? "" : delivery.getConsignee()); pram.put("phone", delivery.getMoblie() == null ? "" : delivery.getMoblie()); pram.put("code", delivery.getDelivPstd() == null ? "" : delivery.getDelivPstd()); pram.put("province", delivery.getProvince() == null ? "" : delivery.getProvince()); pram.put("city", delivery.getCity() == null ? "" : delivery.getCity()); pram.put("district", delivery.getDistrict() == null ? "" : delivery.getDistrict()); pram.put("company", ""); pram.put("address", delivery.getDelivAddress() == null ? "" : delivery.getDelivAddress()); pram.put("sendName", sendAddress == null ? "" : sendAddress.getConsignor()); pram.put("sendPhone", sendAddress == null ? "" : sendAddress.getMobile()); pram.put("sendCode", sendAddress == null ? "" : sendAddress.getZip()); pram.put("sendAddress", sendAddress == null ? "" : sendAddress.getAddress()); pram.put("sendProvince", sendAddress == null ? "" : sendAddress.getProvince()); pram.put("sendCity", sendAddress == null ? "" : sendAddress.getCity()); pram.put("sendDistrict", sendAddress == null ? "" : sendAddress.getDistrict()); pram.put("sendCompany", ""); pram.put("docCode", delivery.getDocCode() == null ? "" : delivery.getDocCode()); pram.put("imageurl", imageurl); tmpList.add(pram); JasperReport jasperReport = JasperCompileManager.compileReport(jasperPath); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, pram, new JRBeanCollectionDataSource(tmpList)); request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint); jasperPrintList.add(jasperPrint); } //byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint); //?? ByteArrayOutputStream baos = new ByteArrayOutputStream(); JRPdfExporter exporter = new JRPdfExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrintList); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos); exporter.exportReport(); byte[] bytes = baos.toByteArray(); response.setContentType("application/pdf"); response.setContentLength(bytes.length); ServletOutputStream out = response.getOutputStream(); out.write(bytes); out.flush(); //end } catch (IOException ioe) { System.err.println(ioe.getMessage()); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.java2s.SendFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { //get the file name from the 'file' parameter String fileName = request.getParameter("file"); if (fileName == null || fileName.equals("")) throw new ServletException("Invalid or non-existent file parameter in SendPdf component."); if (fileName.indexOf(".pdf") == -1) fileName = fileName + ".pdf"; ServletOutputStream stream = null; BufferedInputStream buf = null; HttpServletResponse httpResp = null; try {/* www .j a v a 2 s .co m*/ httpResp = (HttpServletResponse) response; stream = httpResp.getOutputStream(); File pdf = new File(PDF_DIR + "/" + fileName); //set response headers httpResp.setContentType(PDF_CONTENT_TYPE); httpResp.addHeader("Content-Disposition", "attachment; filename=" + fileName); httpResp.setContentLength((int) pdf.length()); FileInputStream input = new FileInputStream(pdf); buf = new BufferedInputStream(input); int readBytes = 0; //read from the file; write to the ServletOutputStream while ((readBytes = buf.read()) != -1) stream.write(readBytes); } catch (Exception ioe) { // throw new ServletException(ioe.getMessage()); System.out.println(ioe.getMessage()); } finally { if (buf != null) buf.close(); if (stream != null) { stream.flush(); //stream.close(); } } //end finally chain.doFilter(request, httpResp); }
From source file:org.inbio.ait.web.ajax.controller.QueryController.java
/** * Write the XML to be parsed on the analysis view * Case: three parameters (1)//w ww . ja v a 2s. com * @param request * @param response * @param totalMatch * @param matchesByPolygon * @return * @throws java.lang.Exception */ private ModelAndView writeReponse1(HttpServletRequest request, HttpServletResponse response, List<Node> matchesByPolygon, List<Node> matchesByIndicator, Long totalMatches, Long totalPercentage) throws Exception { response.setCharacterEncoding("ISO-8859-1"); response.setContentType("text/xml"); ServletOutputStream out = response.getOutputStream(); StringBuilder result = new StringBuilder(); result.append("<?xml version='1.0' encoding='ISO-8859-1'?><response>"); result.append("<type>1</type>"); result.append("<total>" + totalMatches + "</total>"); result.append("<totalp>" + totalPercentage + "</totalp>"); for (Node mp : matchesByPolygon) { result.append("<bypolygon>"); result.append("<abs>" + mp.getValue1() + "</abs>"); result.append("<per>" + mp.getValue2() + "</per>"); result.append("</bypolygon>"); } for (Node mi : matchesByIndicator) { result.append("<byindicator>"); result.append("<abs>" + mi.getValue1() + "</abs>"); result.append("<per>" + mi.getValue2() + "</per>"); result.append("</byindicator>"); } result.append("</response>"); out.println(result.toString()); out.flush(); out.close(); return null; }
From source file:org.n52.smartsensoreditor.controller.SaveLocalControllerSML.java
/** * Hanlde user request/*from w w w. ja v a 2s.com*/ * * @param request * @param pResponse * @return * @throws Exception */ public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse pResponse) throws Exception { // get document stored in backenservice Document lDoc = mBackendService.mergeBackend(); XPathUtil lUtil = new XPathUtil(); lUtil.setContext(editorContext); String lFileId = lUtil.evaluateAsString("//gmd:fileIdentifier/gco:CharacterString/text()", lDoc); if (lFileId.equals("")) { lFileId = lUtil.evaluateAsString("/*/gml:identifier/text()", lDoc); } lFileId = lFileId.trim(); // set response attributes //pResponse.setContentType("application/x-download"); pResponse.setContentType(getContentType() == null ? "application/x-download" : getContentType()); // set header if (getSetHeader() != null) { for (Map.Entry<String, String> entry : getSetHeader().entrySet()) { pResponse.setHeader(entry.getKey(), entry.getValue()); } } // add header if (getAddHeader() != null) { for (Map.Entry<String, String> entry : getAddHeader().entrySet()) { pResponse.addHeader(entry.getKey(), entry.getValue()); } } pResponse.setHeader("Content-disposition", "attachment; filename=" + lFileId + ".xml"); if (LOG.isDebugEnabled()) LOG.debug("Preparing download for document with id: " + lFileId); ServletOutputStream lOutputStream = pResponse.getOutputStream(); try { // write document to servlet response TransformerFactory tf = TransformerFactory.newInstance(); // identity Transformer t = tf.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.transform(new DOMSource(lDoc), new StreamResult(lOutputStream)); } catch (Exception e) { pResponse.setHeader("Content-disposition", "attachment; filename=ExportError.xml"); lOutputStream.println("<?xml version='1.0' encoding=\"UTF-8\" standalone=\"no\" ?>"); lOutputStream.println("<ExportExceptionReport version=\"1.1.0\">"); lOutputStream.println(" Request rejected due to errors."); lOutputStream.println(" Reason: " + e.getMessage()); lOutputStream.println("</ExportExceptionReport>"); lOutputStream.println(); LOG.error("Exception while copying from input to output stream: " + e.getMessage()); } finally { lOutputStream.flush(); lOutputStream.close(); } // forward return null; }
From source file:com.ephesoft.gxt.systemconfig.server.ExportRegexPoolServlet.java
/** * Overridden doGet method./*from www .j ava 2 s . c o m*/ */ @Override public void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class); final RegexGroupService regexGroupService = this.getSingleBeanOfType(RegexGroupService.class); final List<RegexGroup> regexGroupList = regexGroupService.getRegexGroups(); if (regexGroupList == null) { LOGGER.error("Regex group list is null."); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Regex group list is null."); } else { try { final Calendar cal = Calendar.getInstance(); final String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation(); final SimpleDateFormat formatter = new SimpleDateFormat(CoreCommonConstant.DATE_FORMAT); final String formattedDate = formatter.format(new Date()); final String zipFileName = StringUtil.concatenate(SystemConfigConstants.REGEX_POOL, CoreCommonConstant.UNDERSCORE, formattedDate, CoreCommonConstant.UNDERSCORE, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.SECOND)); final String tempFolderLocation = StringUtil.concatenate(exportSerailizationFolderPath, File.separator, zipFileName); final File copiedFolder = new File(tempFolderLocation); if (copiedFolder.exists()) { copiedFolder.delete(); } // Setting the parent of regex pattern list to null for exporting RegexUtil.exportRegexPatterns(regexGroupList); // Setting the id of regex group list to "0" for exporting for (final RegexGroup regexGroup : regexGroupList) { regexGroup.setId(0); } copiedFolder.mkdirs(); final File serializedExportFile = new File(tempFolderLocation + File.separator + SystemConfigConstants.REGEX_POOL + SystemConfigConstants.SERIALIZATION_EXT); try { SerializationUtils.serialize((Serializable) regexGroupList, new FileOutputStream(serializedExportFile)); final File originalFolder = new File( StringUtil.concatenate(batchSchemaService.getBaseSampleFDLock(), File.separator, SystemConfigConstants.REGEX_POOL)); if (originalFolder.isDirectory()) { final String[] folderList = originalFolder.list(); Arrays.sort(folderList); } } catch (final FileNotFoundException fileNotFoundException) { // Unable to read serializable file LOGGER.error("Error occurred while creating the serializable file." + fileNotFoundException, fileNotFoundException); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occurred while creating the serializable file."); } resp.setContentType(SystemConfigConstants.APPLICATION_X_ZIP); resp.setHeader(SystemConfigConstants.CONTENT_DISPOSITION, StringUtil.concatenate(SystemConfigConstants.ATTACHMENT_FILENAME, zipFileName, SystemConfigConstants.ZIP_EXT, SystemConfigConstants.HEADER_MODE)); ServletOutputStream out = null; ZipOutputStream zipOutput = null; try { out = resp.getOutputStream(); zipOutput = new ZipOutputStream(out); FileUtils.zipDirectory(tempFolderLocation, zipOutput, zipFileName); resp.setStatus(HttpServletResponse.SC_OK); } catch (final IOException ioException) { // Unable to create the temporary export file(s)/folder(s) LOGGER.error("Error occurred while creating the zip file." + ioException, ioException); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again."); } finally { // clean up code if (zipOutput != null) { zipOutput.close(); } if (out != null) { out.flush(); } FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder); } } catch (final Exception exception) { LOGGER.error("ERROR IN EXPORT: " + exception, exception); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again."); } } }
From source file:com.ephesoft.gxt.foldermanager.server.UploadDownloadFilesServlet.java
private void downloadFile(HttpServletRequest req, HttpServletResponse response, String currentFileDownloadPath) { DataInputStream in = null;/*w ww. j a v a 2s . co m*/ ServletOutputStream outStream = null; try { outStream = response.getOutputStream(); File file = new File(currentFileDownloadPath); int length = 0; String mimetype = "application/octet-stream"; response.setContentType(mimetype); response.setContentLength((int) file.length()); String fileName = file.getName(); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); byte[] byteBuffer = new byte[1024]; in = new DataInputStream(new FileInputStream(file)); while ((in != null) && ((length = in.read(byteBuffer)) != -1)) { outStream.write(byteBuffer, 0, length); } } catch (IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (outStream != null) { try { outStream.flush(); } catch (IOException e) { } try { outStream.close(); } catch (IOException e) { } } } }
From source file:org.openmrs.module.tracdataquality.web.controller.DownloadController.java
/** * Auto generated method comment/* w w w . jav a 2s .com*/ * * @param request * @param response * @param patients * @param filename * @param title * @throws IOException */ private void doDownload(HttpServletRequest request, HttpServletResponse response, List<Patient> patients, String filename, String title) throws IOException { //creating file writer object ServletOutputStream outputStream = response.getOutputStream(); //creating the file response.setContentType("text/plain"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); //creating file header outputStream.println("Report Name, " + title); outputStream.println("Author, " + Context.getAuthenticatedUser().getPersonName()); outputStream.println("Printed on, " + new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss").format(new Date())); outputStream.println("Number of Patients, " + patients.size()); outputStream.println(); outputStream.println("Identifier,Given Name,Middle Name,Family Name,Age,Gender,Creator"); outputStream.println(); //populating content of the report for (Patient patient : patients) { outputStream.println(patient.getPatientIdentifier() + "," + patient.getGivenName() + "," + patient.getMiddleName() + "," + patient.getFamilyName() + "," + patient.getAge() + "," + patient.getGender() + "," + patient.getCreator()); } outputStream.flush(); outputStream.close(); }