List of usage examples for javax.servlet ServletOutputStream close
public void close() throws IOException
From source file:org.n52.smartsensoreditor.controller.SaveLocalControllerSML.java
/** * Hanlde user request/*w w w. j a v a2 s. c o m*/ * * @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:org.codelabor.system.file.web.servlet.FileUploadServlet.java
/** * ?? ??./*from w ww .j ava 2s . co m*/ * * @param request * * @param response * ? * @throws Exception * */ protected void view(HttpServletRequest request, HttpServletResponse response) throws Exception { WebApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(this.getServletContext()); FileManager fileManager = (FileManager) ctx.getBean("fileManager"); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap: {}", paramMap.toString()); String fileId = (String) paramMap.get("fileId"); StringBuilder sb = new StringBuilder(); FileDTO fileDTO; fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); InputStream inputStream = null; if (StringUtils.isNotEmpty(repositoryPath)) { // FILE_SYSTEM sb.setLength(0); sb.append(repositoryPath); if (!repositoryPath.endsWith(File.separator)) { sb.append(File.separator); } sb.append(uniqueFilename); File file = new File(sb.toString()); inputStream = new FileInputStream(file); } else { // DATABASE byte[] bytes = new byte[] {}; if (fileDTO.getFileSize() > 0) { bytes = fileDTO.getBytes(); } inputStream = new ByteArrayInputStream(bytes); } response.setContentType(fileDTO.getContentType()); // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream); int bytesRead; byte buffer[] = new byte[2048]; while ((bytesRead = bufferdInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } // flush stream bufferedOutputStream.flush(); // close stream inputStream.close(); bufferdInputStream.close(); servletOutputStream.close(); bufferedOutputStream.close(); }
From source file:org.openmrs.module.tracdataquality.web.controller.DownloadController.java
/** * Auto generated method comment/*from ww w.j a v a 2 s . c om*/ * * @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(); }
From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java
/** * ?? .//from www . j a va 2s .c om * * @param request * * @param response * ? * @throws Exception * */ protected void download(HttpServletRequest request, HttpServletResponse response) throws Exception { WebApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(this.getServletContext()); FileManager fileManager = (FileManager) ctx.getBean("fileManager"); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap: {}", paramMap.toString()); String fileId = (String) paramMap.get("fileId"); StringBuilder sb = new StringBuilder(); FileDTO fileDTO; fileDTO = fileManager.selectFileByFileId(fileId); logger.debug("fileDTO: {}", fileDTO); String repositoryPath = fileDTO.getRepositoryPath(); String uniqueFilename = fileDTO.getUniqueFilename(); String realFilename = fileDTO.getRealFilename(); InputStream inputStream = null; if (StringUtils.isNotEmpty(repositoryPath)) { // FILE_SYSTEM sb.setLength(0); sb.append(repositoryPath); if (!repositoryPath.endsWith(File.separator)) { sb.append(File.separator); } sb.append(uniqueFilename); File file = new File(sb.toString()); inputStream = new FileInputStream(file); } else { // DATABASE byte[] bytes = new byte[] {}; if (fileDTO.getFileSize() > 0) { bytes = fileDTO.getBytes(); } inputStream = new ByteArrayInputStream(bytes); } // set response contenttype, header String encodedRealFilename = URLEncoder.encode(realFilename, "UTF-8"); logger.debug("realFilename: {}", realFilename); logger.debug("encodedRealFilename: {}", encodedRealFilename); response.setContentType(org.codelabor.system.file.FileConstants.CONTENT_TYPE); sb.setLength(0); if (request.getHeader(HttpRequestHeaderConstants.USER_AGENT).indexOf("MSIE5.5") > -1) { sb.append("filename="); } else { sb.append("attachment; filename="); } sb.append(encodedRealFilename); response.setHeader(HttpResponseHeaderConstants.CONTENT_DISPOSITION, sb.toString()); logger.debug("header: {}", sb.toString()); logger.debug("character encoding: {}", response.getCharacterEncoding()); logger.debug("content type: {}", response.getContentType()); logger.debug("bufferSize: {}", response.getBufferSize()); logger.debug("locale: {}", response.getLocale()); BufferedInputStream bufferdInputStream = new BufferedInputStream(inputStream); ServletOutputStream servletOutputStream = response.getOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(servletOutputStream); int bytesRead; byte buffer[] = new byte[2048]; while ((bytesRead = bufferdInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } // flush stream bufferedOutputStream.flush(); // close stream inputStream.close(); bufferdInputStream.close(); servletOutputStream.close(); bufferedOutputStream.close(); }
From source file:org.openmrs.module.DeIdentifiedPatientDataExportModule.api.impl.DeIdentifiedExportServiceImpl.java
public void exportJson(HttpServletResponse response, String ids, Integer pid) { response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=patientExportSummary.json"); List<PersonAttributeType> pat = getSavedPersonAttributeList(pid); JSONObject obj = new JSONObject(); JSONObject patientExportSummary = new JSONObject(); JSONArray patients = new JSONArray(); JSONObject patient = new JSONObject(); List<Integer> idsList = multipleIds(ids); PatientService ps = Context.getPatientService(); for (int j = 0; j < idsList.size(); j++) { Patient pt = ps.getPatient(idsList.get(j)); Map patientDemographicData = new HashMap(); for (int i = 0; i < pat.size(); i++) { PersonAttribute pa = pt.getAttribute(pat.get(i)); if (pa != null) patientDemographicData.put(pat.get(i).getName(), pa.getValue()); }/* w ww . java2 s . co m*/ patientDemographicData.put("dob", pt.getBirthdate().toString()); pt = setRandomPatientNames(pt); patientDemographicData.put("name", pt.getGivenName().toString() + " " + pt.getMiddleName().toString() + " " + pt.getFamilyName().toString()); List<Obs> obs1 = new ArrayList<Obs>(); Context.clearSession(); ObsService obsService = Context.getObsService(); List<Obs> ob = getOriginalObsList(pt, obsService); obs1 = getEncountersOfPatient(pt, ob, pid); //New obs list - updated List<ConceptSource> cs = getConceptMapping(obs1); for (int i = 0; i < obs1.size(); i++) { Map encounters = new HashMap(); JSONArray en = new JSONArray(); JSONObject enObj = new JSONObject(); en.add(enObj); encounters.put("observations", en); JSONObject conceptObj = new JSONObject(); JSONObject valueObj = new JSONObject(); JSONObject vObj = new JSONObject(); en.add(vObj); conceptObj.put("concept", enObj); valueObj.put("value", vObj); for (int k = 0; k < cs.size(); k++) { if (obs1.get(i).getValueCoded() != null) { vObj.put("valueCoded", obs1.get(i).getValueCoded().toString()); } else if (obs1.get(i).getValueBoolean() != null) { vObj.put("valueCoded", obs1.get(i).getValueBoolean().toString()); } enObj.put("conceptSourceId", cs.get(k).getHl7Code().toString()); enObj.put("conceptSource", cs.get(k).getName().toString()); } enObj.put("conceptID", obs1.get(i).getConcept().toString()); encounters.put("encounterDate", obs1.get(i).getEncounter().getEncounterDatetime().toLocaleString().toString()); encounters.put("encounterLocation", obs1.get(i).getLocation().getAddress1().toString()); patients.add(encounters); } patients.add(patientDemographicData); } patientExportSummary.put("patients", patients); obj.put("patientExportSummary", patientExportSummary); try { FileWriter file = new FileWriter("c:\\test1.json"); file.write(obj.toJSONString()); file.flush(); file.close(); File f = new File("c:\\test1.json"); FileInputStream fileIn = new FileInputStream(f); ServletOutputStream out = response.getOutputStream(); byte[] outputByte = new byte[4096]; //copy binary contect to output stream while (fileIn.read(outputByte, 0, 4096) != -1) { out.write(outputByte, 0, 4096); } fileIn.close(); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.alkacon.opencms.formgenerator.CmsCaptchaField.java
/** * Writes a Captcha JPEG image to the servlet response output stream. * <p>/*from w ww. j a v a 2 s.co m*/ * * @param cms an initialized Cms JSP action element * @throws IOException if something goes wrong */ public void writeCaptchaImage(CmsJspActionElement cms) throws IOException { // remove eventual session attribute containing captcha settings cms.getRequest().getSession().removeAttribute(SESSION_PARAM_CAPTCHASETTINGS); String sessionId = cms.getRequest().getSession().getId(); Locale locale = cms.getRequestContext().getLocale(); BufferedImage captchaImage = null; int maxTries = 10; do { try { maxTries--; captchaImage = ((ImageCaptchaService) CmsCaptchaServiceCache.getSharedInstance() .getCaptchaService(m_captchaSettings, cms.getCmsObject())).getImageChallengeForID(sessionId, locale); } catch (CaptchaException cex) { // image size is too small, increase dimensions and try it again if (LOG.isInfoEnabled()) { LOG.info(cex); LOG.info(Messages.get().getBundle().key(Messages.LOG_ERR_CAPTCHA_CONFIG_IMAGE_SIZE_2, new Object[] { m_captchaSettings.getPresetPath(), new Integer(maxTries) })); } m_captchaSettings.setImageHeight((int) (m_captchaSettings.getImageHeight() * 1.1)); m_captchaSettings.setImageWidth((int) (m_captchaSettings.getImageWidth() * 1.1)); // IMPORTANT: store changed captcha settings in session, they have to be used when validating the phrase cms.getRequest().getSession().setAttribute(SESSION_PARAM_CAPTCHASETTINGS, m_captchaSettings.clone()); } } while ((captchaImage == null) && (maxTries > 0)); ServletOutputStream out = null; try { CmsFlexController controller = CmsFlexController.getController(cms.getRequest()); HttpServletResponse response = controller.getTopResponse(); response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); ByteArrayOutputStream captchaImageOutput = new ByteArrayOutputStream(); ImageIO.write(captchaImage, "jpg", captchaImageOutput); out = cms.getResponse().getOutputStream(); out.write(captchaImageOutput.toByteArray()); out.flush(); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error(e.getLocalizedMessage(), e); } cms.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { try { if (out != null) { out.close(); } } catch (Throwable t) { // intentionally left blank } } }
From source file:com.spring.tutorial.controllers.DefaultController.java
@RequestMapping(value = "/files/{id}", method = RequestMethod.GET) public String getFile(@PathVariable("id") String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) throws IOException, Exception { String _id = request.getSession().getAttribute("id").toString(); MongoData data = new MongoData(); GridFS collection = new GridFS(data.getDB(), _id + "_files"); BasicDBObject query = new BasicDBObject(); query.put("_id", new ObjectId(id)); GridFSDBFile file = collection.findOne(query); DBCollection metaFileCollection = data.getDB().getCollection(_id + "_files_meta"); BasicDBObject metaQuery = new BasicDBObject(); metaQuery.put("file-id", new ObjectId(id)); DBObject metaFileDoc = metaFileCollection.findOne(metaQuery); MongoFile metaFile = new MongoFile(metaFileDoc); ServletOutputStream out = response.getOutputStream(); String mimeType = metaFile.getType(); response.setContentType(mimeType);// www .j a va2s . c o m response.setContentLength((int) file.getLength()); String headerKey = "Content-Disposition"; File f = File.createTempFile(file.getFilename(), metaFile.getType().substring(metaFile.getType().indexOf("/") + 1)); String headerValue = String.format("attachment; filename=\"%s\"", file.getFilename()); response.setHeader(headerKey, headerValue); file.writeTo(f); FileInputStream inputStream = new FileInputStream(f); byte[] buffer = new byte[4096]; int bytesRead = -1; while (inputStream.read(buffer, 0, 4096) != -1) { out.write(buffer, 0, 4096); } inputStream.close(); out.flush(); out.close(); return "mydrive/temp"; }
From source file:it.cnr.icar.eric.server.interfaces.rest.QueryManagerURLHandler.java
/** Write the result set as a RepositoryList */ private void writeRepositoryItemList(List<IdentifiableType> roList) throws IOException, RegistryException { ServletOutputStream sout = null; @SuppressWarnings("unused") String requestURL = request.getRequestURL().toString() + "?" + request.getQueryString(); try {/*from w ww .j a va 2 s .com*/ sout = response.getOutputStream(); ArrayList<ExtrinsicObjectType> eos = new ArrayList<ExtrinsicObjectType>(); Iterator<IdentifiableType> iter = roList.iterator(); while (iter.hasNext()) { RegistryObjectType ro = (RegistryObjectType) iter.next(); if (ro instanceof ExtrinsicObjectType) { ExtrinsicObjectType eo = (ExtrinsicObjectType) ro; if (eo.getContentVersionInfo() != null) { //This eo has an ri eos.add(eo); } } } writeRepositoryItems(eos); } finally { if (sout != null) { sout.close(); } } }
From source file:com.indeed.imhotep.web.TokenizeController.java
@RequestMapping("/tokenize") @ResponseBody//from www . java2 s.c o m protected void handleTokenize(@RequestParam("q") String query, HttpServletResponse resp) throws IOException { resp.setHeader("Access-Control-Allow-Origin", "*"); try { final List<Token> tokens = TerminalParser.LEXER.parse(query); final ServletOutputStream outputStream = resp.getOutputStream(); resp.setContentType(MediaType.APPLICATION_JSON_VALUE); final ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true); final ObjectNode jsonRoot = mapper.createObjectNode(); final ArrayNode tokenArrayNode = jsonRoot.arrayNode(); jsonRoot.put("tokens", tokenArrayNode); for (Token token : tokens) { final ObjectNode tokenNode = tokenArrayNode.objectNode(); final String text = token.value() instanceof Tokens.Fragment ? ((Tokens.Fragment) token.value()).text() : (String) token.value(); final String tag = token.value() instanceof Tokens.Fragment ? ((Tokens.Fragment) token.value()).tag().toString() : "STRING"; tokenNode.put("text", text); tokenNode.put("index", token.index()); tokenNode.put("length", token.length()); tokenNode.put("tag", tag); tokenArrayNode.add(tokenNode); } mapper.writeValue(outputStream, jsonRoot); outputStream.close(); } catch (Throwable e) { QueryServlet.handleError(resp, true, e, false, false); } }
From source file:org.oscarehr.fax.admin.ManageFaxes.java
public ActionForward viewFax(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {// w w w. j a va2 s .c o m if (!securityInfoManager.hasPrivilege(LoggedInInfo.getLoggedInInfoFromSession(request), "_edoc", "r", null)) { throw new SecurityException("missing required security object (_edoc)"); } try { String doc_no = request.getParameter("jobId"); String pageNum = request.getParameter("curPage"); if (pageNum == null) { pageNum = "0"; } Integer pn = Integer.parseInt(pageNum); log.debug("Document No :" + doc_no); LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.READ, LogConst.CON_DOCUMENT, doc_no, request.getRemoteAddr()); FaxJobDao faxJobDao = SpringUtils.getBean(FaxJobDao.class); FaxJob faxJob = faxJobDao.find(Integer.parseInt(doc_no)); int index; String filename; if ((index = faxJob.getFile_name().lastIndexOf("/")) > -1) { filename = faxJob.getFile_name().substring(index + 1); } else { filename = faxJob.getFile_name(); } String name = filename + "_" + pn + ".png"; log.debug("name " + name); File outfile = null; outfile = hasCacheVersion2(faxJob, pn); if (outfile != null) { log.debug("got doc from local cache "); } else { outfile = createCacheVersion2(faxJob, pn); if (outfile != null) { log.debug("create new doc "); } } response.setContentType("image/png"); ServletOutputStream outs = response.getOutputStream(); response.setHeader("Content-Disposition", "attachment;filename=" + name); BufferedInputStream bfis = null; try { if (outfile != null) { bfis = new BufferedInputStream(new FileInputStream(outfile)); int data; while ((data = bfis.read()) != -1) { outs.write(data); // outs.flush(); } } else { log.info("Unable to retrieve content for " + faxJob + ". This may indicate previous upload or save errors..."); } } finally { if (bfis != null) { bfis.close(); } } outs.flush(); outs.close(); } catch (java.net.SocketException se) { MiscUtils.getLogger().error("Error", se); } catch (Exception e) { MiscUtils.getLogger().error("Error", e); } return null; }