/** * This method will open the sample report pdf. * * @param reportFilePath - full path of the sample report to be shown. * @param request - instance of HttpServletRequest * @param response - instance of HttpServletResponse * @throws ServletException - error * @throws IOException - error */ private static void showSampleReport( String reportFilePath, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (null != request.getSession().getAttribute(ReportServiceConstant.VIEW_SAMPLE_REPORT) && request .getSession() .getAttribute(ReportServiceConstant.VIEW_SAMPLE_REPORT) .toString() .equalsIgnoreCase("Y")) { ServletOutputStream output = null; try { FileInputStream fis = new FileInputStream(reportFilePath); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[256]; try { for (int readNum; (readNum = fis.read(buf)) != -1; ) { baos.write(buf, 0, readNum); // no doubt here is 0 // Writes len bytes from the specified byte array starting at offset off to this byte // array output stream. } } catch (IOException ex) { ex.printStackTrace(); } if (null != baos) { // Init servlet response. response.reset(); response.setContentType("application/pdf"); response.setContentLength(baos.size()); response.setHeader("Content-disposition", "inline; filename=\"" + reportFilePath); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); // response.setHeader("Transfer-Encoding", "identity"); output = response.getOutputStream(); output.write(baos.toByteArray(), 0, baos.size()); // Finalize task. output.flush(); } } catch (Exception exception) { OPPE_LOG.error("ERROR.SHOW_PDF.ERROR", exception); } finally { // Gently close streams. close((Closeable) output); } } }
/** * return OutputStream of JasperReport object, this page could only be viewed from localhost for * security concern. parameter can be (id), or (table and type) * * @param id - report id, or * @param table - table name * @param type - reporttype "s","l","o", case insensitive * @param client(*) - client domain * @param version - version number, default to -1 */ public void process(HttpServletRequest request, HttpServletResponse response) throws Exception { String clientName = request.getParameter("client"); int objectId = ParamUtils.getIntAttributeOrParameter(request, "id", -1); if (objectId == -1) { // try using table and type objectId = getReportId(clientName, request.getParameter("table"), request.getParameter("type")); } if (objectId == -1) { logger.error("report not found, request is:" + Tools.toString(request)); throw new NDSException("report not found"); } int version = ParamUtils.getIntAttributeOrParameter(request, "version", -1); File reportXMLFile = new File(ReportTools.getReportFile(objectId, clientName)); if (reportXMLFile.exists()) { // generate jasperreport if file not exists or not newer String reportName = reportXMLFile.getName().substring(0, reportXMLFile.getName().lastIndexOf(".")); File reportJasperFile = new File(reportXMLFile.getParent(), reportName + ".jasper"); if (!reportJasperFile.exists() || reportJasperFile.lastModified() < reportXMLFile.lastModified()) { JasperCompileManager.compileReportToFile( reportXMLFile.getAbsolutePath(), reportJasperFile.getAbsolutePath()); } InputStream is = new FileInputStream(reportJasperFile); response.setContentType("application/octetstream;"); response.setContentLength((int) reportJasperFile.length()); // response.setHeader("Content-Disposition","inline;filename=\""+reportJasperFile.getName()+"\""); ServletOutputStream os = response.getOutputStream(); byte[] b = new byte[8192]; int bInt; while ((bInt = is.read(b, 0, b.length)) != -1) { os.write(b, 0, bInt); } is.close(); os.flush(); os.close(); } else { throw new NDSException("Not found report template"); } }
/** * This method handles response of showing pdf servlet. * * @param request - instance of HttpServletRequest * @param response - instance of HttpServletResponse * @throws ServletException - error * @throws IOException - error */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String preview = request.getParameter(PREVIEW_REPORT_PARAMETER); String sampleReportParam = request.getParameter(SAMPLE_REPORT_PARAM); if (null != sampleReportParam) { String sampleReportPath = ""; if (sampleReportParam.equalsIgnoreCase(ReportServiceConstant.PROVIDER_SUMMARY)) { sampleReportPath = WL_HOME_PATH + RESOURCES_PATH + ReportServiceConstant.PROVIDER_SUMMARY_SAMPLE_FILE; showSampleReport(sampleReportPath, request, response); } else if (sampleReportParam.equalsIgnoreCase(ReportServiceConstant.COMPARATIVE_SUMMARY)) { sampleReportPath = WL_HOME_PATH + RESOURCES_PATH + ReportServiceConstant.COMPARITIVE_SUMMARY_SAMPLE_FILE; showSampleReport(sampleReportPath, request, response); } else if (sampleReportParam.equalsIgnoreCase(ReportServiceConstant.EXECUTIVE_SUMMARY)) { sampleReportPath = WL_HOME_PATH + RESOURCES_PATH + ReportServiceConstant.EXECUTIVE_SUMMARY_SAMPLE_FILE; showSampleReport(sampleReportPath, request, response); } } else if (null != preview && STR_TRUE.equals(preview)) { // report generation using OracleBI ServletOutputStream output = null; byte[] rawBinaryFile = null; Map<String, String> parameterMap = null; PublicReportServicePortClient client = null; FileStream fileStream = null; try { if (null != request.getSession().getAttribute(REPORTS_PARAMETERS_MAP)) { parameterMap = (Map<String, String>) request.getSession().getAttribute(REPORTS_PARAMETERS_MAP); // request.getSession().removeAttribute(REPORTS_PARAMETERS_MAP); } if (null != parameterMap && parameterMap.containsKey("REPORT_PATH")) { client = new PublicReportServicePortClient(); fileStream = client.generateReport(parameterMap); rawBinaryFile = fileStream.getFileContent(); } if (null != rawBinaryFile) { // Init servlet response. response.reset(); response.setContentType("application/pdf"); response.setContentLength(rawBinaryFile.length); response.setHeader( "Content-disposition", "inline; filename=\"" + fileStream.getFileName() + ".pdf\""); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); // response.setHeader("Transfer-Encoding", "identity"); output = response.getOutputStream(); output.write(rawBinaryFile, 0, rawBinaryFile.length); // Finalize task. output.flush(); } } catch (Exception exception) { OPPE_LOG.error("ERROR.SHOW_PDF.ERROR", exception); } finally { // Gently close streams. close((Closeable) output); } } }
package com.jspsmart.upload;
/** * Write a file to the response stream. Handles Range requests. * * @param req request * @param res response * @param file must exists and not be a directory * @param contentType must not be null * @throws IOException or error */ public static void returnFile( HttpServletRequest req, HttpServletResponse res, File file, String contentType) throws IOException { res.setContentType(contentType); // see if its a Range Request boolean isRangeRequest = false; long startPos = 0, endPos = Long.MAX_VALUE; String rangeRequest = req.getHeader("Range"); if (rangeRequest != null) { // bytes=12-34 or bytes=12- int pos = rangeRequest.indexOf("="); if (pos > 0) { int pos2 = rangeRequest.indexOf("-"); if (pos2 > 0) { String startString = rangeRequest.substring(pos + 1, pos2); String endString = rangeRequest.substring(pos2 + 1); startPos = Long.parseLong(startString); if (endString.length() > 0) endPos = Long.parseLong(endString) + 1; isRangeRequest = true; } } } // set content length long fileSize = file.length(); long contentLength = fileSize; if (isRangeRequest) { endPos = Math.min(endPos, fileSize); contentLength = endPos - startPos; } if (contentLength > Integer.MAX_VALUE) res.addHeader( "Content-Length", Long.toString(contentLength)); // allow content length > MAX_INT else res.setContentLength((int) contentLength); // note HEAD only allows this String filename = file.getPath(); boolean debugRequest = Debug.isSet("returnFile"); if (debugRequest) log.debug( "returnFile(): filename = " + filename + " contentType = " + contentType + " contentLength = " + contentLength); // indicate we allow Range Requests res.addHeader("Accept-Ranges", "bytes"); if (req.getMethod().equals("HEAD")) { log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, 0)); return; } try { if (isRangeRequest) { // set before content is sent res.addHeader("Content-Range", "bytes " + startPos + "-" + (endPos - 1) + "/" + fileSize); res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); FileCacheRaf.Raf craf = null; try { craf = fileCacheRaf.acquire(filename); IO.copyRafB( craf.getRaf(), startPos, contentLength, res.getOutputStream(), new byte[60000]); log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext( HttpServletResponse.SC_PARTIAL_CONTENT, contentLength)); return; } finally { if (craf != null) fileCacheRaf.release(craf); } } // Return the file ServletOutputStream out = res.getOutputStream(); IO.copyFileB(file, out, 60000); res.flushBuffer(); out.close(); if (debugRequest) log.debug("returnFile(): returnFile ok = " + filename); log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_OK, contentLength)); } // @todo Split up this exception handling: those from file access vs those from dealing with // response // File access: catch and res.sendError() // response: don't catch (let bubble up out of doGet() etc) catch (FileNotFoundException e) { log.error("returnFile(): FileNotFoundException= " + filename); log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0)); if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (java.net.SocketException e) { log.info("returnFile(): SocketException sending file: " + filename + " " + e.getMessage()); log.info("returnFile(): " + UsageLog.closingMessageForRequestContext(STATUS_CLIENT_ABORT, 0)); } catch (IOException e) { String eName = e.getClass().getName(); // dont want compile time dependency on ClientAbortException if (eName.equals("org.apache.catalina.connector.ClientAbortException")) { log.info( "returnFile(): ClientAbortException while sending file: " + filename + " " + e.getMessage()); log.info( "returnFile(): " + UsageLog.closingMessageForRequestContext(STATUS_CLIENT_ABORT, 0)); return; } log.error("returnFile(): IOException (" + e.getClass().getName() + ") sending file ", e); log.error( "returnFile(): " + UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_NOT_FOUND, 0)); if (!res.isCommitted()) res.sendError(HttpServletResponse.SC_NOT_FOUND, "Problem sending file: " + e.getMessage()); } }