List of usage examples for javax.servlet ServletOutputStream close
public void close() throws IOException
From source file:org.openmrs.module.pmtct.util.FileExporter.java
public void exportToCSVFile2(HttpServletRequest request, HttpServletResponse response, List<Object> patientList, String filename, String title) throws Exception { ServletOutputStream outputStream = null; try {//from www . j av a 2 s .co m outputStream = response.getOutputStream(); Patient p; PatientService ps = Context.getPatientService(); response.setContentType("text/plain"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); outputStream.println("" + title); outputStream.println("Number of Patients: " + patientList.size()); outputStream.println(); outputStream.println("No.,Identifier, Names, Gender, BirthDay, Enrollment Date"); outputStream.println(); int ids = 0; for (Object patient : patientList) { Object[] o = (Object[]) patient; p = ps.getPatient(Integer.parseInt(o[1].toString())); ids += 1; outputStream.println( ids + "," + p.getActiveIdentifiers().get(0).getIdentifier() + "," + p.getPersonName() + "," + p.getGender() + "," + sdf.format(p.getBirthdate()) + "," + o[4].toString()); } outputStream.flush(); } catch (Exception e) { log.error(e.getMessage()); } finally { if (null != outputStream) outputStream.close(); } }
From source file:com.indeed.imhotep.web.QueryServlet.java
private void handleShowStatement(final HttpServletRequest req, final HttpServletResponse resp) throws IOException { final ServletOutputStream outputStream = resp.getOutputStream(); final boolean json = req.getParameter("json") != null; if (json) {/*from ww w. ja va 2 s . c o m*/ resp.setContentType(MediaType.APPLICATION_JSON_VALUE); final ObjectMapper mapper = new ObjectMapper(); final ObjectNode jsonRoot = mapper.createObjectNode(); final ArrayNode array = mapper.createArrayNode(); jsonRoot.put("datasets", array); for (DatasetMetadata dataset : metadata.getDatasets().values()) { final ObjectNode datasetInfo = mapper.createObjectNode(); dataset.toJSON(datasetInfo, mapper, true); array.add(datasetInfo); } mapper.writeValue(outputStream, jsonRoot); } else { for (DatasetMetadata dataset : metadata.getDatasets().values()) { outputStream.println(dataset.getName()); } } outputStream.close(); }
From source file:com.indeed.imhotep.web.QueryServlet.java
private void handleDescribeDataset(HttpServletRequest req, HttpServletResponse resp, DescribeStatement parsedQuery) throws IOException { final ServletOutputStream outputStream = resp.getOutputStream(); final String dataset = parsedQuery.dataset; final DatasetMetadata datasetMetadata = metadata.getDataset(dataset); final boolean json = req.getParameter("json") != null; if (json) {/* w w w . j a v a 2s . c om*/ resp.setContentType(MediaType.APPLICATION_JSON_VALUE); final ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); final ObjectNode jsonRoot = mapper.createObjectNode(); datasetMetadata.toJSON(jsonRoot, mapper, false); mapper.writeValue(outputStream, jsonRoot); } else { for (FieldMetadata field : datasetMetadata.getFields().values()) { final String description = Strings.nullToEmpty(field.getDescription()); outputStream.println(field.getName() + "\t" + description); } } outputStream.close(); }
From source file:org.sakaiproject.signup.tool.jsf.SignupUIBaseBean.java
/** * Send a warning message to user about failed ICS file generation * @param fileName//from w w w .j a v a 2 s .c o m * @param warningMsg */ protected void sendDownloadWarning(String fileName, String warningMsg) { FacesContext fc = FacesContext.getCurrentInstance(); ServletOutputStream out = null; try { HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse(); response.reset(); response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0"); response.setContentType("text/plain"); response.setHeader("Content-disposition", "attachment; filename=" + fileName); out = response.getOutputStream(); warningMsg = warningMsg != null ? warningMsg : "Missing Scheduler tool on site"; out.print(warningMsg); out.flush(); } catch (IOException ex) { logger.warn("Error generating file for download:" + ex.getMessage()); } finally { try { out.close(); } catch (Exception e) { //do nothing; } } fc.responseComplete(); }
From source file:org.exist.http.SOAPServer.java
public void doPost(DBBroker broker, HttpServletRequest request, HttpServletResponse response, String path) throws BadRequestException, PermissionDeniedException, NotFoundException, IOException { /*// www . ja v a 2s.c o m * Example incoming SOAP Request * <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <echo xmlns="http://localhost:8080/exist/servlet/db/echo.xqws"> <arg1>adam</arg1> </echo> </SOAP-ENV:Body> </SOAP-ENV:Envelope> */ // 1) Read the incoming SOAP request final InputStream is = request.getInputStream(); final byte[] buf = new byte[request.getContentLength()]; int bytes = 0; int offset = 0; final int max = 4096; while ((bytes = is.read(buf, offset, max)) != -1) { offset += bytes; } // 2) Create an XML Document from the SOAP Request Document soapRequest = null; try { soapRequest = BuildXMLDocument(buf); } catch (final Exception e) { LOG.debug(e.getMessage()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, new XPathException( "Unable to construct an XML document from the SOAP Request, probably an invalid request: " + e.getMessage(), e)), "text/html", ENCODING); return; } try { final StringWriter out = new StringWriter(); broker.getSerializer().serialize((ElementImpl) soapRequest.getDocumentElement(), out); //System.out.println(out.toString()); } catch (final SAXException e) { LOG.error("Error during serialization.", e); } // 3) Validate the SOAP Request //TODO: validate the SOAP Request // 4) Extract the function call from the SOAP Request final NodeList nlBody = soapRequest.getDocumentElement().getElementsByTagNameNS(Namespaces.SOAP_ENVELOPE, "Body"); if (nlBody == null) { LOG.error("Style Parameter wrapped not supported yet"); } final Node nSOAPBody = nlBody.item(0); // DW: can return NULL ! case: style ParameterWrapped final NodeList nlBodyChildren = nSOAPBody.getChildNodes(); Node nSOAPFunction = null; for (int i = 0; i < nlBodyChildren.getLength(); i++) { Node bodyChild = nlBodyChildren.item(i); if (bodyChild.getNodeType() == Node.ELEMENT_NODE) { nSOAPFunction = bodyChild; break; } } // Check the namespace for the function in the SOAP document is the same as the request path? final String funcNamespace = nSOAPFunction.getNamespaceURI(); if (funcNamespace != null) { if (!funcNamespace.equals(request.getRequestURL().toString())) { //function in SOAP request has an invalid namespace response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, "SOAP Function call has invalid namespace, got: " + funcNamespace + " but expected: " + request.getRequestURL().toString(), "text/html", ENCODING); return; } } else { //function in SOAP request has no namespace response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, "SOAP Function call has no namespace, expected: " + request.getRequestURL().toString(), "text/html", ENCODING); return; } // 4.5) Detemine encoding style final String encodingStyle = ((org.w3c.dom.Element) nSOAPFunction).getAttributeNS(Namespaces.SOAP_ENVELOPE, "encodingStyle"); boolean isRpcEncoded = (encodingStyle != null && "http://schemas.xmlsoap.org/soap/encoding/".equals(encodingStyle)); // As this detection is a "quirk" which is not always available, let's use a better one... if (!isRpcEncoded) { final NodeList nlSOAPFunction = nSOAPFunction.getChildNodes(); for (int i = 0; i < nlSOAPFunction.getLength(); i++) { final Node functionChild = nlSOAPFunction.item(i); if (functionChild.getNodeType() == Node.ELEMENT_NODE) { if (((org.w3c.dom.Element) functionChild).hasAttributeNS(Namespaces.SCHEMA_INSTANCE_NS, "type")) { isRpcEncoded = true; break; } } } } // 5) Execute the XQWS function indicated by the SOAP request try { //Get the internal description for the function requested by SOAP (should be in the cache) final XQWSDescription description = getXQWSDescription(broker, path, request); //Create an XQuery to call the XQWS function final CompiledXQuery xqCallXQWS = XQueryExecuteXQWSFunction(broker, nSOAPFunction, description, request, response); //xqCallXQWS final XQuery xqueryService = broker.getXQueryService(); final Sequence xqwsResult = xqueryService.execute(xqCallXQWS, null); // 6) Create a SOAP Response describing the Result String funcName = nSOAPFunction.getLocalName(); if (funcName == null) { funcName = nSOAPFunction.getNodeName(); } final byte[] result = description.getSOAPResponse(funcName, xqwsResult, request, isRpcEncoded); // 7) Send the SOAP Response to the http servlet response response.setContentType(MimeType.XML_LEGACY_TYPE.getName()); final ServletOutputStream os = response.getOutputStream(); final BufferedOutputStream bos = new BufferedOutputStream(os); bos.write(result); bos.close(); os.close(); } catch (final XPathException xpe) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, xpe), "text/html", ENCODING); } catch (final SAXException saxe) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, new XPathException( "SAX exception while transforming node: " + saxe.getMessage(), saxe)), "text/html", ENCODING); } catch (final TransformerConfigurationException tce) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); writeResponse(response, formatXPathException(null, path, new XPathException("SAX exception while transforming node: " + tce.getMessage(), tce)), "text/html", ENCODING); } }
From source file:org.openxdata.server.servlet.DataImportServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletOutputStream out = response.getOutputStream(); try {/*from www .j a v a2 s . c o m*/ // authenticate user User user = getUser(request.getHeader("Authorization")); if (user != null) { log.info("authenticated user:"); // check msisdn String msisdn = request.getParameter("msisdn"); if (msisdn != null && !msisdn.equals("")) { // if an msisdn is sent, then we retrieve the user with that phone number authenticateUserBasedOnMsisd(msisdn); } // can be empty or null, then the default is used. this parameter is a key in the settings table indicating the classname of the serializer to use String serializer = request.getParameter("serializer"); // input stream // first byte contains number of forms (x) // followed by x number of UTF strings (use writeUTF method in DataOutput) formDownloadService.submitForms(request.getInputStream(), out, serializer); } else { response.setHeader("WWW-Authenticate", "BASIC realm=\"openxdata\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } } catch (UserNotFoundException userNotFound) { out.println("Invalid msisdn"); response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } catch (Exception e) { log.error("Could not import data", e); out.println(e.getMessage()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { out.close(); } }
From source file:com.carfinance.module.common.controller.DocumentDownloadController.java
/** * ??/* w w w . j a v a 2 s . c o m*/ * @param model * @param request * @param response */ @RequestMapping(value = "/pdfhunchecontrace", method = RequestMethod.GET) public void pdfHuncheContrace(Model model, HttpServletRequest request, HttpServletResponse response) { String contrace_id_str = request.getParameter("contrace_id"); String org_id = ""; String contrace_no = ""; String customer_name = ""; String vehicle_id = ""; String daily_available_km = ""; VehicleContraceInfo vehicleContraceInfo = this.vehicleServiceManageService .getVehicleContraceInfoById(Long.valueOf(contrace_id_str)); if (vehicleContraceInfo != null) { org_id = String.valueOf(vehicleContraceInfo.getOrg_id()); contrace_no = vehicleContraceInfo.getContrace_no(); customer_name = vehicleContraceInfo.getCustomer_name(); daily_available_km = vehicleContraceInfo.getDaily_available_km() + ""; } else { PropertyContraceInfo propertyContraceInfo = this.vehicleServiceManageService .getPropertyContraceInfoById(Long.valueOf(contrace_id_str)); if (propertyContraceInfo != null) { org_id = String.valueOf(propertyContraceInfo.getOrg_id()); contrace_no = propertyContraceInfo.getContrace_no(); customer_name = propertyContraceInfo.getCustomer_name(); } } List<VehicleContraceVehsInfo> vehicleContraceVehsInfoList = this.vehicleServiceManageService .getVehicleContraceVehsListByContraceId(Long.valueOf(contrace_id_str)); //1.ContentType response.setContentType("multipart/form-data"); //2.????(??a.pdf) response.setHeader("Content-Disposition", "attachment;fileName=" + contrace_no + ".pdf"); Document pdfDoc = new Document(PageSize.A4, 50, 50, 50, 50); // ?? pdf ? try { BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false); Font bold_fontChinese = new Font(bfChinese, 18, Font.BOLD, BaseColor.BLACK); Font normal_fontChinese = new Font(bfChinese, 12, Font.NORMAL, BaseColor.BLACK); Font normal_desc_fontChinese = new Font(bfChinese, 6, Font.NORMAL, BaseColor.BLACK); FileOutputStream pdfFile = new FileOutputStream( new File(appProps.get("hunche.contrace.download.path") + contrace_no + ".pdf")); // pdf ? Paragraph paragraph1 = new Paragraph("???", bold_fontChinese); paragraph1.setAlignment(Element.ALIGN_CENTER); Paragraph paragraph2 = new Paragraph( "???", normal_fontChinese); Paragraph paragraph3 = new Paragraph("" + customer_name + " (", normal_fontChinese); Paragraph paragraph4 = new Paragraph( "?????________________???", normal_fontChinese); Paragraph paragraph5 = new Paragraph("??????", normal_fontChinese); // table PdfPTable table = new PdfPTable(4); table.setWidthPercentage(100); table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT); PdfPCell cell = new PdfPCell(); cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); // cell.setPhrase(new Paragraph("?", normal_fontChinese)); table.addCell(cell); cell.setPhrase(new Paragraph("", normal_fontChinese)); table.addCell(cell); cell.setPhrase(new Paragraph("?/", normal_fontChinese)); table.addCell(cell); cell.setPhrase(new Paragraph("?", normal_fontChinese)); table.addCell(cell); // ? for (VehicleContraceVehsInfo v : vehicleContraceVehsInfoList) { PdfPCell newcell = new PdfPCell(); newcell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER); newcell.setPhrase(new Paragraph("1", normal_fontChinese)); table.addCell(newcell); newcell.setPhrase(new Paragraph(v.getModel(), normal_fontChinese)); table.addCell(newcell); newcell.setPhrase(new Paragraph(v.getDaily_price() + "", normal_fontChinese)); table.addCell(newcell); newcell.setPhrase(new Paragraph(daily_available_km, normal_fontChinese)); table.addCell(newcell); } Paragraph paragraph6 = new Paragraph( "??_________________________________________________________________", normal_fontChinese); Paragraph paragraph7 = new Paragraph( "____________________________?______", normal_fontChinese); Paragraph paragraph8 = new Paragraph("????", normal_fontChinese); Paragraph paragraph9 = new Paragraph( "???________________________???________________________", normal_fontChinese); Paragraph paragraph10 = new Paragraph("?", normal_fontChinese); Paragraph paragraph11 = new Paragraph( "???????????????", normal_fontChinese); Paragraph paragraph12 = new Paragraph("?", normal_fontChinese); Paragraph paragraph13 = new Paragraph( "??????????????", normal_fontChinese); Paragraph paragraph14 = new Paragraph( "?????????", normal_fontChinese); Paragraph paragraph15 = new Paragraph("?????", normal_fontChinese); Paragraph paragraph16 = new Paragraph( "(/) (/)", normal_fontChinese); Paragraph paragraph17 = new Paragraph( " ??", normal_fontChinese); Paragraph paragraph18 = new Paragraph( "?? ?? ", normal_fontChinese); Paragraph paragraph19 = new Paragraph( " 201 ", normal_fontChinese); // Document ?File PdfWriter ? PdfWriter.getInstance(pdfDoc, pdfFile); pdfDoc.open(); // Document // ?? pdfDoc.add(paragraph1); pdfDoc.add(new Chunk("\n\n")); pdfDoc.add(paragraph2); pdfDoc.add(paragraph3); pdfDoc.add(paragraph4); pdfDoc.add(paragraph5); pdfDoc.add(table); pdfDoc.add(paragraph6); pdfDoc.add(paragraph7); pdfDoc.add(paragraph8); pdfDoc.add(paragraph9); pdfDoc.add(paragraph10); pdfDoc.add(paragraph11); pdfDoc.add(paragraph12); pdfDoc.add(paragraph13); pdfDoc.add(paragraph14); pdfDoc.add(paragraph15); pdfDoc.add(paragraph16); pdfDoc.add(paragraph17); pdfDoc.add(paragraph18); pdfDoc.add(paragraph19); pdfDoc.close(); ServletOutputStream out; //File(?download.pdf) File file = new File(appProps.get("hunche.contrace.download.path") + contrace_no + ".pdf"); try { FileInputStream inputStream = new FileInputStream(file); //3.response?ServletOutputStream(out) out = response.getOutputStream(); int b = 0; byte[] buffer = new byte[512]; while (b != -1) { b = inputStream.read(buffer); //4.?(out) out.write(buffer, 0, b); } inputStream.close(); out.close(); out.flush(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.ephesoft.dcma.gwt.foldermanager.server.UploadDownloadFilesServlet.java
private void downloadFile(HttpServletResponse response, String currentFileDownloadPath) { LOG.info(DOWNLOADING_FILE_FROM_PATH + currentFileDownloadPath); DataInputStream inputStream = null; ServletOutputStream outStream = null; try {//from www . ja va 2s . com 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 + CLOSING_QUOTES); byte[] byteBuffer = new byte[1024]; inputStream = new DataInputStream(new FileInputStream(file)); length = inputStream.read(byteBuffer); while ((inputStream != null) && (length != -1)) { outStream.write(byteBuffer, 0, length); length = inputStream.read(byteBuffer); } LOG.info(DOWNLOAD_COMPLETED_FOR_FILEPATH + currentFileDownloadPath); } catch (IOException e) { LOG.error(EXCEPTION_OCCURED_WHILE_DOWNLOADING_A_FILE_FROM_THE_FILE_PATH + currentFileDownloadPath); LOG.error(e.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { LOG.error(UNABLE_TO_CLOSE_INPUT_STREAM_FOR_FILE_DOWNLOAD); } } if (outStream != null) { try { outStream.flush(); } catch (IOException e) { LOG.error(UNABLE_TO_FLUSH_OUTPUT_STREAM_FOR_DOWNLOAD); } try { outStream.close(); } catch (IOException e) { LOG.error(UNABLE_TO_CLOSE_OUTPUT_STREAM_FOR_DOWNLOAD); } } } }
From source file:it.cnr.icar.eric.server.interfaces.rest.QueryManagerURLHandler.java
/** Write the directory listing showing specified objects */ private void writeDirectoryListing(List<?> roList) throws IOException, RegistryException { ServletOutputStream sout = null; String requestURL = request.getRequestURL().toString() + "?" + request.getQueryString(); response.setContentType("text/html; charset=UTF-8"); try {//from w ww .j a va 2s.com sout = response.getOutputStream(); sout.println("<html>"); sout.println("<head>"); sout.println("<title>Index of " + requestURL + "</title>"); sout.println("</head>"); sout.println("<body>"); sout.println("<h1>Index of " + requestURL + "</h1>"); sout.println("<pre>ObjectType\t\tName\t\tVersion\t\tContent Version\t\tLogical ID"); sout.println("<hr/>"); Iterator<?> iter = roList.iterator(); while (iter.hasNext()) { // RegistryObjectType ro = (RegistryObjectType)iter.next(); // take ComplexType from Element @SuppressWarnings("unchecked") RegistryObjectType ebRegistryObjectType = ((JAXBElement<RegistryObjectType>) iter.next()) .getValue(); writeDirectoryListingItem(sout, ebRegistryObjectType); } sout.println("</pre>"); sout.println("<hr/>"); sout.println("<address>freebXML Regisry Server version 3.0</address>"); sout.println("</body>"); sout.println("</html>"); } finally { if (sout != null) { sout.close(); } } }
From source file:de.sub.goobi.metadaten.FileManipulation.java
/** * Download file./*www. j a v a2 s. c o m*/ */ public void downloadFile() { URI downloadFile = null; int imageOrder = Integer.parseInt(imageSelection); DocStruct page = metadataBean.getDigitalDocument().getPhysicalDocStruct().getAllChildren().get(imageOrder); String imagename = page.getImageName(); String filenamePrefix = imagename.substring(0, imagename.lastIndexOf(".")); URI processSubTypeURI = serviceManager.getFileService().getProcessSubTypeURI(metadataBean.getProcess(), ProcessSubType.IMAGE, currentFolder); ArrayList<URI> filesInFolder = fileService.getSubUris(processSubTypeURI); for (URI currentFile : filesInFolder) { String currentFileName = fileService.getFileName(currentFile); String currentFileNamePrefix = currentFileName.substring(0, currentFileName.lastIndexOf(".")); if (filenamePrefix.equals(currentFileNamePrefix)) { downloadFile = currentFile; break; } } if (downloadFile == null || !fileService.fileExist(downloadFile)) { List<String> paramList = new ArrayList<>(); // paramList.add(metadataBean.getMyProzess().getTitel()); paramList.add(filenamePrefix); paramList.add(currentFolder); Helper.setFehlerMeldung(Helper.getTranslation("MetsEditorMissingFile", paramList)); return; } FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.getResponseComplete()) { HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); InputStream in = null; ServletOutputStream out = null; try { String fileName = fileService.getFileName(downloadFile); ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String contentType = servletContext.getMimeType(fileName); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); in = fileService.read(downloadFile); out = response.getOutputStream(); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } out.flush(); } catch (IOException e) { logger.error("IOException while exporting run note", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error(e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.error(e); } } } facesContext.responseComplete(); } }