List of usage examples for java.io ByteArrayOutputStream writeTo
public synchronized void writeTo(OutputStream out) throws IOException
From source file:org.kuali.ole.module.purap.document.web.struts.PurchaseOrderAction.java
/** * Print the list of PO Quote requests.//from ww w .j a v a 2 s. c o m * * @param mapping An ActionMapping * @param form An ActionForm * @param request The HttpServletRequest * @param response The HttpServletResponse * @return An ActionForward * @throws Exception */ public ActionForward printPoQuoteListOnly(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String poDocId = request.getParameter("docId"); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); try { StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PURAP_PO_QUOTE_LIST_"); sbFilename.append(poDocId); sbFilename.append("_"); sbFilename.append(System.currentTimeMillis()); sbFilename.append(".pdf"); boolean success = SpringContext.getBean(PurchaseOrderService.class) .printPurchaseOrderQuoteRequestsListPDF(poDocId, baosPDF); if (!success) { if (baosPDF != null) { baosPDF.reset(); } return mapping.findForward(OLEConstants.MAPPING_PORTAL); } 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"); } sbContentDispValue.append("; filename="); sbContentDispValue.append(sbFilename); response.setHeader("Content-disposition", sbContentDispValue.toString()); response.setContentLength(baosPDF.size()); ServletOutputStream sos; sos = response.getOutputStream(); baosPDF.writeTo(sos); sos.flush(); } finally { if (baosPDF != null) { baosPDF.reset(); } } return null; }
From source file:org.kuali.ole.module.purap.document.web.struts.PurchaseOrderAction.java
/** * Print a particular selected PO Quote as a PDF. * * @param mapping An ActionMapping/*from ww w . ja va 2s . c o m*/ * @param form An ActionForm -- The PO Quote must be selected here. * @param request The HttpServletRequest * @param response The HttpServletResponse * @return An ActionForward * @throws Exception */ public ActionForward printPoQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // String poDocId = request.getParameter("docId"); // PurchaseOrderDocument po = (PurchaseOrderDocument) // SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(poDocId); // Integer poSelectedVendorId = new Integer(request.getParameter("quoteVendorId")); KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form; PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument(); PurchaseOrderVendorQuote poVendorQuote = po.getPurchaseOrderVendorQuotes().get(getSelectedLine(request)); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); poVendorQuote.setTransmitPrintDisplayed(false); try { StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PURAP_PO_QUOTE_"); sbFilename.append(po.getPurapDocumentIdentifier()); sbFilename.append("_"); sbFilename.append(System.currentTimeMillis()); sbFilename.append(".pdf"); boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po, poVendorQuote, baosPDF); if (!success) { poVendorQuote.setTransmitPrintDisplayed(true); poVendorQuote.setPdfDisplayedToUserOnce(false); if (baosPDF != null) { baosPDF.reset(); } return mapping.findForward(OLEConstants.MAPPING_BASIC); } response.setHeader("Cache-Control", "max-age=30"); response.setContentType("application/pdf"); StringBuffer sbContentDispValue = new StringBuffer(); // sbContentDispValue.append("inline"); sbContentDispValue.append("attachment"); sbContentDispValue.append("; filename="); sbContentDispValue.append(sbFilename); response.setHeader("Content-disposition", sbContentDispValue.toString()); response.setContentLength(baosPDF.size()); ServletOutputStream sos; sos = response.getOutputStream(); baosPDF.writeTo(sos); sos.flush(); } finally { if (baosPDF != null) { baosPDF.reset(); } } return null; }
From source file:org.kuali.kfs.module.purap.document.web.struts.PurchaseOrderAction.java
/** * Print the list of PO Quote requests.//ww w .jav a2 s.co m * * @param mapping An ActionMapping * @param form An ActionForm * @param request The HttpServletRequest * @param response The HttpServletResponse * @throws Exception * @return An ActionForward */ public ActionForward printPoQuoteListOnly(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String poDocId = request.getParameter("docId"); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); try { StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PURAP_PO_QUOTE_LIST_"); sbFilename.append(poDocId); sbFilename.append("_"); sbFilename.append(System.currentTimeMillis()); sbFilename.append(".pdf"); boolean success = SpringContext.getBean(PurchaseOrderService.class) .printPurchaseOrderQuoteRequestsListPDF(poDocId, baosPDF); if (!success) { if (baosPDF != null) { baosPDF.reset(); } return mapping.findForward(KFSConstants.MAPPING_PORTAL); } 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"); } sbContentDispValue.append("; filename="); sbContentDispValue.append(sbFilename); response.setHeader("Content-disposition", sbContentDispValue.toString()); response.setContentLength(baosPDF.size()); ServletOutputStream sos; sos = response.getOutputStream(); baosPDF.writeTo(sos); sos.flush(); } finally { if (baosPDF != null) { baosPDF.reset(); } } return null; }
From source file:org.kuali.kfs.module.purap.document.web.struts.PurchaseOrderAction.java
/** * Print a particular selected PO Quote as a PDF. * * @param mapping An ActionMapping/*from w ww.jav a2 s . c o m*/ * @param form An ActionForm -- The PO Quote must be selected here. * @param request The HttpServletRequest * @param response The HttpServletResponse * @throws Exception * @return An ActionForward */ public ActionForward printPoQuote(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // String poDocId = request.getParameter("docId"); // PurchaseOrderDocument po = (PurchaseOrderDocument) // SpringContext.getBean(DocumentService.class).getByDocumentHeaderId(poDocId); // Integer poSelectedVendorId = new Integer(request.getParameter("quoteVendorId")); KualiDocumentFormBase kualiDocumentFormBase = (KualiDocumentFormBase) form; PurchaseOrderDocument po = (PurchaseOrderDocument) kualiDocumentFormBase.getDocument(); PurchaseOrderVendorQuote poVendorQuote = po.getPurchaseOrderVendorQuotes().get(getSelectedLine(request)); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); poVendorQuote.setTransmitPrintDisplayed(false); try { StringBuffer sbFilename = new StringBuffer(); sbFilename.append("PURAP_PO_QUOTE_"); sbFilename.append(po.getPurapDocumentIdentifier()); sbFilename.append("_"); sbFilename.append(System.currentTimeMillis()); sbFilename.append(".pdf"); boolean success = SpringContext.getBean(PurchaseOrderService.class).printPurchaseOrderQuotePDF(po, poVendorQuote, baosPDF); if (!success) { poVendorQuote.setTransmitPrintDisplayed(true); poVendorQuote.setPdfDisplayedToUserOnce(false); if (baosPDF != null) { baosPDF.reset(); } return mapping.findForward(KFSConstants.MAPPING_BASIC); } response.setHeader("Cache-Control", "max-age=30"); response.setContentType("application/pdf"); StringBuffer sbContentDispValue = new StringBuffer(); // sbContentDispValue.append("inline"); sbContentDispValue.append("attachment"); sbContentDispValue.append("; filename="); sbContentDispValue.append(sbFilename); response.setHeader("Content-disposition", sbContentDispValue.toString()); response.setContentLength(baosPDF.size()); ServletOutputStream sos; sos = response.getOutputStream(); baosPDF.writeTo(sos); sos.flush(); } finally { if (baosPDF != null) { baosPDF.reset(); } } return null; }
From source file:net.lightbody.bmp.proxy.jetty.http.handler.DumpHandler.java
public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException { if (!isStarted()) return;// w w w .j a v a 2 s. c o m // Only handle GET, HEAD and POST if (!HttpRequest.__GET.equals(request.getMethod()) && !HttpRequest.__HEAD.equals(request.getMethod()) && !HttpRequest.__POST.equals(request.getMethod())) return; log.debug("Dump"); response.setField(HttpFields.__ContentType, HttpFields.__TextHtml); OutputStream out = response.getOutputStream(); ByteArrayOutputStream buf = new ByteArrayOutputStream(2048); Writer writer = new OutputStreamWriter(buf, StringUtil.__ISO_8859_1); writer.write("<HTML><H1>Dump HttpHandler</H1>"); writer.write("<PRE>\npath=" + request.getPath() + "\ncontextPath=" + getHttpContext().getContextPath() + "\npathInContext=" + pathInContext + "\n</PRE>\n"); writer.write("<H3>Header:</H3><PRE>"); writer.write(request.toString()); writer.write("</PRE>\n<H3>Parameters:</H3>\n<PRE>"); Set names = request.getParameterNames(); Iterator iter = names.iterator(); while (iter.hasNext()) { String name = iter.next().toString(); List values = request.getParameterValues(name); if (values == null || values.size() == 0) { writer.write(name); writer.write("=\n"); } else if (values.size() == 1) { writer.write(name); writer.write("="); writer.write((String) values.get(0)); writer.write("\n"); } else { for (int i = 0; i < values.size(); i++) { writer.write(name); writer.write("[" + i + "]="); writer.write((String) values.get(i)); writer.write("\n"); } } } String cookie_name = request.getParameter("CookieName"); if (cookie_name != null && cookie_name.trim().length() > 0) { String cookie_action = request.getParameter("Button"); try { Cookie cookie = new Cookie(cookie_name.trim(), request.getParameter("CookieVal")); if ("Clear Cookie".equals(cookie_action)) cookie.setMaxAge(0); response.addSetCookie(cookie); } catch (IllegalArgumentException e) { writer.write("</PRE>\n<H3>BAD Set-Cookie:</H3>\n<PRE>"); writer.write(e.toString()); LogSupport.ignore(log, e); } } writer.write("</PRE>\n<H3>Cookies:</H3>\n<PRE>"); Cookie[] cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (int c = 0; c < cookies.length; c++) { Cookie cookie = cookies[c]; writer.write(cookie.getName()); writer.write("="); writer.write(cookie.getValue()); writer.write("\n"); } } writer.write("</PRE>\n<H3>Attributes:</H3>\n<PRE>"); Enumeration attributes = request.getAttributeNames(); if (attributes != null && attributes.hasMoreElements()) { while (attributes.hasMoreElements()) { String attr = attributes.nextElement().toString(); writer.write(attr); writer.write("="); writer.write(request.getAttribute(attr).toString()); writer.write("\n"); } } writer.write("</PRE>\n<H3>Content:</H3>\n<PRE>"); byte[] content = new byte[4096]; int len; try { InputStream in = request.getInputStream(); while ((len = in.read(content)) >= 0) writer.write(new String(content, 0, len)); } catch (IOException e) { LogSupport.ignore(log, e); writer.write(e.toString()); } // You wouldn't normally set a trailer like this, but // we don't want to commit the output to force trailers as // it makes test harness messy request.getAcceptableTransferCodings(); // commit now writer.flush(); response.setIntField(HttpFields.__ContentLength, buf.size() + 1000); buf.writeTo(out); out.flush(); // Now add the response buf.reset(); writer.write("</PRE>\n<H3>Response:</H3>\n<PRE>"); writer.write(response.toString()); writer.write("</PRE></HTML>"); writer.flush(); for (int pad = 998 - buf.size(); pad-- > 0;) writer.write(" "); writer.write("\015\012"); writer.flush(); buf.writeTo(out); request.setHandled(true); }
From source file:org.sakaiproject.chat2.model.impl.ChatEntityProducer.java
/** * {@inheritDoc}/*from www . ja v a 2 s .co m*/ */ public HttpAccess getHttpAccess() { return new HttpAccess() { public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref, Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException { try { //TODO: Isn't there a better way to do this than build out the whole page here?? // We need to write to a temporary stream for better speed, plus // so we can get a byte count. Internet Explorer has problems // if we don't make the setContentLength() call. ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); OutputStreamWriter sw = new OutputStreamWriter(outByteStream); String skin = ServerConfigurationService.getString("skin.default"); String skinRepo = ServerConfigurationService.getString("skin.repo"); ChatMessage message = getMessage(ref); String title = ref.getDescription(); //MessageHeader messageHead = message.getHeader(); //String date = messageHead.getDate().toStringLocalFullZ(); String date = TimeService.newTime(message.getMessageDate().getTime()).toStringLocalFullZ(); String from = UserDirectoryService.getUser(message.getOwner()).getDisplayName(); //String from = messageHead.getFrom().getDisplayName(); String groups = ""; //Collection gr = messageHead.getGroups(); //for (Iterator i = gr.iterator(); i.hasNext();) //{ // groups += "<li>" + i.next() + "</li>"; //} String body = Web.escapeHtml(message.getBody()); sw.write( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n" + "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" + "<link href=\""); sw.write(skinRepo); sw.write("/tool_base.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n" + "<link href=\""); sw.write(skinRepo); sw.write("/"); sw.write(skin); sw.write("/tool.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n" + "<meta http-equiv=\"Content-Style-Type\" content=\"text/css\" />\n" + "<title>"); sw.write(title); sw.write("</title></head><body><div class=\"portletBody\">\n" + "<h2>"); sw.write(title); sw.write("</h2><ul><li>Date "); sw.write(date); sw.write("</li>"); sw.write("<li>From "); sw.write(from); sw.write("</li>"); sw.write(groups); sw.write("<ul><p>"); sw.write(body); sw.write("</p></div></body></html> "); sw.flush(); res.setContentType("text/html"); res.setContentLength(outByteStream.size()); if (outByteStream.size() > 0) { // Increase the buffer size for more speed. res.setBufferSize(outByteStream.size()); } OutputStream out = null; try { out = res.getOutputStream(); if (outByteStream.size() > 0) { outByteStream.writeTo(out); } out.flush(); out.close(); } catch (Throwable ignore) { } finally { if (out != null) { try { out.close(); } catch (Throwable ignore) { } } } } catch (PermissionException e) { throw new EntityPermissionException(e.getUser(), e.getLocalizedMessage(), e.getResource()); } catch (IdUnusedException e) { throw new EntityNotDefinedException(e.getId()); } catch (Throwable t) { throw new RuntimeException("Faied to find message ", t); } } }; }
From source file:org.kuali.kfs.module.tem.document.web.struts.TravelActionBase.java
/** * * @param request//from w ww. j av a2 s . c om * @param response * @param reportFile * @param fileName * @throws IOException */ @SuppressWarnings("rawtypes") protected void displayPDF(HttpServletRequest request, HttpServletResponse response, File reportFile, StringBuilder fileName) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); String contentDisposition = ""; try { ArrayList master = new ArrayList(); PdfCopy writer = null; // create a reader for the document String reportName = reportFile.getAbsolutePath(); PdfReader reader = new PdfReader(reportName); reader.consolidateNamedDestinations(); // retrieve the total number of pages int n = reader.getNumberOfPages(); List bookmarks = SimpleBookmark.getBookmark(reader); if (bookmarks != null) { master.addAll(bookmarks); } // step 1: create a document-object com.lowagie.text.Document pdfDoc = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); // step 2: create a writer that listens to the document writer = new PdfCopy(pdfDoc, baos); // step 3: open the document pdfDoc.open(); // step 4: add content PdfImportedPage page; for (int i = 0; i < n;) { ++i; page = writer.getImportedPage(reader, i); writer.addPage(page); } writer.freeReader(reader); if (!master.isEmpty()) { writer.setOutlines(master); } // step 5: we close the document pdfDoc.close(); StringBuffer sbContentDispValue = new StringBuffer(); String useJavascript = request.getParameter("useJavascript"); if (useJavascript == null || useJavascript.equalsIgnoreCase("false")) { sbContentDispValue.append("attachment"); } else { sbContentDispValue.append("inline"); } sbContentDispValue.append("; filename="); sbContentDispValue.append(fileName); contentDisposition = sbContentDispValue.toString(); } catch (Exception e) { e.printStackTrace(); } response.setContentType("application/pdf"); response.setHeader("Content-Disposition", contentDisposition); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setContentLength(baos.size()); // write to output ServletOutputStream sos; sos = response.getOutputStream(); baos.writeTo(sos); sos.flush(); sos.close(); }
From source file:com.sr.apps.freightbit.documentation.action.DocumentAction.java
public String generateProformaReport() { System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>orderIdParam " + orderIdParam); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>documentIdParam " + documentIdParam); Documents documentEntity = documentsService.findDocumentById(documentIdParam); String orderId = (documentEntity.getReferenceId()).toString(); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>orderId " + orderId); Map<String, String> params = new HashMap(); params.put("orderId", orderId); ByteArrayOutputStream byteArray = null; BufferedOutputStream responseOut = null; try {/*from www . j av a 2s . c o m*/ final File outputFile = new File("Proforma Bill of Lading.pdf"); MasterReport report = proformaBillOfLadingReportService.generateReport(params); HttpServletResponse response = ServletActionContext.getResponse(); responseOut = new BufferedOutputStream(response.getOutputStream()); byteArray = new ByteArrayOutputStream(); boolean isRendered = PdfReportUtil.createPDF(report, byteArray); byteArray.writeTo(responseOut); byteArray.close(); responseOut.close(); } catch (Exception re) { re.printStackTrace(); } return null; }
From source file:com.sr.apps.freightbit.documentation.action.DocumentAction.java
public String generateHouseWayBillReport() { Documents documentEntity = documentsService.findDocumentById(documentIdParam); String orderId = (documentEntity.getReferenceId()).toString(); String documentId = (documentEntity.getDocumentId().toString()); Map<String, String> params = new HashMap(); params.put("orderId", orderId); params.put("documentId", documentId); ByteArrayOutputStream byteArray = null; BufferedOutputStream responseOut = null; try {//from w w w .j av a2 s . co m // Create an output filename final File outputFile = new File("Way Bill.pdf"); // Generate the report MasterReport report = houseWayBillService.generateReport(params); HttpServletResponse response = ServletActionContext.getResponse(); responseOut = new BufferedOutputStream(response.getOutputStream()); byteArray = new ByteArrayOutputStream(); boolean isRendered = PdfReportUtil.createPDF(report, byteArray); byteArray.writeTo(responseOut); byteArray.close(); responseOut.close(); } catch (Exception re) { re.printStackTrace(); } return null; }
From source file:com.sr.apps.freightbit.documentation.action.DocumentAction.java
public String generateReleaseOrderReport() { Documents documentEntity = documentsService.findDocumentById(documentIdParam); String orderId = (documentEntity.getReferenceId()).toString(); String documentId = (documentEntity.getDocumentId().toString()); Map<String, String> params = new HashMap(); params.put("orderId", orderId); params.put("documentId", documentId); ByteArrayOutputStream byteArray = null; BufferedOutputStream responseOut = null; try {//from ww w . j a v a 2 s . c o m // Create an output filename final File outputFile = new File("Release Order.pdf"); // Generate the report MasterReport report = releaseOrderReportService.generateReport(params); HttpServletResponse response = ServletActionContext.getResponse(); responseOut = new BufferedOutputStream(response.getOutputStream()); byteArray = new ByteArrayOutputStream(); boolean isRendered = PdfReportUtil.createPDF(report, byteArray); byteArray.writeTo(responseOut); byteArray.close(); responseOut.close(); } catch (Exception re) { re.printStackTrace(); } return null; }