Example usage for java.io ByteArrayOutputStream size

List of usage examples for java.io ByteArrayOutputStream size

Introduction

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

Prototype

public synchronized int size() 

Source Link

Document

Returns the current size of the buffer.

Usage

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;/*from   w w  w.  ja  va2s  .c  o  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:org.dbgl.gui.MainWindow.java

private void doExportTemplates() {
    try {/*from   ww w. jav a2s  . c o m*/
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bos);

        java.util.List<ExpTemplate> expTemplateList = new ArrayList<ExpTemplate>();
        for (Template template : templatesList) {
            Conf conf = new Conf(template, DosboxVersion.findById(dbversionsList, template.getDbversionId()),
                    ps);
            expTemplateList.add(new ExpTemplate(-1, conf, template));
        }
        DOMSource doc = new DOMSource(XmlUtils.getFullTemplatesXML(expTemplateList, dbversionsList,
                "DBGL default templates", StringUtils.EMPTY, "rcblanke"));
        XmlUtils.saveDomSource(doc, FileUtils.getDefaultTemplatesXmlFile(), null);

        if (bos.size() > 0) {
            GeneralPurposeDialogs.warningMessage(shell, bos.toString());
            bos.reset();
        }
    } catch (Exception e) {
        GeneralPurposeDialogs.fatalMessage(shell, e.toString(), e);
    }
}

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/*  ww  w  . j a  va  2  s  .  co 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 w w .  jav 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 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   ww  w.  j a v  a  2s.co m
        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();
    }

}

From source file:org.dbgl.gui.EditProfileDialog.java

protected void doPerformDosboxConfAction(DosboxConfAction action) {
    try {/*from w  ww.  j  a  v  a 2  s  . c  o  m*/
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bos);
        updateAllConfigurationsBySettings();

        Conf newDosboxVersion = null;
        if (action == DosboxConfAction.RELOAD_TEMPLATE) {
            newDosboxVersion = new Conf(templatesList.get(template.getSelectionIndex()),
                    dbversionsList.get(dbversion.getSelectionIndex()), ps);
        } else {
            newDosboxVersion = new Conf(dbversionsList.get(dbversion.getSelectionIndex()), ps);
        }

        if (isMultiEdit()) {
            for (Configurable c : multiProfileList) {
                if (c.getConf().hasDifferentBaseMountsThan(newDosboxVersion)) {
                    ps.println(Settings.getInstance().msg("dialog.multiprofile.notice.basemountsconflicting"));
                    break;
                }
            }
        }

        for (Configurable c : multiProfileList) {
            doPerformdosboxConfAction(action, newDosboxVersion, c);
        }

        if (isMultiEdit()) {
            doPerformdosboxConfAction(action, newDosboxVersion, multiProfileCombined);
            enableSettingsByConfiguration(multiProfileCombined.getConf().getDosboxSettings());
            selectSettingsByConfiguration(multiProfileCombined.getConf());
        } else {
            if (action == DosboxConfAction.RELOAD_TEMPLATE) {
                if (multiProfileList.get(0).getNativeCommandsList().size() == 1) {
                    multiProfileList.get(0).setNativeCommandsList(dbase.readNativeCommandsList(-1,
                            templatesList.get(template.getSelectionIndex()).getId()));
                    updateNativeCommands(-1);
                }
            }
            enableSettingsByConfiguration(multiProfileList.get(0).getConf().getDosboxSettings());
            selectSettingsByConfiguration(multiProfileList.get(0).getConf());
        }

        if (bos.size() > 0) {
            GeneralPurposeDialogs.warningMessage(getParent(), bos.toString());
            bos.reset();
        }
    } catch (IOException | SQLException e) {
        GeneralPurposeDialogs.warningMessage(getParent(), e);
    }
}

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

/**
 * Print the list of PO Quote requests./*from w  w w .  j av  a  2s  . co  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   w  ww. j  a v  a 2s. c om
 * @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.dbgl.gui.MainWindow.java

private void doImportDefaultTemplates(final boolean interactive) {
    if (!interactive || GeneralPurposeDialogs.confirmMessage(shell,
            settings.msg("dialog.importdefaulttemplates.confirm.start"))) {
        try {/*from  www. ja  v  a 2s.c  o m*/
            if (checkDefaultDBVersion() == null) {
                return;
            }

            File defaultXml = FileUtils.getDefaultTemplatesXmlFile();
            if (!FileUtils.isExistingFile(defaultXml))
                throw new IOException(settings.msg("general.error.openfile", new Object[] { defaultXml }));

            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(defaultXml);

            XPath xPath = XPathFactory.newInstance().newXPath();
            String packageVersion = xPath.evaluate("/document/export/format-version", doc);
            String packageTitle = xPath.evaluate("/document/export/title", doc);
            String packageAuthor = xPath.evaluate("/document/export/author", doc);
            String packageNotes = xPath.evaluate("/document/export/notes", doc);
            String creationApp = xPath.evaluate("/document/export/generator-title", doc);
            String creationAppVersion = xPath.evaluate("/document/export/generator-version", doc);
            Date creationDate = XmlUtils.datetimeFormatter
                    .parse(xPath.evaluate("/document/export/creationdatetime", doc));

            System.out
                    .println(settings.msg("dialog.import.importing",
                            new Object[] { StringUtils.join(
                                    new String[] { packageTitle, packageVersion, packageAuthor, packageNotes,
                                            creationApp, creationAppVersion, creationDate.toString() },
                                    ' ') }));

            NodeList templateNodes = (NodeList) xPath.evaluate("/document/template", doc,
                    XPathConstants.NODESET);

            java.util.List<ExpTemplate> templates = new ArrayList<ExpTemplate>();
            SortedSet<DosboxVersion> dbSet = new TreeSet<DosboxVersion>();
            for (int i = 0; i < templateNodes.getLength(); i++) {
                Element templateNode = (Element) templateNodes.item(i);
                Element dosbox = XmlUtils.getNode(templateNode, "dosbox");
                DosboxVersion d = new DosboxVersion(i, XmlUtils.getTextValue(dosbox, "title"), "", "", true,
                        false, false, "", XmlUtils.getTextValue(dosbox, "version"), null, null, null, 0);
                dbSet.add(d);
                templates.add(new ExpTemplate(templateNode, ImportDialog.getDosboxVersionId(d, dbSet)));
            }

            java.util.List<Integer> dbmapping = new ArrayList<Integer>();
            for (DosboxVersion dbversion : dbSet) {
                dbmapping.add(dbversion.findBestMatchId(dbversionsList));
            }

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(bos);

            Template addedTemplate = null;
            for (ExpTemplate template : templates) {
                template.setDbversionId(
                        ImportDialog.getMappedDosboxVersionId(dbSet, dbmapping, template.getDbversionId()));

                DosboxVersion assocDBVersion = DosboxVersion.findById(dbversionsList,
                        template.getDbversionId());

                addedTemplate = dbase.addOrEditTemplate(template.getTitle(), template.getDbversionId(),
                        template.isDefault(), -1);
                Conf gameConf = new Conf(template.getImportedFullConfig(), template.getImportedIncrConfig(),
                        false, FileUtils.getDefaultTemplatesXmlFile().getPath(), addedTemplate.getId(),
                        assocDBVersion, ps);
                gameConf.save();
            }
            updateTemplateList(addedTemplate);

            if (bos.size() > 0) {
                GeneralPurposeDialogs.warningMessage(shell, bos.toString());
                bos.reset();
            } else {
                if (interactive)
                    GeneralPurposeDialogs.infoMessage(shell, settings.msg("dialog.import.notice.importok"));
            }

        } catch (XPathExpressionException | SAXException e) {
            GeneralPurposeDialogs.fatalMessage(shell,
                    settings.msg("dialog.importdefaulttemplates.error.defaultxmlinvalidformat",
                            new Object[] { e.toString() }),
                    e);
        } catch (Exception e) {
            GeneralPurposeDialogs.fatalMessage(shell, e.toString(), e);
        }
    }
}

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

/**
 * Print the list of PO Quote requests.//from  www  .  j  ava 2  s. c  om
 *
 * @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;
}