List of usage examples for javax.servlet ServletOutputStream close
public void close() throws IOException
From source file:com.ibm.ioes.actions.NewOrderAction.java
public ActionForward downloadTemplateExcelForPrdCatelog(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String forwardMapping = null; try {//from w w w . jav a 2 s. c o m NewOrderBean formBean = (NewOrderBean) form; NewOrderModel model = new NewOrderModel(); //String[] serviceProductId=request.getParameterValues("chk_spId"); //make excel model.downloadTemplateExcelForPrdCatelog(formBean); //send excel in request response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=ProductCatelogExcel.xls"); ServletOutputStream out = response.getOutputStream(); formBean.getProductCatelogTemplateWorkbook().write(out); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); //AppConstants.NPDLOGGER.error(ex.getMessage() // + " Exception occured in downloadPlanExcelForEdit method of " // + this.getClass().getSimpleName()+AppUtility.getStackTrace(ex)); forwardMapping = Messages.getMessageValue("errorGlobalForward"); return mapping.findForward(forwardMapping); } return null; }
From source file:com.ibm.ioes.actions.NewOrderAction.java
public ActionForward goToDownloadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { NewOrderBean formBean = (NewOrderBean) form; //String fileName=formBean.getFileName(); ActionForward forward = new ActionForward(); ActionMessages messages = new ActionMessages(); FileAttachmentDto downloadedFile = new FileAttachmentDto(); CommonBaseModel commonBaseModel = new CommonBaseModel(); byte[] File = null; FileAttachmentDto fileDto = new FileAttachmentDto(); fileDto.setHdnOrderNo(request.getParameter("hdnOrderNo")); fileDto.setHdnAccountNo(request.getParameter("accountID")); //--Added & modified by vijay--// /*these code is modify for solving the error of downloading file whose name contain special characters */ //fileDto.setFileName(request.getParameter("fileName")); fileDto.setFileName(request.getParameter("hdnFileName")); fileDto.setCreateDate(request.getParameter("createDate")); //String slNO=request.getParameter("sLNO"); //fileDto.setSlno(Integer.parseInt(slNO)); String slNO = request.getParameter("hdnslno"); fileDto.setSlno(Integer.parseInt(slNO)); //--end of code--// NewOrderModel objModel = new NewOrderModel(); downloadedFile = objModel.getDownloadedFile(fileDto); //java.sql.Blob blob=null; File = commonBaseModel.blobToByteArray(downloadedFile.getFile()); String ContentType = commonBaseModel.setContentTypeForFile(downloadedFile.getFileName());//CHANGES FOR SYSTEM TESTING DEFECTS response.setContentType(ContentType); //---added by vijay--// //response.setHeader("Content-Disposition","attachment;filename=" + downloadedFile.getFileName());//CHANGES FOR SYSTEM TESTING DEFECTS /*//from www. j a va 2 s .co m * Here file name is encoded and space is replace by special secequence of charcters, * because if file name contain space then bydefault space is converting in a plus sign (+) while downloading, * so for recognize any space in file name, space is replacing by this string @%20@ */ String encodedFileName = java.net.URLEncoder.encode(downloadedFile.getFileName().replace(" ", "@%20@"), "ISO-8859-1"); System.out.println("encoded file name is - " + encodedFileName); /* * After encoding file name, for maintaing the space character, again replace this special sequence %40%2520%40% with space character. * This sequence of characters %40%2520%40% means file name containg space space */ response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName.replace("%40%2520%40", " ")); //--end of code--// ServletOutputStream outs = response.getOutputStream(); outs.write(File); outs.flush(); outs.close(); if (downloadedFile.getIsDownload().equalsIgnoreCase("1")) { formBean.setIsDownload("successDownload"); forward = mapping.findForward(""); } else { messages.add("saveDownloadFile", new ActionMessage("FileDownloadFailed")); saveMessages(request, messages); forward = mapping.findForward(""); } try { } catch (Exception e) { AppConstants.IOES_LOGGER.error(AppUtility.getStackTrace(e)); } return forward; }
From source file:org.fcrepo.server.access.FedoraAccessServlet.java
public void getDatastreamDissemination(Context context, String PID, String dsID, Date asOfDateTime, HttpServletResponse response, HttpServletRequest request) throws IOException, ServerException { ServletOutputStream out = null; MIMETypedStream dissemination = null; dissemination = m_access.getDatastreamDissemination(context, PID, dsID, asOfDateTime); try {//w ww. j a va 2 s .c om // testing to see what's in request header that might be of interest if (logger.isDebugEnabled()) { for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); Enumeration<?> headerValues = request.getHeaders(name); StringBuffer sb = new StringBuffer(); while (headerValues.hasMoreElements()) { sb.append((String) headerValues.nextElement()); } String value = sb.toString(); logger.debug("FEDORASERVLET REQUEST HEADER CONTAINED: {} : {}", name, value); } } // Dissemination was successful; // Return MIMETypedStream back to browser client if (dissemination.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { String location = ""; for (Property prop : dissemination.header) { if (prop.name.equalsIgnoreCase(HttpHeaders.LOCATION)) { location = prop.value; break; } } response.sendRedirect(location); } else { int status = dissemination.getStatusCode(); response.setStatus(status); if (status == HttpStatus.SC_OK) { response.setContentType(dissemination.getMIMEType()); } Property[] headerArray = dissemination.header; if (headerArray != null) { for (int i = 0; i < headerArray.length; i++) { if (headerArray[i].name != null && !headerArray[i].name.equalsIgnoreCase("transfer-encoding") && !headerArray[i].name.equalsIgnoreCase("content-type")) { response.addHeader(headerArray[i].name, headerArray[i].value); logger.debug( "THIS WAS ADDED TO FEDORASERVLET RESPONSE HEADER FROM ORIGINATING PROVIDER {} : {}", headerArray[i].name, headerArray[i].value); } } } out = response.getOutputStream(); int byteStream = 0; logger.debug("Started reading dissemination stream"); InputStream dissemResult = dissemination.getStream(); byte[] buffer = new byte[BUF]; while ((byteStream = dissemResult.read(buffer)) != -1) { out.write(buffer, 0, byteStream); } buffer = null; dissemResult.close(); dissemResult = null; out.flush(); out.close(); logger.debug("Finished reading dissemination stream"); } } finally { dissemination.close(); } }
From source file:com.globalsight.connector.eloqua.EloquaCreateJobHandler.java
@ActionHandler(action = "getFileProfile", formClass = "") public void getFileProfile(HttpServletRequest request, HttpServletResponse response, Object form) throws Exception { ServletOutputStream out = response.getOutputStream(); try {/*from ww w .ja va 2s. c o m*/ String currentCompanyId = CompanyThreadLocal.getInstance().getValue(); HttpSession session = request.getSession(false); SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER); User user = (User) sessionMgr.getAttribute(WebAppConstants.USER); if (user == null) { String userName = request.getParameter("userName"); if (userName != null && !"".equals(userName)) { user = ServerProxy.getUserManager().getUserByName(userName); sessionMgr.setAttribute(WebAppConstants.USER, user); } } ArrayList<FileProfileImpl> fileProfileListOfUser = new ArrayList<FileProfileImpl>(); List<String> extensionList = new ArrayList<String>(); extensionList.add("html"); List<FileProfileImpl> fileProfileListOfCompany = (List) ServerProxy.getFileProfilePersistenceManager() .getFileProfilesByExtension(extensionList, Long.valueOf(currentCompanyId)); SortUtil.sort(fileProfileListOfCompany, new Comparator<Object>() { public int compare(Object arg0, Object arg1) { FileProfileImpl a0 = (FileProfileImpl) arg0; FileProfileImpl a1 = (FileProfileImpl) arg1; return a0.getName().compareToIgnoreCase(a1.getName()); } }); List projectsOfCurrentUser = ServerProxy.getProjectHandler().getProjectsByUser(user.getUserId()); for (FileProfileImpl fp : fileProfileListOfCompany) { Project fpProj = getProject(fp); // get the project and check if it is in the group of // user's projects if (projectsOfCurrentUser.contains(fpProj)) { fileProfileListOfUser.add(fp); } } List l = new ArrayList(); for (FileProfileImpl fp : fileProfileListOfUser) { Map m = new HashMap(); m.put("id", fp.getId()); m.put("name", fp.getName()); m.put("lid", fp.getL10nProfileId()); l.add(m); } out.write(JsonUtil.toJson(l).getBytes("UTF-8")); } catch (ValidateException ve) { ResourceBundle bundle = PageHandler.getBundle(request.getSession()); String s = "({\"error\" : " + JsonUtil.toJson(ve.getMessage(bundle)) + "})"; out.write(s.getBytes("UTF-8")); } catch (Exception e) { String s = "({\"error\" : " + JsonUtil.toObjectJson(e.getMessage()) + "})"; out.write(s.getBytes("UTF-8")); } finally { out.close(); pageReturn(); } }
From source file:org.openmrs.module.mohtracportal.util.FileExporter.java
/** * Auto generated method comment//from ww w . j a va 2 s .c om * * @param request * @param response * @param res * @param filename * @param title * @param to * @param from * @param selectedUsers * @throws Exception */ public void exportToCSVFile(HttpServletRequest request, HttpServletResponse response, List<Object> res, String filename, String title, String from, String to, List<Integer> selectedUsers) throws Exception { SimpleDateFormat sdf = Context.getDateFormat(); ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); PersonService ps = Context.getPersonService(); String users = ""; for (Integer usrId : selectedUsers) { users += ps.getPerson(usrId).getPersonName() + "; "; } response.setContentType("text/plain"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); outputStream.println(MohTracUtil.getMessage("mohtracportal.report.title", null) + ", : " + title); if (from.trim().compareTo("") != 0) outputStream.println(MohTracUtil.getMessage("mohtracportal.from", null) + ", : " + from); if (to.trim().compareTo("") != 0) outputStream.println(MohTracUtil.getMessage("mohtracportal.to", null) + ", : " + to); outputStream.println(MohTracUtil.getMessage("mohtracportal.report.created.on", null) + ", : " + sdf.format(new Date()));// Report // date outputStream.println(MohTracUtil.getMessage("mohtracportal.report.created.by", null) + ", : " + Context.getAuthenticatedUser().getPersonName());// Report // author if (users.trim().compareTo("") != 0) outputStream .println(MohTracUtil.getMessage("mohtracportal.patient.enterers", null) + ", : " + users); outputStream.println(); Integer numberOfPatients = res.size(); outputStream.println(MohTracUtil.getMessage("mohtracportal.numberOfPatients", null) + ", " + numberOfPatients.toString()); outputStream.println(); boolean hasPrivToViewPatientNames = Context.getAuthenticatedUser().hasPrivilege("View Patient Names"); outputStream.println(MohTracUtil.getMessage("mohtracportal.report.list.no", null) + "," + ((hasPrivToViewPatientNames) ? MohTracUtil.getMessage("mohtracportal.patient.names", null) + ", " : "") + MohTracPortalTag.getIdentifierTypeNameByIdAsString( "" + MohTracConfigurationUtil.getTracNetIdentifierTypeId()) + ", " + MohTracPortalTag.getIdentifierTypeNameByIdAsString( "" + MohTracConfigurationUtil.getLocalHealthCenterIdentifierTypeId()) + ", " + MohTracUtil.getMessage("mohtracportal.patient.date.created", null) + "(" + Context.getDateFormat().toPattern() + "), " + MohTracUtil.getMessage("mohtracportal.numberOfEncounters", null)); outputStream.println(); int ids = 0; for (Object patient : res) { Object[] o = (Object[]) patient; ids += 1; outputStream.println(ids + "," + ((hasPrivToViewPatientNames) ? MohTracPortalTag.getPersonNames(Integer.valueOf(o[0].toString())) + "," : "") + MohTracPortalTag.personIdentifierByPatientIdAndIdentifierTypeId( Integer.valueOf(o[0].toString()), MohTracConfigurationUtil.getTracNetIdentifierTypeId()) + "," + MohTracPortalTag.personIdentifierByPatientIdAndIdentifierTypeId( Integer.valueOf(o[0].toString()), MohTracConfigurationUtil.getLocalHealthCenterIdentifierTypeId()) + "," + sdf.format(o[1]) + "," + MohTracPortalTag.getNumberOfEncounterByPatient(Integer.valueOf(o[0].toString()))); } outputStream.flush(); log.info("csv File created"); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } finally { if (null != outputStream) outputStream.close(); } }
From source file:de.fau.amos.ChartRenderer.java
/** * // w w w.j a v a 2s . c o m * Reads Information from request and returns respective chart (.png-type) in response * * @param request Request from website. Contains info about what should be displayed in chart. * @param response Contains .png-file with ready-to-use chart. * * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("image/png"); ServletOutputStream os = response.getOutputStream(); //<img src="../ChartRenderer?selectedChartType=<%=chartType%>&time=<%out.println(time+(timeGranularity==3?"&endTime="+endTime:""));%>&timeGranularity=<%=timeGranularity%>&countType=<%=countType%>&groupParameters=<%out.println(ChartPreset.createParameterString(request));%>" /> JFreeChart chart = null; // Parameters from URL String chartType = request.getParameter("selectedChartType"); if (chartType != null) { chartType = chartType.trim(); } else { chartType = ""; } String startTime = request.getParameter("startTime"); String endTime = request.getParameter("endTime"); String timeGranularity = request.getParameter("timeGranularity"); String stringTimeGranularity = timeGranularityToString(timeGranularity); String countType = countTypeToString(request.getParameter("countType")); String groupLocationParameters = encodeGroupParameters(request.getParameter("groupLocationParameters")); String groupFormatParameters = encodeGroupParameters(request.getParameter("groupFormatParameters")); String unit = request.getParameter("unit"); int width = 100; try { width = Integer.parseInt(request.getParameter("w")); } catch (NumberFormatException e) { } int height = 100; try { height = Integer.parseInt(request.getParameter("h")); } catch (NumberFormatException e) { } if (chartType.equals("1")) { //show time chart // Create TimeSeriesCollection from URL-Parameters. This includes the SQL Query TimeSeriesCollection dataset = null; dataset = createTimeCollection(stringTimeGranularity, startTime, endTime, countType, groupLocationParameters, unit); // Create Chart from TimeSeriesCollection and do graphical modifications. if (timeGranularity.equals("0")) { chart = createTimeLineChart(dataset, timeGranularity, startTime, unit); } else { chart = createTimeBarChart(dataset, timeGranularity, startTime, unit); } } else if (chartType.equals("2")) { //show location-format chart DefaultCategoryDataset dataset = createLocationFormatCollection(startTime, endTime, countType, groupLocationParameters, groupFormatParameters, unit, chartType); chart = createLocationFormatChart(dataset, unit); } else if (chartType.equals("3")) { //show location-format chart DefaultCategoryDataset dataset = createLocationFormatCollection(startTime, endTime, countType, groupLocationParameters, groupFormatParameters, unit, chartType); chart = createLocationFormatChart(dataset, unit); } else if (chartType.equals("forecast")) { TimeSeriesCollection dataset = createForecastCollection(request.getParameter("forecastYear"), request.getParameter("forecastPlant"), request.getParameter("forecastMethod"), request.getParameter("forecastUnits")); chart = createForecastChart(dataset, "2004-01-01 00:00:00", "1"); } //create Image and clear output stream RenderedImage chartImage = chart.createBufferedImage(width, height); ImageIO.write(chartImage, "png", os); os.flush(); os.close(); }
From source file:gov.nih.nci.evs.browser.servlet.AjaxServlet.java
public void exportVSDToXMLAction(HttpServletRequest request, HttpServletResponse response) { String selectedvalueset = null; String multiplematches = HTTPUtils.cleanXSS((String) request.getParameter("multiplematches")); if (multiplematches != null) { selectedvalueset = HTTPUtils.cleanXSS((String) request.getParameter("valueset")); } else {//from w ww . j a va2 s . co m selectedvalueset = HTTPUtils.cleanXSS((String) request.getParameter("vsd_uri")); if (selectedvalueset != null && selectedvalueset.indexOf("|") != -1) { Vector u = DataUtils.parseData(selectedvalueset); selectedvalueset = (String) u.elementAt(1); } } String uri = selectedvalueset; request.getSession().setAttribute("selectedvalueset", uri); String xml_str = valueSetDefinition2XMLString(uri); try { response.setContentType("text/xml"); String vsd_name = DataUtils.valueSetDefiniionURI2Name(uri); vsd_name = vsd_name.replaceAll(" ", "_"); vsd_name = vsd_name + ".xml"; response.setHeader("Content-Disposition", "attachment; filename=" + vsd_name); response.setContentLength(xml_str.length()); ServletOutputStream ouputStream = response.getOutputStream(); ouputStream.write(xml_str.getBytes("UTF8"), 0, xml_str.length()); ouputStream.flush(); ouputStream.close(); } catch (IOException e) { e.printStackTrace(); } FacesContext.getCurrentInstance().responseComplete(); }
From source file:gov.nih.nci.evs.browser.servlet.AjaxServlet.java
public void export_mapping(HttpServletRequest request, HttpServletResponse response) { String mapping_schema = HTTPUtils.cleanXSS((String) request.getParameter("dictionary")); String mapping_version = HTTPUtils.cleanXSS((String) request.getParameter("version")); ResolvedConceptReferencesIterator iterator = DataUtils.getMappingDataIterator(mapping_schema, mapping_version);//from w w w. j a va 2s . c o m int numRemaining = 0; if (iterator != null) { try { numRemaining = iterator.numberRemaining(); //System.out.println("number of records: " + numRemaining); } catch (Exception ex) { ex.printStackTrace(); } } StringBuffer sb = new StringBuffer(); try { sb.append("Source Code,"); sb.append("Source Name,"); sb.append("Source Coding Scheme,"); sb.append("Source Coding Scheme Version,"); sb.append("Source Coding Scheme Namespace,"); sb.append("Association Name,"); sb.append("REL,"); sb.append("Map Rank,"); sb.append("Target Code,"); sb.append("Target Name,"); sb.append("Target Coding Scheme,"); sb.append("Target Coding Scheme Version,"); sb.append("Target Coding Scheme Namespace"); sb.append("\r\n"); MappingIteratorBean bean = new MappingIteratorBean(iterator); List list = bean.getData(0, numRemaining - 1); for (int k = 0; k < list.size(); k++) { MappingData mappingData = (MappingData) list.get(k); sb.append("\"" + mappingData.getSourceCode() + "\","); sb.append("\"" + mappingData.getSourceName() + "\","); sb.append("\"" + mappingData.getSourceCodingScheme() + "\","); sb.append("\"" + mappingData.getSourceCodingSchemeVersion() + "\","); sb.append("\"" + mappingData.getSourceCodeNamespace() + "\","); sb.append("\"" + mappingData.getAssociationName() + "\","); sb.append("\"" + mappingData.getRel() + "\","); sb.append("\"" + mappingData.getScore() + "\","); sb.append("\"" + mappingData.getTargetCode() + "\","); sb.append("\"" + mappingData.getTargetName() + "\","); sb.append("\"" + mappingData.getTargetCodingScheme() + "\","); sb.append("\"" + mappingData.getTargetCodingSchemeVersion() + "\","); sb.append("\"" + mappingData.getTargetCodeNamespace() + "\""); sb.append("\r\n"); } } catch (Exception ex) { sb.append("WARNING: Export to CVS action failed."); ex.printStackTrace(); } String filename = mapping_schema + "_" + mapping_version; filename = filename.replaceAll(" ", "_"); filename = filename + ".csv"; response.setContentType("text/csv"); response.setHeader("Content-Disposition", "attachment; filename=" + filename); response.setContentLength(sb.length()); try { ServletOutputStream ouputStream = response.getOutputStream(); ouputStream.write(sb.toString().getBytes("UTF-8"), 0, sb.length()); ouputStream.flush(); ouputStream.close(); } catch (Exception ex) { ex.printStackTrace(); sb.append("WARNING: Export to CVS action failed."); } FacesContext.getCurrentInstance().responseComplete(); return; }
From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java
@Override public void newCheckDetails(HttpServletResponse theResponse, HttpServletRequest theRequest) throws BankingException { Session printBeanSession = itsSessionFactory.openSession(); SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) printBeanSession .getSessionFactory();//from w ww .ja v a 2 s. c om ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider(); Map<String, Object> params = new HashMap<String, Object>(); Connection connection = null; try { itsLogger.info("Testing:--->" + theRequest.getParameter("moTransactionID")); params.put("traxID", Integer.parseInt(theRequest.getParameter("moTransactionID"))); ServletOutputStream out = theResponse.getOutputStream(); String fileName = theRequest.getParameter("fileName"); theResponse.setHeader("Content-Disposition", "attachment; filename=" + fileName); theResponse.setContentType("application/pdf"); connection = connectionProvider.getConnection(); String path_JRXML = theRequest.getSession().getServletContext() .getRealPath("/resources/jasper_reports/newcheck.jrxml"); JasperReport report = JasperCompileManager.compileReport(path_JRXML); JasperPrint print = JasperFillManager.fillReport(report, params, connection); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JasperExportManager.exportReportToPdfStream(print, baos); out.write(baos.toByteArray()); out.flush(); out.close(); } catch (Exception e) { itsLogger.error(e.getMessage(), e); BankingException aBankingException = new BankingException(e.getMessage(), e); } finally { try { if (connectionProvider != null) { connectionProvider.closeConnection(connection); connectionProvider = null; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } printBeanSession.flush(); printBeanSession.close(); } }
From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java
@Override public void creditCheckDetails(HttpServletResponse theResponse, HttpServletRequest theRequest) throws BankingException { Session printBeanSession = itsSessionFactory.openSession(); SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) printBeanSession .getSessionFactory();//www . j a v a2 s . c o m ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider(); Map<String, Object> params = new HashMap<String, Object>(); Connection connection = null; Rxaddress address = null; try { itsLogger.info("Testing:--->" + theRequest.getParameter("moTransactionID")); ServletOutputStream out = theResponse.getOutputStream(); String fileName = theRequest.getParameter("fileName"); theResponse.setHeader("Content-Disposition", "attachment; filename=" + fileName); theResponse.setContentType("application/pdf"); connection = connectionProvider.getConnection(); String path_JRXML = theRequest.getSession().getServletContext() .getRealPath("/resources/jasper_reports/CreditPayment.jrxml"); JasperReport report = JasperCompileManager.compileReport(path_JRXML); JasperPrint print = JasperFillManager.fillReport(report, params, connection); ByteArrayOutputStream baos = new ByteArrayOutputStream(); JasperExportManager.exportReportToPdfStream(print, baos); out.write(baos.toByteArray()); out.flush(); out.close(); } catch (Exception e) { itsLogger.error(e.getMessage(), e); BankingException aBankingException = new BankingException(e.getMessage(), e); // throw aBankingException; } finally { try { if (connectionProvider != null) { connectionProvider.closeConnection(connection); connectionProvider = null; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } printBeanSession.flush(); printBeanSession.close(); } }