List of usage examples for javax.servlet ServletOutputStream flush
public void flush() throws IOException
From source file:org.mxhero.engine.plugin.attachmentlink.fileserver.servlet.FileService.java
private void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ContentService service = null;//w w w. j ava 2 s.c o m InputStream in = null; Long idToSearch = null; String id = req.getParameter("id"); String type = req.getParameter("type"); String email = req.getParameter("email"); MDC.put("message", id); try { if (StringUtils.isEmpty(id) || StringUtils.isEmpty(type)) { log.debug("Error. No params in URL present. Forwarding to error URL page"); req.getRequestDispatcher("/errorParams.jsp").forward(req, resp); } else { ApplicationContext context = WebApplicationContextUtils .getWebApplicationContext(getServletContext()); StandardPBEStringEncryptor encryptor = (StandardPBEStringEncryptor) context.getBean("encryptor"); String decrypt = encryptor.decrypt(id); idToSearch = Long.valueOf(decrypt); log.debug("Trying download to id " + idToSearch); service = context.getBean(ContentService.class); ContentDTO content = service.getContent(idToSearch, email); if (content.hasPublicUrl()) { service.successContent(idToSearch); resp.sendRedirect(content.getPublicUrl()); } else { ServletOutputStream outputStream = resp.getOutputStream(); resp.setContentLength(content.getLength()); resp.setContentType(content.getContentType(type)); if (!content.hasToBeOpen(type)) { resp.setHeader("Content-Type", "application/octet-stream"); resp.addHeader("Content-Disposition", "attachment; filename=\"" + content.getFileName() + "\""); } else { resp.addHeader("Content-Disposition", "filename=\"" + content.getFileName() + "\""); } resp.addHeader("Cache-Control", "no-cache"); in = content.getInputStream(); int BUFF_SIZE = 2048; byte[] buffer = new byte[BUFF_SIZE]; int byteCount = 0; while ((in != null) && (byteCount = in.read(buffer)) != -1) { outputStream.write(buffer, 0, byteCount); } outputStream.flush(); log.debug("Download completed successfuly"); service.successContent(idToSearch); } } } catch (NotAllowedToSeeContentException e) { log.debug("User not more allowed to download content. Forwarding to not allowed page"); req.getRequestDispatcher("/notAllowed.jsp").forward(req, resp); } catch (EmptyResultDataAccessException e) { log.debug("Content not more available. Forwarding to not available page"); req.getRequestDispatcher("/contentNotAvailable.jsp").forward(req, resp); } catch (Exception e) { try { service.failDownload(idToSearch); } catch (Exception e2) { } log.error("Exception: " + e.getClass().getName()); log.error("Message Exception: " + e.getMessage()); log.debug("Error General. Forwarding to page error general"); req.getRequestDispatcher("/error.jsp").forward(req, resp); } finally { if (in != null) { in.close(); } MDC.put("message", id); } }
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()); }/* ww w. ja va 2s . c o 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.jd.survey.web.settings.SurveyDefinitionController.java
/** * Returns the survey logo image binary * @param departmentId/*from w w w .j a v a2s . c o m*/ * @param uiModel * @param httpServletRequest * @return */ @Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" }) @RequestMapping(value = "/logo/{id}", produces = "text/html") public void getSurveyLogo(@PathVariable("id") Long surveyDefinitionId, Model uiModel, Principal principal, HttpServletRequest httpServletRequest, HttpServletResponse response) { try { uiModel.asMap().clear(); User user = userService.user_findByLogin(principal.getName()); //Check if the user is authorized if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); throw (new RuntimeException("Unauthorized access to logo")); } SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId); //response.setContentType("image/png"); ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write(surveyDefinition.getLogo()); servletOutputStream.flush(); } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
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);/*w ww . j a va 2 s .c om*/ 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:com.jd.survey.web.settings.SurveyDefinitionController.java
/** * Exports the survey definition as a JSON file * @param surveyDefinitionId//from w ww .j a va2s . co m * @param response */ @Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" }) @RequestMapping(value = "/{id}", params = "export", produces = "text/html") public void exportToJson(@PathVariable("id") Long surveyDefinitionId, Principal principal, HttpServletRequest httpServletRequest, HttpServletResponse response) { try { String login = principal.getName(); User user = userService.user_findByLogin(login); //Check if the user is authorized if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); response.sendRedirect("../../accessDenied"); } SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId); //set the exported survey definition status to Inactive surveyDefinition.setStatus(SurveyDefinitionStatus.I); String json = jsonHelperService.serializeSurveyDefinition(surveyDefinition); //response.setContentType("text/html; charset=utf-8"); response.setContentType("application/octet-stream"); // Set standard HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // Set standard HTTP/1.0 no-cache header. response.setHeader("Pragma", "no-cache"); response.setHeader("Content-Disposition", "inline;filename=surveyDef" + surveyDefinitionId + ".jsn"); ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write(json.getBytes("UTF-8")); servletOutputStream.flush(); //Returning the original survey's status to Published. surveyDefinition.setStatus(SurveyDefinitionStatus.P); } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:org.oscarehr.fax.admin.ManageFaxes.java
public ActionForward viewFax(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {/*from w ww .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; }
From source file:org.itracker.web.actions.report.DisplayReportAction.java
/** * *///w w w. ja v a 2 s . c o m public static void outputReport(List<Issue> reportDataArray, Project project, Report report, Locale userLocale, String reportOutput, HttpServletResponse response) throws ReportException { try { // hack, we have to find a more structured way to support // various types of queries final JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource( reportDataArray); final Map<String, Object> parameters = new HashMap<String, Object>(); String reportTitle = report.getName(); if (project != null) { reportTitle += " - " + project.getName(); if (report.getNameKey() != null) { reportTitle = ITrackerResources.getString(report.getNameKey(), project.getName()); } } else if (report.getNameKey() != null) { reportTitle = ITrackerResources.getString(report.getNameKey()); } parameters.put("ReportTitle", reportTitle); parameters.put("BaseDir", new File(".")); parameters.put("REPORT_LOCALE", userLocale); parameters.put("REPORT_RESOURCE_BUNDLE", ITrackerResourceBundle.getBundle(userLocale)); final JasperPrint jasperPrint = generateReport(report, parameters, beanCollectionDataSource); final ServletOutputStream out = response.getOutputStream(); final JRExporter x; if (ReportUtilities.REPORT_OUTPUT_PDF.equals(reportOutput)) { response.setHeader("Content-Type", "application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=\"" + report.getName() + new SimpleDateFormat("-yyyy-MM-dd").format(new Date()) + ".pdf\""); x = new JRPdfExporter(); } else if (ReportUtilities.REPORT_OUTPUT_XLS.equals(reportOutput)) { response.setHeader("Content-Type", "application/xls"); response.setHeader("Content-Disposition", "attachment; filename=\"" + report.getName() + new SimpleDateFormat("-yyyy-MM-dd").format(new Date()) + ".xls\""); x = new JRXlsExporter(); } else if (ReportUtilities.REPORT_OUTPUT_CSV.equals(reportOutput)) { response.setHeader("Content-Type", "text/csv"); response.setHeader("Content-Disposition", "attachment; filename=\"" + report.getName() + new SimpleDateFormat("-yyyy-MM-dd").format(new Date()) + ".csv\""); x = new JRCsvExporter(); } else if (ReportUtilities.REPORT_OUTPUT_HTML.equals(reportOutput)) { response.setHeader("Content-Type", "text/html"); response.setHeader("Content-Disposition", "attachment; filename=\"" + report.getName() + new SimpleDateFormat("-yyyy-MM-dd").format(new Date()) + ".html\""); x = new JRHtmlExporter(); } else { log.error("Invalid report output format: " + reportOutput); throw new ReportException("Invalid report type.", "itracker.web.error.invalidreportoutput"); } x.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); x.setParameter(JRExporterParameter.OUTPUT_STREAM, out); x.exportReport(); out.flush(); out.close(); } catch (JRException e) { throw new ReportException(e); } catch (IOException e) { throw new ReportException(e); } }
From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.erasmus.ErasmusIndividualCandidacyProcessPublicDA.java
public ActionForward retrieveLearningAgreement(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { MobilityIndividualApplicationProcess process = (MobilityIndividualApplicationProcess) 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 w w w.ja va 2s. c o m*/ writer.flush(); writer.close(); response.flushBuffer(); return mapping.findForward(""); }
From source file:org.red5.stream.http.servlet.TransportSegmentFeeder.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)/*www . j a v a2 s . c o m*/ */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Segment feed requested"); // get red5 context and segmenter if (service == null) { ApplicationContext appCtx = (ApplicationContext) getServletContext() .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); service = (SegmenterService) appCtx.getBean("segmenter.service"); } // get the requested stream / segment String servletPath = request.getServletPath(); String streamName = servletPath.split("\\.")[0]; log.debug("Stream name: {}", streamName); if (service.isAvailable(streamName)) { response.setContentType("video/MP2T"); // data segment Segment segment = null; // setup buffers and output stream byte[] buf = new byte[188]; ByteBuffer buffer = ByteBuffer.allocate(188); ServletOutputStream sos = response.getOutputStream(); // loop segments while ((segment = service.getSegment(streamName)) != null) { do { buffer = segment.read(buffer); // log.trace("Limit - position: {}", (buffer.limit() - buffer.position())); if ((buffer.limit() - buffer.position()) == 188) { buffer.get(buf); // write down the output stream sos.write(buf); } else { log.info("Segment result has indicated a problem"); // verifies the currently requested stream segment // number against the currently active segment if (service.getSegment(streamName) == null) { log.debug("Requested segment is no longer available"); break; } } buffer.clear(); } while (segment.hasMoreData()); log.trace("Segment {} had no more data", segment.getIndex()); // flush sos.flush(); // segment had no more data segment.cleanupThreadLocal(); } buffer.clear(); buffer = null; } else { // let requester know that stream segment is not available response.sendError(404, "Requested segmented stream not found"); } }
From source file:org.kuali.kra.coi.disclosure.CoiDisclosureAction.java
/** * /*w w w . j a v a 2s .c om*/ * This method is for use with a JSON/AJAX call and should not be used as a post method * */ public ActionForward getDisclosureEventTypeInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String eventType = request.getParameter("eventType"); Map<String, Object> fieldValues = new HashMap<String, Object>(); fieldValues.put("eventTypeCode", eventType); List<CoiDisclosureEventType> disclosureEventTypes = (List<CoiDisclosureEventType>) getBusinessObjectService() .findMatching(CoiDisclosureEventType.class, fieldValues); StringWriter writer = new StringWriter(); if (!CollectionUtils.isEmpty(disclosureEventTypes)) { CoiDisclosureEventType disclosureEventType = disclosureEventTypes.get(0); CoiDisclosureEventTypeAjaxBean disclosureEventTypeAjaxBean = new CoiDisclosureEventTypeAjaxBean(); disclosureEventTypeAjaxBean.setDisclosureEventType(disclosureEventType); //Special code to handle select box if (disclosureEventType.isUseSelectBox1()) { try { String valuesFinder = disclosureEventType.getSelectBox1ValuesFinder(); if (StringUtils.isNotBlank(valuesFinder)) { Class valuesFinderClass = Class.forName(valuesFinder); KeyValuesFinder keyValuesFinder = (KeyValuesFinder) valuesFinderClass.newInstance(); List<KeyValue> keyValues = keyValuesFinder.getKeyValues(); if (!CollectionUtils.isEmpty(keyValues)) { disclosureEventTypeAjaxBean.setKeyValues(keyValues); } } } catch (Exception e) { //Failed to load select box } } // disclosure ID and label are always required, so put in a default if (StringUtils.isEmpty(disclosureEventType.getProjectIdLabel())) { disclosureEventType.setProjectIdLabel(CoreApiServiceLocator.getKualiConfigurationService() .getPropertyValueAsString(DEFAULT_EVENT_ID_STRING)); } if (StringUtils.isEmpty(disclosureEventType.getProjectTitleLabel())) { disclosureEventType.setProjectTitleLabel(CoreApiServiceLocator.getKualiConfigurationService() .getPropertyValueAsString(DEFAULT_EVENT_TITLE_STRING)); } ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(writer, disclosureEventTypeAjaxBean); response.setContentType("application/json"); ServletOutputStream out = response.getOutputStream(); try { out.write(writer.getBuffer().toString().getBytes()); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(new PrintWriter(out)); } } return null; }