List of usage examples for javax.servlet ServletOutputStream flush
public void flush() throws IOException
From source file:org.kuali.kfs.module.purap.document.web.struts.BulkReceivingAction.java
public ActionForward printReceivingTicket(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String blkDocId = request.getParameter("docId"); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); try {/*from w w w .j a v a2 s . c o m*/ // will throw validation exception if errors occur SpringContext.getBean(BulkReceivingService.class).performPrintReceivingTicketPDF(blkDocId, baosPDF); response.setHeader("Cache-Control", "max-age=30"); response.setContentType("application/pdf"); StringBuffer sbContentDispValue = new StringBuffer(); String useJavascript = request.getParameter("useJavascript"); if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) { sbContentDispValue.append("attachment"); } else { sbContentDispValue.append("inline"); } StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PURAP_RECEIVING_TICKET_"); sbFilename.append(blkDocId); sbFilename.append("_"); sbFilename.append(System.currentTimeMillis()); sbFilename.append(".pdf"); sbContentDispValue.append("; filename="); sbContentDispValue.append(sbFilename); response.setHeader("Content-disposition", sbContentDispValue.toString()); response.setContentLength(baosPDF.size()); ServletOutputStream sos = response.getOutputStream(); baosPDF.writeTo(sos); sos.flush(); } finally { if (baosPDF != null) { baosPDF.reset(); } } return null; }
From source file:org.betaconceptframework.astroboa.console.export.ExcelExportBean.java
public void exportContentObjectSelection(ContentObjectSelectionBean contentObjectSelection, String locale) { if (contentObjectSelection == null || CollectionUtils.isEmpty(contentObjectSelection.getSelectedContentObjects())) { JSFUtilities.addMessage(null, "object.action.export.message.nullList", null, FacesMessage.SEVERITY_WARN); return;// w ww .j a v a 2 s . c o m } if (StringUtils.isEmpty(locale)) { locale = "en"; logger.warn("Provided Locale was empty. The default locale which is 'en' will be used"); } List<ContentObjectUIWrapper> contentObjectUiWrapperList = contentObjectSelection .getSelectedContentObjects(); FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.getResponseComplete()) { HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("UTF-8"); WorkbookBuilder workbookBuilder = new WorkbookBuilder(astroboaClient.getDefinitionService(), locale); int rowIndex = 2; for (ContentObjectUIWrapper contentObjectUiWrapper : contentObjectUiWrapperList) { ContentObject contentObject = contentObjectUiWrapper.getContentObject(); //Reload object ContentObject object = astroboaClient.getContentService().getContentObject(contentObject.getId(), ResourceRepresentationType.CONTENT_OBJECT_INSTANCE, FetchLevel.FULL, CacheRegion.NONE, null, false); workbookBuilder.addContentObjectToWorkbook(object); ++rowIndex; //Limit to the first 5000 content objects if (rowIndex > 5000) { break; } } String filename = createFilename(workbookBuilder); response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xls"); try { ServletOutputStream servletOutputStream = response.getOutputStream(); //workbook.write(servletOutputStream); workbookBuilder.getWorkbook().write(servletOutputStream); servletOutputStream.flush(); facesContext.responseComplete(); } catch (IOException e) { logger.error("An error occurred while writing excel workbook to servlet output stream", e); JSFUtilities.addMessage(null, "object.action.export.message.error", null, FacesMessage.SEVERITY_WARN); } finally { workbookBuilder.clear(); workbookBuilder = null; } } else { JSFUtilities.addMessage(null, "object.action.export.message.error", null, FacesMessage.SEVERITY_WARN); } }
From source file:org.betaconceptframework.astroboa.console.export.ExcelExportBean.java
public void exportContentObjectList(ContentObjectCriteria contentObjectCriteria, String locale) { // remove offset from criteria and add a limit of 5000 contentObjectCriteria.setOffset(0);/*from ww w .jav a 2 s . c o m*/ contentObjectCriteria.setLimit(5000); // run the query CmsOutcome<ContentObject> cmsOutcome = astroboaClient.getContentService() .searchContentObjects(contentObjectCriteria, ResourceRepresentationType.CONTENT_OBJECT_LIST); if (cmsOutcome.getCount() == 0) { JSFUtilities.addMessage(null, "object.action.export.message.nullList", null, FacesMessage.SEVERITY_WARN); return; } if (StringUtils.isEmpty(locale)) { locale = "en"; logger.warn("Provided Locale was empty. The default locale which is 'en' will be used"); } List<ContentObject> cmsOutcomeRowList = cmsOutcome.getResults(); FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.getResponseComplete()) { HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("UTF-8"); WorkbookBuilder workbookBuilder = new WorkbookBuilder(astroboaClient.getDefinitionService(), locale); int rowIndex = 2; for (ContentObject contentObject : cmsOutcomeRowList) { //Reload object ContentObject object = astroboaClient.getContentService().getContentObject(contentObject.getId(), ResourceRepresentationType.CONTENT_OBJECT_INSTANCE, FetchLevel.FULL, CacheRegion.NONE, null, false); workbookBuilder.addContentObjectToWorkbook(object); ++rowIndex; } String filename = createFilename(workbookBuilder); response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xls"); //autoSizeColumns(sheet); try { ServletOutputStream servletOutputStream = response.getOutputStream(); //workbook.write(servletOutputStream); workbookBuilder.getWorkbook().write(servletOutputStream); servletOutputStream.flush(); facesContext.responseComplete(); } catch (IOException e) { logger.error("An error occurred while writing excel workbook to servlet output stream", e); JSFUtilities.addMessage(null, "object.action.export.message.error", null, FacesMessage.SEVERITY_WARN); } finally { workbookBuilder.clear(); workbookBuilder = null; } } else { JSFUtilities.addMessage(null, "object.action.export.message.error", null, FacesMessage.SEVERITY_WARN); } }
From source file:com.labimo.portlet.DownloadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String hardwareUuid = request.getParameter("hardwareUuid"); String licenseUuid = request.getParameter("licenseUuid"); String fileName = "license.txt"; License license = null;//from w w w .ja v a2 s. c o m try { license = LicenseLocalServiceUtil.getLicense(licenseUuid); if (license != null && license.getValid()) { response.setHeader("Content-Type", "application/octet-stream"); ServletOutputStream servletOutputStream = response.getOutputStream(); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); IOUtils.write(LicenseUtils.getChargesLicenseContent(hardwareUuid, license.getIssueDate(), license.getValidDate()), servletOutputStream); servletOutputStream.flush(); servletOutputStream.close(); } } catch (Exception e) { e.printStackTrace(); } /* * String activationId = "1a508567-61f9-3e5a-8923-b27ca6d00028"; String * fileName = "license.txt"; List<Activation> activationList = * LicenseUtils * .getActivationListByLicenseUuid("4091a61b-4b3d-46b9-890d-2a3e63f09d3c" * ); if (activationList != null && activationList.size() > 0) { // * License license = // LicenseLocalServiceUtil.getLicense(licenseUuid); * License license = null; try { license = LicenseLocalServiceUtil * .getLicense("4091a61b-4b3d-46b9-890d-2a3e63f09d3c"); } catch * (PortalException e) { // TODO Auto-generated catch block * e.printStackTrace(); } catch (SystemException e) { // TODO * Auto-generated catch block e.printStackTrace(); } * System.out.println("getIssueDate = " + license.getIssueDate()); * System.out.println("getValidDate = " + license.getValidDate()); * System.out.println("getValid = " + license.getValid()); if * (license.getValid()) { response.setHeader("Content-Type", * "application/octet-stream"); ServletOutputStream servletOutputStream * = response .getOutputStream(); * response.setHeader("Content-Disposition", "attachment; filename=\"" + * fileName + "\""); * * try { IOUtils.write(LicenseUtils.getChargesLicenseContent( * activationId, license.getIssueDate(), license.getValidDate()), * servletOutputStream); } catch (Exception e) { // TODO Auto-generated * catch block e.printStackTrace(); } servletOutputStream.flush(); * servletOutputStream.close(); * * } } */ }
From source file:org.efs.openreports.actions.ReportRunAction.java
public String execute() { ReportUser user = (ReportUser) ActionContext.getContext().getSession().get(ORStatics.REPORT_USER); Report report = (Report) ActionContext.getContext().getSession().get(ORStatics.REPORT); int exportType = Integer .parseInt((String) ActionContext.getContext().getSession().get(ORStatics.EXPORT_TYPE)); Map reportParameters = getReportParameterMap(user, report, exportType); Map imagesMap = getImagesMap(); HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); // set headers to disable caching response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "max-age=0"); ReportLog reportLog = new ReportLog(user, report, new Date()); JRVirtualizer virtualizer = null;/*from w ww . j a va 2s . c om*/ try { if (exportType == ReportEngine.EXPORT_PDF) { // Handle "contype" request from Internet Explorer if ("contype".equals(request.getHeader("User-Agent"))) { response.setContentType("application/pdf"); response.setContentLength(0); ServletOutputStream outputStream = response.getOutputStream(); outputStream.close(); return NONE; } } log.debug("Filling report: " + report.getName()); reportLogProvider.insertReportLog(reportLog); if (report.isVirtualizationEnabled() && exportType != ReportEngine.EXPORT_IMAGE) { log.debug("Virtualization Enabled"); virtualizer = new JRFileVirtualizer(2, directoryProvider.getTempDirectory()); reportParameters.put(JRParameter.REPORT_VIRTUALIZER, virtualizer); } ReportEngineInput reportInput = new ReportEngineInput(report, reportParameters); reportInput.setExportType(exportType); reportInput.setImagesMap(imagesMap); // add any charts if (report.getReportChart() != null) { log.debug("Adding chart: " + report.getReportChart().getName()); ChartReportEngine chartEngine = new ChartReportEngine(dataSourceProvider, directoryProvider, propertiesProvider); ChartEngineOutput chartOutput = (ChartEngineOutput) chartEngine.generateReport(reportInput); reportParameters.put("ChartImage", chartOutput.getContent()); } ReportEngineOutput reportOutput = null; JasperPrint jasperPrint = null; if (report.isJasperReport()) { JasperReportEngine jasperEngine = new JasperReportEngine(dataSourceProvider, directoryProvider, propertiesProvider); jasperPrint = jasperEngine.fillReport(reportInput); log.debug("Report filled - " + report.getName() + " : size = " + jasperPrint.getPages().size()); log.debug("Exporting report: " + report.getName()); reportOutput = jasperEngine.exportReport(jasperPrint, exportType, report.getReportExportOption(), imagesMap, false); } else { ReportEngine reportEngine = ReportEngineHelper.getReportEngine(report, dataSourceProvider, directoryProvider, propertiesProvider); reportOutput = reportEngine.generateReport(reportInput); } response.setContentType(reportOutput.getContentType()); if (exportType != ReportEngine.EXPORT_HTML && exportType != ReportEngine.EXPORT_IMAGE) { response.setHeader("Content-disposition", "inline; filename=" + StringUtils.deleteWhitespace(report.getName()) + reportOutput.getContentExtension()); } if (exportType == ReportEngine.EXPORT_IMAGE) { if (jasperPrint != null) { ActionContext.getContext().getSession().put(ORStatics.JASPERPRINT, jasperPrint); } } else { byte[] content = reportOutput.getContent(); response.setContentLength(content.length); ServletOutputStream out = response.getOutputStream(); out.write(content, 0, content.length); out.flush(); out.close(); } reportLog.setEndTime(new Date()); reportLog.setStatus(ReportLog.STATUS_SUCCESS); reportLogProvider.updateReportLog(reportLog); log.debug("Finished report: " + report.getName()); } catch (Exception e) { if (e.getMessage() != null && e.getMessage().indexOf("Empty") > 0) { addActionError(LocalStrings.getString(LocalStrings.ERROR_REPORT_EMPTY)); reportLog.setStatus(ReportLog.STATUS_EMPTY); } else { addActionError(e.getMessage()); log.error(e.getMessage()); reportLog.setMessage(e.getMessage()); reportLog.setStatus(ReportLog.STATUS_FAILURE); } reportLog.setEndTime(new Date()); try { reportLogProvider.updateReportLog(reportLog); } catch (Exception ex) { log.error("Unable to create ReportLog: " + ex.getMessage()); } return ERROR; } finally { if (virtualizer != null) { reportParameters.remove(JRParameter.REPORT_VIRTUALIZER); virtualizer.cleanup(); } } if (exportType == ReportEngine.EXPORT_IMAGE) return SUCCESS; return NONE; }
From source file:net.sourceforge.fenixedu.presentationTier.Action.manager.enrolments.CurriculumLineLogsDA.java
public ActionForward viewCurriculumLineLogStatisticsChartOperations(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { final ExecutionSemester executionSemester = getDomainObject(request, "executionSemesterId"); if (executionSemester != null) { final CurriculumLineLogStatisticsCalculator curriculumLineLogStatisticsCalculator = new CurriculumLineLogStatisticsCalculator( executionSemester);/*from w ww . ja va 2s . co m*/ ServletOutputStream writer = null; try { writer = response.getOutputStream(); response.setContentType("image/jpeg"); writer.write(curriculumLineLogStatisticsCalculator.getOperationsChart()); writer.flush(); } finally { writer.close(); response.flushBuffer(); } } return null; }
From source file:com.controlj.green.istat.web.TreeServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Expires", "Wed, 01 Jan 2003 12:00:00 GMT"); resp.setHeader("Cache-Control", "no-cache"); ServletOutputStream out = resp.getOutputStream(); try {//w w w. ja va 2s.co m writeLevel(out, req.getParameter(LOCATION_PARAM), req); } catch (Exception e) { Logging.LOGGER.println("Error getting tree info"); e.printStackTrace(Logging.LOGGER); throw new ServletException(e); } out.flush(); /* out.println("["); out.println("{ display:'Main Conf Room', id:'mainconf'},"); out.println("{ display:'Board Room', id:'boardroom'},"); out.println("{ display:'Room 235', id:'room235'}"); out.println("]"); */ }
From source file:com.rplt.studioMusik.controller.OperatorController.java
@RequestMapping(value = "/cetakNota", method = RequestMethod.GET) public String cetakNota(HttpServletResponse response) { Connection conn = DatabaseConnection.getmConnection(); // File reportFile = new File(application.getRealPath("Coba.jasper"));//your report_name.jasper file File reportFile = new File( servletConfig.getServletContext().getRealPath("/resources/report/nota_persewaan.jasper")); Map parameters = new HashMap(); Map<String, Object> params = new HashMap<String, Object>(); params.put("P_KODESEWA", request.getParameter("kodeSewa")); byte[] bytes = null; try {/*w w w .jav a 2s . c o m*/ bytes = JasperRunManager.runReportToPdf(reportFile.getPath(), params, conn); } catch (JRException ex) { Logger.getLogger(OperatorController.class.getName()).log(Level.SEVERE, null, ex); } response.setContentType("application/pdf"); response.setContentLength(bytes.length); try { ServletOutputStream outStream = response.getOutputStream(); outStream.write(bytes, 0, bytes.length); outStream.flush(); outStream.close(); } catch (IOException ex) { Logger.getLogger(MemberController.class.getName()).log(Level.SEVERE, null, ex); } return "halaman-cetakNota-operator"; }
From source file:com.jd.survey.web.security.LoginController.java
@RequestMapping(method = RequestMethod.GET, value = "/w/{uuid}", produces = "image/gif") public void getWhiteGif(@PathVariable("uuid") String uuid, Principal principal, HttpServletRequest httpServletRequest, HttpServletResponse response) { try {//from www . j a v a 2 s .c o m Invitation invitation = surveySettingsService.invitation_findByUuid(uuid); if (invitation != null) { surveySettingsService.invitation_updateAsRead(invitation.getId()); } //white 1 x 1 pixel gif binary byte[] trackingGif = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x1, 0x0, 0x1, 0x0, (byte) 0x80, 0x0, 0x0, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x0, 0x0, 0x0, 0x2c, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x1, 0x0, 0x0, 0x2, 0x2, 0x44, 0x1, 0x0, 0x3b }; response.setContentType("image/gif"); ServletOutputStream servletOutputStream = response.getOutputStream(); servletOutputStream.write(trackingGif); servletOutputStream.flush(); } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:org.dataconservancy.ui.api.DataItemController.java
@RequestMapping(value = "/{idpart}", method = RequestMethod.GET) public void handleDataItemGetRequest(@RequestHeader(value = "Accept", required = false) String mimeType, @RequestHeader(value = "If-Match", required = false) String ifMatch, @RequestHeader(value = "If-None-Match", required = false) String ifNoneMatch, @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date modifiedSince, HttpServletRequest request, HttpServletResponse response) throws IOException, ArchiveServiceException, BizPolicyException { // Check to see if the user is authenticated (TODO: have Spring Security be responsible for this?) // Note that the fact that the user has to be authenticated, and further authorized, is a policy decision, // but the pattern for the Project and Person controllers is that the Controller has handled this. final Person authenticatedUser = getAuthenticatedUser(); // Rudimentary Accept Header handling; accepted values are */*, application/*, application/xml, // application/octet-stream if (mimeType != null && !(mimeType.contains(APPLICATION_XML) || mimeType.contains(ACCEPT_WILDCARD) || mimeType.contains(ACCEPT_APPLICATION_WILDCARD) || mimeType.contains(ACCEPT_OCTET_STREAM))) { response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Unacceptable value for 'Accept' header: '" + mimeType + "'"); return;/*from w w w . j a v a2s . c o m*/ } // Resolve the Request URL to the ID of the DataItem (in this case URL == ID) String dataItemId = requestUtil.buildRequestUrl(request); if (dataItemId == null || dataItemId.trim().isEmpty()) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // Get the DataItem final DataItem dataItem = getDataItem(dataItemId); // Calculate the ETag for the DataItem, may be null. final String etag; if (dataItem != null) { etag = calculateEtag(dataItem); } else { etag = null; } // Handle the 'If-Match' header first; RFC 2616 14.24 if (this.responseHeaderUtil.handleIfMatch(request, response, this.requestUtil, ifMatch, dataItem, etag, dataItemId, "DataItem")) { return; } final DateTime lastModified; if (dataItem != null) { lastModified = getLastModified(dataItem.getId()); } else { lastModified = null; } // Handle the 'If-None-Match' header; RFC 2616 14.26 if (this.responseHeaderUtil.handleIfNoneMatch(request, response, ifNoneMatch, dataItem, etag, dataItemId, lastModified, modifiedSince)) { return; } if (dataItem == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Handle the 'If-Modified-Since' header; RFC 2616 14.26 if (this.responseHeaderUtil.handleIfModifiedSince(request, response, modifiedSince, lastModified)) { return; } // Check to see if the user is authorized if (!authzService.canRetrieveDataSet(authenticatedUser, dataItem)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // Compose the Business Object Package Bop businessPackage = new Bop(); businessPackage.addDataItem(dataItem); // Serialize the package to an output stream ByteArrayOutputStream out = new ByteArrayOutputStream(); bob.buildBusinessObjectPackage(businessPackage, out); out.close(); // Compose the Response (headers, entity body) this.responseHeaderUtil.setResponseHeaderFields(response, etag, out, lastModified); // Send the Response final ServletOutputStream servletOutputStream = response.getOutputStream(); IOUtils.copy(new ByteArrayInputStream(out.toByteArray()), servletOutputStream); servletOutputStream.flush(); servletOutputStream.close(); }