Example usage for java.io ByteArrayOutputStream writeTo

List of usage examples for java.io ByteArrayOutputStream writeTo

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream writeTo.

Prototype

public synchronized void writeTo(OutputStream out) throws IOException 

Source Link

Document

Writes the complete contents of this ByteArrayOutputStream to the specified output stream argument, as if by calling the output stream's write method using out.write(buf, 0, count) .

Usage

From source file:ch.unifr.pai.twice.widgets.mpproxy.server.SimpleHttpUrlConnectionServletFilter.java

/**
 * Apply the filter logic//from w  w  w  .  ja va 2 s  .  co m
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter(ServletRequest genericRequest, ServletResponse genericResponse, FilterChain chain)
        throws IOException, ServletException {
    if (genericRequest instanceof HttpServletRequest && genericResponse instanceof HttpServletResponse) {
        HttpServletRequest request = (HttpServletRequest) genericRequest;
        HttpServletResponse response = (HttpServletResponse) genericResponse;

        if (request.getSession().getAttribute(Constants.uuidCookie) == null) {
            request.getSession().setAttribute(Constants.uuidCookie, UUID.randomUUID().toString());
        }
        response.addCookie(new Cookie(Constants.uuidCookie,
                request.getSession().getAttribute(Constants.uuidCookie).toString()));
        String fullUrl = getFullRequestString(request);

        fullUrl.replace("gwt.codesvr=127.0.0.1:9997&", "");
        String servletPath = getServletPath(request);
        if (!servletPath.endsWith("/"))
            servletPath += "/";

        URLParser parser = new URLParser(fullUrl, servletPath);
        String url = parser.getFullProxyPath();

        // Prevent the managing resources to be filtered.
        if (request.getRequestURL().toString().startsWith(servletPath + Constants.nonFilterPrefix)
                || (url != null && url.equals(fullUrl))) {
            chain.doFilter(genericRequest, genericResponse);
            return;
        }

        // The read only screen
        if (request.getRequestURL().toString().contains("miceScreenShot")) {

            String result = ReadOnlyPresentation.getScreenshotForUUID(request.getParameter("uuid"));
            PrintWriter w = response.getWriter();
            if (result == null) {
                w.println("No screenshot available");
            } else {
                w.print(result);
            }
            w.flush();
            w.close();
            return;
        }
        // ProxyURLParser parser = new ProxyURLParser(fullUrl);
        // String url = parser.writeRequestUrl();
        if (url == null || url.isEmpty() || !url.startsWith("http")) {
            // We've lost context - lets try to re-establish it from
            // other
            // sources...
            String newProxyBase = null;

            // ... a referer is the best hint
            String referer = request.getHeader("Referer");
            if (referer != null && !referer.isEmpty()) {
                URLParser refererParser = new URLParser(referer, Rewriter.getServletPath(referer));
                if (refererParser.getProxyBasePath() != null && !refererParser.getProxyBasePath().isEmpty()) {
                    newProxyBase = refererParser.getProxyBasePath();
                }
            }
            // ... otherwise use the last used proxy (since it probably
            // is a
            // redirection we might have success with this)
            if (newProxyBase == null) {
                newProxyBase = (String) request.getSession().getAttribute("lastProxy");
            }

            // Now redirect the client to the new url
            if (newProxyBase != null) {
                url = newProxyBase + (url != null && !url.isEmpty() ? '/' + url : "/");
                response.sendRedirect(servletPath + url);

            } else {
                response.sendError(404);
            }
            return;

        }
        url = url.replace("\\|", "|");

        ProcessResult result = null;
        try {
            result = servlet.loadFromProxy(request, response, url, servletPath, parser.getProxyBasePath());

        } catch (UnknownHostException e) {
            // If we get a unknown host exception, we try it with the
            // referer
            String referer = request.getHeader("Referer");
            if (parser.getRefererRelative() != null && referer != null && !referer.isEmpty()) {
                URLParser refererParser = new URLParser(referer, Rewriter.getServletPath(referer));
                if (refererParser.getProxyBasePath() != null && !refererParser.getProxyBasePath().isEmpty()) {
                    String newUrl = refererParser.getProxyBasePath() + parser.getRefererRelative();
                    try {
                        result = servlet.loadFromProxy(request, response, newUrl, servletPath,
                                refererParser.getProxyBasePath());
                    } catch (UnknownHostException e1) {
                        result = null;
                        response.sendError(404);
                    }
                } else {
                    result = null;
                    response.sendError(404);
                }
            } else {
                result = null;
                response.sendError(404);
            }

        }

        if (result != null) {
            // If an error is returned, we don't need to process the
            // inputstream
            InputStream input;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            OutputStream output = outputStream;
            if (result.isGzipped()) {
                output = new GZIPOutputStream(outputStream, 100000);
            }
            String s = URLRewriterServer.process(result.getContent(), fullUrl);
            s = URLRewriterServer.removeTopHref(s);
            if (request.getSession().getAttribute(Constants.miceManaged) == null
                    || !request.getSession().getAttribute(Constants.miceManaged).equals("true")) {
                s = s.replace("<head>",
                        "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">");
                // Pattern p = Pattern.compile("<body.*?>");
                // Matcher m = p.matcher(s);
                // StringBuffer sb = new StringBuffer();
                // while (m.find()) {
                // m.appendReplacement(
                // sb,
                // m.group()
                // + "<link href=\""
                // + servletPath
                // +
                // "miceproxy/navigation.css\" rel=\"stylesheet\" type=\"text/css\"/><div id=\"miceNavigation\"><input id=\"miceUrlBox\" type=\"text\" value=\""
                // + parser.getFullProxyPath()
                // +
                // "\"/></div><div id=\"contentWrapper\">");
                // }
                // s = m.appendTail(sb).toString();
                // s = s.replace("</body>",
                // "</div></body>");
            }

            // The page shall only be injected if it is a
            // html page and if it really has html content
            // (prevent e.g. blank.html to be injected)
            if (result.getContentType() != null && result.getContentType().contains("text/html")
                    && (s.contains("body") || s.contains("BODY")))
                s += "<script type=\"text/javascript\" language=\"javascript\" src=\"" + servletPath
                        + "miceproxy/miceproxy.nocache.js\"></script>";
            IOUtils.write(s, output, result.getCharset());
            output.flush();
            if (output instanceof GZIPOutputStream)
                ((GZIPOutputStream) output).finish();
            outputStream.writeTo(response.getOutputStream());
        }

    }
}

From source file:oscar.oscarLab.ca.all.parsers.OLISHL7Handler.java

@SuppressWarnings("unused")
public void processEncapsulatedData(HttpServletRequest request, HttpServletResponse response, int obr,
        int obx) {
    getOBXField(obr, obx, 5, 0, 2);//  w  w  w.j  av  a2s .co m
    String subtype = getOBXField(obr, obx, 5, 0, 3);
    String data = getOBXEDField(obr, obx, 5, 0, 5);
    try {
        if (subtype.equals("PDF")) {
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + getAccessionNum().replaceAll("\\s", "_") + "_" + obr + "-" + obx + "_Document.pdf\"");
        } else if (subtype.equals("JPEG")) {
            response.setContentType("image/jpeg");
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + getAccessionNum().replaceAll("\\s", "_") + "_" + obr + "-" + obx + "_Image.jpg\"");
        } else if (subtype.equals("GIF")) {
            response.setContentType("image/gif");
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + getAccessionNum().replaceAll("\\s", "_") + "_" + obr + "-" + obx + "_Image.gif\"");
        } else if (subtype.equals("RTF")) {
            response.setContentType("application/gif");
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + getAccessionNum().replaceAll("\\s", "_") + "_" + obr + "-" + obx + "_Document.rtf\"");
        } else if (subtype.equals("HTML")) {
            response.setContentType("text/html");
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + getAccessionNum().replaceAll("\\s", "_") + "_" + obr + "-" + obx + "_Document.html\"");
        } else if (subtype.equals("RTF")) {
            response.setContentType("text/plain");
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + getAccessionNum().replaceAll("\\s", "_") + "_" + obr + "-" + obx + "_Document.xml\"");
        }

        byte[] buf = Base64.decode(data);
        /*
        int pos = 0;
        int read;
        while (pos < buf.length) {
           read = buf.length - pos > 1024 ? 1024 : buf.length - pos;
           response.getOutputStream().write(buf, pos, read);
           pos += read;
        }
        */
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(buf, 0, buf.length);
        baos.writeTo(response.getOutputStream());

    } catch (IOException e) {
        MiscUtils.getLogger().error("OLIS HL7 Error", e);
    }
}

From source file:org.apache.poi.hpsf.Section.java

/**
 * Writes this section into an output stream.<p>
 *
 * Internally this is done by writing into three byte array output
 * streams: one for the properties, one for the property list and one for
 * the section as such. The two former are appended to the latter when they
 * have received all their data./*  w w  w  .  j  av  a2  s.  com*/
 *
 * @param out The stream to write into.
 *
 * @return The number of bytes written, i.e. the section's size.
 * @exception IOException if an I/O error occurs
 * @exception WritingNotSupportedException if HPSF does not yet support
 * writing a property's variant type.
 */
public int write(final OutputStream out) throws WritingNotSupportedException, IOException {
    /* Check whether we have already generated the bytes making out the
     * section. */
    if (sectionBytes.size() > 0) {
        sectionBytes.writeTo(out);
        return sectionBytes.size();
    }

    /* Writing the section's dictionary it tricky. If there is a dictionary
     * (property 0) the codepage property (property 1) must be set, too. */
    int codepage = getCodepage();
    if (codepage == -1) {
        String msg = "The codepage property is not set although a dictionary is present. "
                + "Defaulting to ISO-8859-1.";
        LOG.log(POILogger.WARN, msg);
        codepage = Property.DEFAULT_CODEPAGE;
    }

    /* The properties are written to this stream. */
    final ByteArrayOutputStream propertyStream = new ByteArrayOutputStream();

    /* The property list is established here. After each property that has
     * been written to "propertyStream", a property list entry is written to
     * "propertyListStream". */
    final ByteArrayOutputStream propertyListStream = new ByteArrayOutputStream();

    /* Maintain the current position in the list. */
    int position = 0;

    /* Increase the position variable by the size of the property list so
     * that it points behind the property list and to the beginning of the
     * properties themselves. */
    position += 2 * LittleEndianConsts.INT_SIZE + getPropertyCount() * 2 * LittleEndianConsts.INT_SIZE;

    /* Write the properties and the property list into their respective
     * streams: */
    for (Property p : properties.values()) {
        final long id = p.getID();

        /* Write the property list entry. */
        LittleEndian.putUInt(id, propertyListStream);
        LittleEndian.putUInt(position, propertyListStream);

        /* If the property ID is not equal 0 we write the property and all
         * is fine. However, if it equals 0 we have to write the section's
         * dictionary which has an implicit type only and an explicit
         * value. */
        if (id != 0) {
            /* Write the property and update the position to the next
             * property. */
            position += p.write(propertyStream, codepage);
        } else {
            if (codepage == -1) {
                throw new IllegalPropertySetDataException("Codepage (property 1) is undefined.");
            }
            position += writeDictionary(propertyStream, codepage);
        }
    }

    /* Write the section: */
    int streamLength = LittleEndianConsts.INT_SIZE * 2 + propertyListStream.size() + propertyStream.size();

    /* Write the section's length: */
    LittleEndian.putInt(streamLength, out);

    /* Write the section's number of properties: */
    LittleEndian.putInt(getPropertyCount(), out);

    /* Write the property list: */
    propertyListStream.writeTo(out);

    /* Write the properties: */
    propertyStream.writeTo(out);

    return streamLength;
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphServlet.java

private void writePDFContent(HttpServletRequest request, HttpServletResponse response, JFreeChart charts[],
        Statistic[] stats, long starttime, long endtime, int width, int height) throws IOException {

    try {/* w  w  w .  ja  v  a  2  s.  co  m*/
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setPageEvent(new PDFEventListener(request));
        document.open();

        int index = 0;
        int chapIndex = 0;
        for (Statistic stat : stats) {

            String serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
            String dateName = JiveGlobals.formatDate(new Date(starttime)) + " - "
                    + JiveGlobals.formatDate(new Date(endtime));
            Paragraph paragraph = new Paragraph(serverName,
                    FontFactory.getFont(FontFactory.HELVETICA, 18, Font.BOLD));
            document.add(paragraph);
            paragraph = new Paragraph(dateName, FontFactory.getFont(FontFactory.HELVETICA, 14, Font.PLAIN));
            document.add(paragraph);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);

            Paragraph chapterTitle = new Paragraph(++chapIndex + ". " + stat.getName(),
                    FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD));

            document.add(chapterTitle);
            // total hack: no idea what tags people are going to use in the description
            // possibly recommend that we only use a <p> tag?
            String[] paragraphs = stat.getDescription().split("<p>");
            for (String s : paragraphs) {
                Paragraph p = new Paragraph(s);
                document.add(p);
            }
            document.add(Chunk.NEWLINE);

            PdfContentByte contentByte = writer.getDirectContent();
            PdfTemplate template = contentByte.createTemplate(width, height);
            Graphics2D graphs2D = template.createGraphics(width, height, new DefaultFontMapper());
            Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
            charts[index++].draw(graphs2D, rectangle2D);
            graphs2D.dispose();
            float x = (document.getPageSize().width() / 2) - (width / 2);
            contentByte.addTemplate(template, x, writer.getVerticalPosition(true) - height);
            document.newPage();
        }

        document.close();

        // setting some response headers
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength is needed for MSIE!!!
        response.setContentLength(baos.size());
        // write ByteArrayOutputStream to the ServletOutputStream
        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();
    } catch (DocumentException e) {
        Log.error("error creating PDF document: " + e.getMessage());

    }
}

From source file:org.kuali.ole.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Creates a PDF document based on the PO information and the items that were selected by the user on the Purchase Order
 * Retransmit Document page to be retransmitted, then display the PDF to the browser.
 *
 * @param mapping  An ActionMapping//w w w .  j  a v a2 s.  c  o  m
 * @param form     An ActionForm
 * @param request  The HttpServletRequest
 * @param response The HttpServletResponse
 * @return An ActionForward
 * @throws Exception
 */
public ActionForward printingRetransmitPoOnly(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    String selectedItemIndexes = request.getParameter("selectedItemIndexes");
    String documentNumber = request.getParameter("poDocumentNumberForRetransmit");
    PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class)
            .getPurchaseOrderByDocumentNumber(documentNumber);
    String retransmitHeader = request.getParameter("retransmitHeader");

    // setting the isItemSelectedForRetransmitIndicator items of the PO obtained from the database based on its value from
    // the po from the form

    setItemSelectedForRetransmitIndicatorFromPOInForm(selectedItemIndexes, po.getItems());
    po.setRetransmitHeader(retransmitHeader);
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        // below method will throw ValidationException if errors are found
        SpringContext.getBean(PurchaseOrderService.class).retransmitPurchaseOrderPDF(po, baosPDF);

        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        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();

    } catch (ValidationException e) {
        LOG.warn("Caught ValidationException while trying to retransmit PO with doc id "
                + po.getDocumentNumber());
        return mapping.findForward(OLEConstants.MAPPING_ERROR);
    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:org.kuali.ext.mm.document.web.struts.CountWorksheetPrintAction.java

private void combineAndFlushReportPDFFiles(List<File> fileList, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    long startTime = System.currentTimeMillis();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ArrayList master = new ArrayList();
    int pageOffset = 0;
    int f = 0;//ww w.  j av  a  2  s . co  m
    PdfCopy writer = null;
    com.lowagie.text.Document document = null;
    for (File file : fileList) {
        // we create a reader for a certain document
        String reportName = file.getAbsolutePath();
        PdfReader reader = new PdfReader(reportName);
        reader.consolidateNamedDestinations();
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            if (pageOffset != 0) {
                SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
            }
            master.addAll(bookmarks);
        }
        pageOffset += n;

        if (f == 0) {
            // step 1: creation of a document-object
            document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            writer = new PdfCopy(document, baos);
            // step 3: we open the document
            document.open();
        }
        // step 4: we add content
        PdfImportedPage page;
        for (int i = 0; i < n;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        writer.freeReader(reader);
        f++;
    }

    if (!master.isEmpty())
        writer.setOutlines(master);
    // step 5: we close the document
    document.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(MMUtil.getFileName());

    String contentDisposition = sbContentDispValue.toString();

    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 = response.getOutputStream();
    baos.writeTo(sos);
    sos.flush();
    baos.close();
    sos.close();
    long endTime = System.currentTimeMillis();
    loggerAc.debug("Time taken for report Parameter settings in action " + (endTime - startTime));
}

From source file:com.yahoo.glimmer.indexing.preprocessor.ResourceRecordWriterTest.java

@Test
public void writeSubjectAndObjectTest() throws IOException, InterruptedException, ClassNotFoundException {
    ByteArrayOutputStream bySubjectBos = new ByteArrayOutputStream(1024);
    FSDataOutputStream bySubjectOs = new FSDataOutputStream(bySubjectBos, null);
    ByteArrayOutputStream bySubjectOffsetsBos = new ByteArrayOutputStream(1024);
    FSDataOutputStream bySubjectOffsetsOs = new FSDataOutputStream(bySubjectOffsetsBos, null);

    e.one(fs).create(e.with(new Path(tempDirPath, "bySubject.bz2")), e.with(false));
    e.will(Expectations.returnValue(bySubjectOs));
    e.one(fs).create(e.with(new Path(tempDirPath, "bySubject.blockOffsets")), e.with(false));
    e.will(Expectations.returnValue(bySubjectOffsetsOs));

    e.one(allOs).write(e.with(new ByteMatcher("http://a/key1\nhttp://a/key2\nhttp://a/key3\n", true)),
            e.with(0), e.with(42));//from ww  w  .  jav  a  2s  .c o  m
    e.one(contextOs).write(e.with(new ByteMatcher("http://a/key\n", true)), e.with(0), e.with(13));
    e.one(objectOs).write(e.with(new ByteMatcher("http://a/key\nbNode123\n", true)), e.with(0), e.with(22));
    e.one(predicateOs).write(e.with(new ByteMatcher("3\thttp://a/key\n", true)), e.with(0), e.with(15));
    e.one(subjectOs).write(e.with(new ByteMatcher("http://a/key\n", true)), e.with(0), e.with(13));

    context.checking(e);

    ResourceRecordWriter writer = new ResourceRecordWriter(fs, tempDirPath, null);

    OutputCount outputCount = new OutputCount();
    outputCount.output = OUTPUT.PREDICATE;
    outputCount.count = 3;
    writer.write(new Text("http://a/key"), outputCount);
    outputCount.output = OUTPUT.OBJECT;
    outputCount.count = 0;
    writer.write(new Text("http://a/key"), outputCount);
    outputCount.output = OUTPUT.CONTEXT;
    outputCount.count = 0;
    writer.write(new Text("http://a/key"), outputCount);
    outputCount.output = OUTPUT.ALL;
    outputCount.count = 0;
    writer.write(new Text("http://a/key1"), outputCount);
    writer.write(new Text("http://a/key2"), outputCount);
    writer.write(new Text("http://a/key3"), outputCount);
    BySubjectRecord record = new BySubjectRecord();
    record.setId(66);
    record.setPreviousId(55);
    record.setSubject("http://a/key");
    record.addRelation("<http://predicate/> <http://Object> .");
    writer.write(new Text("http://a/key"), record);
    outputCount.output = OUTPUT.OBJECT;
    outputCount.count = 0;
    writer.write(new Text("bNode123"), outputCount);
    writer.close(null);

    context.assertIsSatisfied();

    BlockCompressedDocumentCollection collection = new BlockCompressedDocumentCollection("foo", null, 10);
    InputStream blockOffsetsInputStream = new ByteArrayInputStream(bySubjectOffsetsBos.toByteArray());

    File bySubjectTempFile = File.createTempFile(ResourceRecordWriterTest.class.getSimpleName(), "tmp");
    FileOutputStream tempFileOutputStream = new FileOutputStream(bySubjectTempFile);
    bySubjectBos.writeTo(tempFileOutputStream);
    tempFileOutputStream.flush();
    tempFileOutputStream.close();

    FileInputStream bySubjectFileInputStream = new FileInputStream(bySubjectTempFile);
    collection.init(bySubjectFileInputStream.getChannel(), blockOffsetsInputStream, 100000);
    blockOffsetsInputStream.close();

    // Size of collection. This is the same as the number of lines written to ALL.
    assertEquals(3l, collection.size());

    InputStream documentInputStream = collection.stream(65l);
    assertEquals(-1, documentInputStream.read());
    documentInputStream = collection.stream(67l);
    assertEquals(-1, documentInputStream.read());
    documentInputStream = collection.stream(66l);
    assertNotNull(documentInputStream);

    collection.close();
    bySubjectFileInputStream.close();
}

From source file:org.kuali.kfs.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Creates a PDF document based on the PO information and the items that were selected by the user on the Purchase Order
 * Retransmit Document page to be retransmitted, then display the PDF to the browser.
 *
 * @param mapping An ActionMapping/*from  w  w  w  .  ja  v  a  2 s  . c o m*/
 * @param form An ActionForm
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @throws Exception
 * @return An ActionForward
 */
public ActionForward printingRetransmitPoOnly(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    String selectedItemIndexes = request.getParameter("selectedItemIndexes");
    String documentNumber = request.getParameter("poDocumentNumberForRetransmit");
    PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class)
            .getPurchaseOrderByDocumentNumber(documentNumber);
    String retransmitHeader = request.getParameter("retransmitHeader");

    // setting the isItemSelectedForRetransmitIndicator items of the PO obtained from the database based on its value from
    // the po from the form

    setItemSelectedForRetransmitIndicatorFromPOInForm(selectedItemIndexes, po.getItems());
    po.setRetransmitHeader(retransmitHeader);
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        // below method will throw ValidationException if errors are found
        SpringContext.getBean(PurchaseOrderService.class).retransmitPurchaseOrderPDF(po, baosPDF);

        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        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();

    } catch (ValidationException e) {
        LOG.warn("Caught ValidationException while trying to retransmit PO with doc id "
                + po.getDocumentNumber());
        return mapping.findForward(KFSConstants.MAPPING_ERROR);
    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:org.kuali.kfs.module.purap.document.web.struts.PurchaseOrderAction.java

/**
 * Prints the PDF only, as opposed to <code>firstTransmitPrintPo</code>, which calls this method (indirectly) to print the PDF,
 * and calls the doc handler to display the PO tabbed page.
 *
 * @param mapping An ActionMapping/*  w ww  .  ja  va 2  s  .c o  m*/
 * @param form An ActionForm
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @throws Exception
 * @return An ActionForward
 */
public ActionForward printPurchaseOrderPDFOnly(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    String poDocId = request.getParameter("docId");
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        // will throw validation exception if errors occur
        SpringContext.getBean(PurchaseOrderService.class).performPrintPurchaseOrderPDFOnly(poDocId, 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_PO_");
        sbFilename.append(poDocId);
        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;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    } finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}

From source file:Servlet3.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from w w w . ja v  a  2  s .com
        System.out.println("inside servlet");
        String a = request.getParameter("countryf");
        String c = request.getParameter("submit");
        String b = request.getParameter("paramf");

        String CurentUID = request.getParameter("UIDvalue2f");
        String URLRequest = request.getRequestURL().append('?').append(request.getQueryString()).toString();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat format1 = new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy");
        String date1 = cal.getTime().toString();

        System.out.println("inside servlet");

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con = DriverManager.getConnection("jdbc:odbc:server");

        // To Insert data to UserActivity table for Recent Activities Tab
        Statement sthistoryinsert3 = con.createStatement();
        String insertstring = "Insert into UserActivity values('" + CurentUID + "','" + date1
                + "','Future Data Forecast','" + a + "','" + b + "','" + URLRequest + "')";
        sthistoryinsert3.executeUpdate(insertstring);
        sthistoryinsert3.close();
        System.out.println("\n Step 1");
        Statement st = con.createStatement();
        XYSeriesCollection dataset = new XYSeriesCollection();
        XYSeries series = new XYSeries(b);

        String query = "SELECT [2000],[2012] FROM country where CountryName='" + a + "' AND SeriesName='" + b
                + "'";
        System.out.println(query);
        ResultSet rs = st.executeQuery(query);
        if (rs == null)
            System.out.println("\n no rows ");
        else
            System.out.println("Rows present ");
        rs.next();

        Double start = Double.parseDouble(rs.getString(1));
        Double end = Double.parseDouble(rs.getString(2));
        Double period = 13.0;
        Double growth = Math.pow((end / start), (1 / period)) - 1;
        System.out.println("growth percentage =" + growth);
        rs.close();
        String query2 = "select [2011],[2012] from country where CountryName='" + a + "' AND SeriesName='" + b
                + "'";
        rs = st.executeQuery(query2);
        rs.next();
        series.add(2011, Double.parseDouble(rs.getString(1)));
        Double second = Double.parseDouble(rs.getString(2));
        series.add(2012, second);

        Double growthvalue = second + (second * growth);

        series.add(2013, growthvalue);
        for (int i = 2014; i <= 2016; i++) {
            System.out.println("actual growth value = " + growthvalue);
            series.add((i++), (growthvalue + growthvalue * growth));
            growthvalue = growthvalue + growthvalue * growth;
        }
        rs.close();
        dataset.addSeries(series);
        DecimalFormat format_2Places = new DecimalFormat("0.00");
        growth = growth * 100;
        growth = Double.valueOf(format_2Places.format(growth));
        JFreeChart chart = ChartFactory.createXYLineChart(
                "Energy forecasting for " + a + " based on " + b + " with growth value estimated at " + growth
                        + "% ",
                "Year", "Energy consumed in millions", dataset, PlotOrientation.VERTICAL, true, true, false);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        chart.setBackgroundPaint(Color.white);
        final XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(Color.white);
        plot.setDomainGridlinesVisible(true);
        plot.setRangeGridlinesVisible(true);
        plot.setDomainGridlinePaint(Color.black);
        plot.setRangeGridlinePaint(Color.black);

        final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesLinesVisible(2, false);
        renderer.setSeriesShapesVisible(2, false);
        plot.setRenderer(renderer);
        // To insert colored Pie Chart into the PDF file using
        // iText now   
        if (c.equals("View Graph in Browser")) {
            ChartUtilities.writeChartAsPNG(bos, chart, 700, 500);
            response.setContentType("image/png");
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(bos.toByteArray());
            out.flush();
            out.close();
        }

        else {
            int width = 640; /* Width of our chart */
            int height = 480; /* Height of our chart */
            Document PieChart = new Document(new com.itextpdf.text.Rectangle(width, height));
            java.util.Date date = new java.util.Date();
            String chartname = "My_Colored_Chart" + date.getTime() + ".pdf";
            PdfWriter writer = PdfWriter.getInstance(PieChart, new FileOutputStream(chartname));
            PieChart.open();

            PieChart.addTitle("Pie-Chart");
            PieChart.addAuthor("MUurugappan");

            PdfContentByte Add_Chart_Content = writer.getDirectContent();
            PdfTemplate template_Chart_Holder = Add_Chart_Content.createTemplate(width, height);
            Graphics2D Graphics_Chart = template_Chart_Holder.createGraphics(width, height,
                    new DefaultFontMapper());
            Rectangle2D Chart_Region = new Rectangle2D.Double(0, 0, 540, 380);
            chart.draw(Graphics_Chart, Chart_Region);
            Graphics_Chart.dispose();
            Add_Chart_Content.addTemplate(template_Chart_Holder, 0, 0);
            PieChart.close();

            PdfReader reader = new PdfReader(chartname);
            PdfStamper stamper = null;
            try {
                stamper = new PdfStamper(reader, bos);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            try {
                stamper.close();
            } catch (DocumentException e) {

                e.printStackTrace();
            }

            // set response headers to view PDF
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setContentType("application/pdf");
            response.setContentLength(bos.size());

            OutputStream os = response.getOutputStream();
            bos.writeTo(os);
            os.flush();
            os.close();
        }
    }

    catch (Exception i) {
        i.printStackTrace();
    }

}