Example usage for com.lowagie.text Document open

List of usage examples for com.lowagie.text Document open

Introduction

In this page you can find the example usage for com.lowagie.text Document open.

Prototype

boolean open

To view the source code for com.lowagie.text Document open.

Click Source Link

Document

Is the document open or not?

Usage

From source file:ispyb.client.mx.collection.PdfRtfExporter.java

License:Open Source License

/**
 * export datacollection report/*ww  w .j av a  2 s . c  o m*/
 * 
 * @param rtfFormat
 * @return
 * @throws Exception
 */
public ByteArrayOutputStream exportNewDataCollectionReport(boolean rtfFormat) throws Exception {
    // create simple doc and write to a ByteArrayOutputStream
    Document document = new Document(PageSize.A4.rotate(), 20, 20, 20, 20);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if (!rtfFormat) {
        PdfWriter.getInstance(document, baos);
    } else {
        RtfWriter2.getInstance(document, baos);
    }

    // =============================
    // Header + footer
    // =============================

    setHeader(document);
    setFooter(document);
    document.open();

    // ===============================
    // Body
    // ===============================
    // Crystallographer added only for IFX proposal in case of MXPress
    // experiment
    setCrystallographer(document);
    // Session comments
    setSessionComments(document);
    // session title& info
    setSessionTable(document);

    // ======================
    // Data Collection table
    // ======================
    document.add(new Paragraph(" "));
    setDataCollectionTable2(document);

    // ======================
    // Energy scans
    // ======================
    document.add(new Paragraph(" "));
    setEnergyScansTable(document);

    // ======================
    // XRF Spectra
    // ======================
    document.add(new Paragraph(" "));
    setXfrSpectraTable(document);

    // ======================
    // Summary
    // ======================
    setSummary(document);

    // ======================
    // End of file
    // ======================
    document.close();
    return baos;

}

From source file:ispyb.client.mx.results.ExportAutoProcAction.java

License:Open Source License

public ByteArrayOutputStream exportAutoProc(boolean exportAsPDF) throws Exception {
    // create simple doc and write to a ByteArrayOutputStream
    Document document = new Document(PageSize.A4);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if (exportAsPDF) {
        PdfWriter.getInstance(document, baos);
    } else {// www  .jav  a  2s . c  o m
        RtfWriter2.getInstance(document, baos);
    }

    // =============================
    // Header + footer
    // =============================

    setHeader(document);
    setFooter(document);
    document.open();

    // ===============================
    // Body
    // ===============================
    // dataCollection info
    setDataCollectionInfo(document);
    document.add(new Paragraph(" "));
    // Session comments
    setAutoProcInfo(document);

    // ======================
    // End of file
    // ======================
    document.close();
    return baos;

}

From source file:ispyb.common.util.export.ExiPdfRtfExporter.java

License:Open Source License

/**
 * export datacollection report//from  w  w  w  .  j a va2  s .co  m
 * 
 * @param rtfFormat
 * @return
 * @throws Exception
 */
public ByteArrayOutputStream exportDataCollectionReport(boolean rtfFormat) throws Exception {

    this.init();
    // create simple doc and write to a ByteArrayOutputStream
    Document document = new Document(PageSize.A4.rotate(), 20, 20, 20, 20);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if (!rtfFormat) {
        PdfWriter.getInstance(document, baos);
    } else {
        RtfWriter2.getInstance(document, baos);
    }

    // =============================
    // Header + footer
    // =============================

    setHeader(document);
    setFooter(document);
    document.open();

    // ===============================
    // Body
    // ===============================
    // Crystallographer added only for IFX proposal in case of MXPress
    // experiment
    setCrystallographer(document);
    // Session comments
    setSessionComments(document);
    // session title& info
    setSessionTable(document);

    // ======================
    // Data Collection table
    // ======================
    document.add(new Paragraph(" "));
    setDataCollectionTable(document);

    // ======================
    // End of file
    // ======================
    document.close();
    return baos;

}

From source file:ispyb.common.util.export.PdfExporterSample.java

License:Open Source License

/**
 * Exports the file for viewSample for shipment
 * //from  ww  w.j  a v  a2s  .  c  o  m
 * @return
 * @throws Exception
 */
public ByteArrayOutputStream exportAsPdf() throws Exception {

    // create simple doc and write to a ByteArrayOutputStream
    Document document = new Document(PageSize.A4.rotate(), 20, 20, 20, 20);
    document.addTitle("exportSamplesView");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);
    HeaderFooter header;

    // header + footer
    if (viewName != null)
        header = new HeaderFooter(new Phrase("Samples for Proposal: " + proposalDesc + "  ---  " + viewName),
                false);

    else
        header = new HeaderFooter(new Phrase("Samples for Proposal: " + proposalDesc), false);

    header.setAlignment(Element.ALIGN_CENTER);
    header.setBorderWidth(1);
    header.getBefore().getFont().setSize(8);
    HeaderFooter footer = new HeaderFooter(new Phrase("Page n."), true);
    footer.setAlignment(Element.ALIGN_RIGHT);
    footer.setBorderWidth(1);
    footer.getBefore().getFont().setSize(6);

    document.setHeader(header);
    document.setFooter(footer);

    document.open();

    if (aList.isEmpty()) {
        document.add(new Paragraph("There is no samples in this report"));
        document.close();
        return baos;
    }
    // Create first table for samples

    int NumColumns = 19;
    PdfPTable table = new PdfPTable(NumColumns);
    int headerwidths[] = { 6, 6, 6, 6, 6, 4, 6, 4, 4, 4, 4, 4, 4, 8, 5, 5, 5, 10, 6 }; // percentage
    table.setWidths(headerwidths);

    table.setWidthPercentage(100); // percentage
    table.getDefaultCell().setPadding(3);
    table.getDefaultCell().setBorderWidth(1);
    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

    // header
    PdfPCell cell = new PdfPCell();
    table.addCell(new Paragraph("Protein", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Sample name", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Smp code", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Dewar", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Container", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Loc. in cont.", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Space group", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Cell a", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Cell b", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Cell c", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Cell alpha", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Cell beta", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Cell gamma", new Font(Font.HELVETICA, 8)));

    cell = new PdfPCell(new Paragraph("Crystal comments", new Font(Font.HELVETICA, 8)));
    table.addCell(cell);

    table.addCell(new Paragraph("Already observed resol.", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Required resol.", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Min. resol.", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Sample comments", new Font(Font.HELVETICA, 8)));
    table.addCell(new Paragraph("Sample status", new Font(Font.HELVETICA, 8)));

    table.setHeaderRows(1); // this is the end of the table header

    table.getDefaultCell().setBorderWidth(1);
    DecimalFormat df1 = new DecimalFormat("#####0.0");
    DecimalFormat df2 = new DecimalFormat("#####0.00");

    Iterator it = aList.iterator();
    int i = 1;
    String currentContainer = "next";
    String nextContainer = "next";

    while (it.hasNext()) {
        table.getDefaultCell().setGrayFill(0.99f);
        if (i % 2 == 1) {
            table.getDefaultCell().setGrayFill(0.9f);
        }
        BLSample3VO samplefv = (BLSample3VO) it.next();
        LOG.debug("table of datacollections pdf " + samplefv.getBlSampleId());

        if (samplefv.getContainerVO() != null && samplefv.getContainerVO().getCode() != null)
            nextContainer = samplefv.getContainerVO().getCode();
        else
            nextContainer = "next";

        // in the case of view sorted by dewar/container, we add a page break afetr each container
        if (sortView.equals("2") && !currentContainer.equals(nextContainer)) {
            document.add(table);
            table.deleteBodyRows();
            document.newPage();
        }

        if (samplefv.getCrystalVO().getProteinVO().getAcronym() != null)
            table.addCell(new Paragraph(samplefv.getCrystalVO().getProteinVO().getAcronym(),
                    new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getName() != null)
            table.addCell(new Paragraph(samplefv.getName(), new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getCode() != null)
            table.addCell(new Paragraph(samplefv.getCode(), new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getContainerVO() != null && samplefv.getContainerVO().getDewarVO() != null
                && samplefv.getContainerVO().getDewarVO().getCode() != null)
            table.addCell(new Paragraph(samplefv.getContainerVO().getDewarVO().getCode(),
                    new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getContainerVO() != null && samplefv.getContainerVO().getCode() != null) {
            currentContainer = samplefv.getContainerVO().getCode();
            table.addCell(new Paragraph(currentContainer, new Font(Font.HELVETICA, 8)));
        } else {
            currentContainer = "current";
            table.addCell("");
        }

        if (samplefv.getLocation() != null)
            table.addCell(new Paragraph(samplefv.getLocation(), new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getCrystalVO().getSpaceGroup() != null)
            table.addCell(new Paragraph(samplefv.getCrystalVO().getSpaceGroup(), new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getCrystalVO().getCellA() != null)
            table.addCell(
                    new Paragraph(df1.format(samplefv.getCrystalVO().getCellA()), new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getCrystalVO().getCellB() != null)
            table.addCell(
                    new Paragraph(df1.format(samplefv.getCrystalVO().getCellB()), new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getCrystalVO().getCellC() != null)
            table.addCell(
                    new Paragraph(df1.format(samplefv.getCrystalVO().getCellC()), new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getCrystalVO().getCellAlpha() != null)
            table.addCell(new Paragraph(df1.format(samplefv.getCrystalVO().getCellAlpha()),
                    new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getCrystalVO().getCellBeta() != null)
            table.addCell(new Paragraph(df1.format(samplefv.getCrystalVO().getCellBeta()),
                    new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getCrystalVO().getCellGamma() != null)
            table.addCell(new Paragraph(df1.format(samplefv.getCrystalVO().getCellGamma()),
                    new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getCrystalVO().getComments() != null)
            table.addCell(new Paragraph(samplefv.getCrystalVO().getComments(), new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getDiffractionPlanVO() != null
                && samplefv.getDiffractionPlanVO().getObservedResolution() != null) {
            table.addCell(new Paragraph(df2.format(samplefv.getDiffractionPlanVO().getObservedResolution()),
                    new Font(Font.HELVETICA, 8)));
        } else if (samplefv.getCrystalVO().getDiffractionPlanVO() != null
                && samplefv.getCrystalVO().getDiffractionPlanVO().getObservedResolution() != null)
            table.addCell(new Paragraph(
                    df2.format(samplefv.getCrystalVO().getDiffractionPlanVO().getObservedResolution()),
                    new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getDiffractionPlanVO() != null
                && samplefv.getDiffractionPlanVO().getRequiredResolution() != null) {
            table.addCell(new Paragraph(df2.format(samplefv.getDiffractionPlanVO().getRequiredResolution()),
                    new Font(Font.HELVETICA, 8)));
        } else if (samplefv.getCrystalVO().getDiffractionPlanVO() != null
                && samplefv.getCrystalVO().getDiffractionPlanVO().getRequiredResolution() != null)
            table.addCell(new Paragraph(
                    df2.format(samplefv.getCrystalVO().getDiffractionPlanVO().getRequiredResolution()),
                    new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getDiffractionPlanVO() != null
                && samplefv.getDiffractionPlanVO().getMinimalResolution() != null) {
            table.addCell(new Paragraph(df2.format(samplefv.getDiffractionPlanVO().getMinimalResolution()),
                    new Font(Font.HELVETICA, 8)));
        } else if (samplefv.getCrystalVO().getDiffractionPlanVO() != null
                && samplefv.getCrystalVO().getDiffractionPlanVO().getMinimalResolution() != null)
            table.addCell(new Paragraph(
                    df2.format(samplefv.getCrystalVO().getDiffractionPlanVO().getMinimalResolution()),
                    new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getComments() != null && samplefv.getComments() != "")
            table.addCell(new Paragraph(samplefv.getComments(), new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (samplefv.getBlSampleStatus() != null)
            table.addCell(new Paragraph(samplefv.getBlSampleStatus(), new Font(Font.HELVETICA, 8)));
        else
            table.addCell("");

        if (i % 2 == 1) {
            table.getDefaultCell().setGrayFill(0.0f);
        }

        i++;
    }

    document.add(table);

    document.close();

    return baos;
}

From source file:it.eng.spagobi.engines.chart.Utilities.ExportCharts.java

License:Mozilla Public License

public static void transformSVGIntoPDF(InputStream inputStream, OutputStream outputStream)
        throws IOException, DocumentException {
    FileOutputStream imageFileOutputStream = null;
    File imageFile = null;//w ww . ja  v  a2  s.  co  m
    try {
        imageFile = File.createTempFile("chart", ".jpg");
        imageFileOutputStream = new FileOutputStream(imageFile);
        transformSVGIntoPNG(inputStream, imageFileOutputStream);

        Document pdfDocument = new Document(PageSize.A4.rotate());
        PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, outputStream);
        pdfDocument.open();
        Image jpg = Image.getInstance(imageFile.getPath());
        fitImage(jpg);

        pdfDocument.add(jpg);
        pdfDocument.close();
        docWriter.close();
    } finally {
        if (imageFileOutputStream != null) {
            try {
                imageFileOutputStream.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
        if (imageFile.exists()) {
            imageFile.delete();
        }
    }
}

From source file:it.eng.spagobi.engines.documentcomposition.exporterUtils.PdfCreator.java

License:Mozilla Public License

public FileOutputStream createPdfFile(FileOutputStream fileOutputStream,
        Map<String, DocumentContainer> documentsMap, boolean defaultStyle)
        throws MalformedURLException, IOException, DocumentException {

    logger.debug("IN");

    Document document = new Document(PageSize.A4.rotate());
    Rectangle rect = document.getPageSize();
    docWidth = rect.getWidth();//from  w  w  w .j a  va2s. c  om
    docHeight = rect.getHeight();

    logger.debug("document size width: " + docWidth + " height: " + docHeight);

    //PdfWriter writer=PdfWriter.getInstance(document,new FileOutputStream("C:/comp/SpagoBIProva.pdf"));
    PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
    document.open();

    int documentsNumber = documentsMap.keySet().size();
    int columnnsNumber = 2;

    if (defaultStyle == true) {
        logger.debug("use default style");
        int cellsCounter = 0;

        PdfPTable table = new PdfPTable(columnnsNumber);
        table.setWidthPercentage(100);

        for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) {
            String label = (String) iterator.next();
            DocumentContainer docContainer = documentsMap.get(label);
            byte[] content = docContainer.getContent();
            if (content != null) {
                Image img = null;
                try {
                    img = Image.getInstance(content);
                    table.addCell(img);
                } catch (Exception e) {
                    logger.debug("Trying to evaluate response as a PDF file... ");
                    table.addCell("");
                    //                  try {
                    //                     PdfReader reader = new PdfReader(content);
                    //                     PdfImportedPage page = writer.getImportedPage(reader, 1);
                    //                     writer.addPage(page);
                    //                     table.addCell("");
                    //                  } catch (Exception x) {
                    //                     logger.error("Error in inserting image for document " + label, e);
                    //                     logger.error("Error in inserting pdf file for document " + label, x);
                    //                     table.addCell("");
                    //                  }
                }
            }
            cellsCounter++;
        }

        // if cell counter is not pair make it pair
        if (cellsCounter % 2 != 0) {
            table.addCell("");
        }
        document.add(table);

    } else { // ************* NO DEFAULT STYLE *****************
        logger.debug("No default style");

        // I want to calculate total height of scaled heights!!
        //int totalScaledHeight=calculateTotaleScaledHeights(documentsMap, defaultStyle);

        // run on all documents
        for (Iterator iterator = documentsMap.keySet().iterator(); iterator.hasNext();) {
            String label = (String) iterator.next();
            logger.debug("document with label " + label);

            DocumentContainer docContainer = documentsMap.get(label);
            MetadataStyle style = docContainer.getStyle();

            // one table for each image, set at absolute position
            PdfPTable table = new PdfPTable(1);

            // width and height specified for the container by style attribute
            int widthStyle = style.getWidth();
            int heightStyle = style.getHeight();
            logger.debug("style for document width: " + widthStyle + " height: " + heightStyle);

            // width and height for the table scaled to the document size
            int tableWidth = calculatePxSize(docWidth, widthStyle, videoWidth);
            int tableHeight = calculatePxSize(docHeight, heightStyle, videoHeight);

            logger.debug("table for document width: " + tableWidth + " height: " + tableHeight);

            // x and y position as specified for the container by the style attribute
            int yStyle = style.getY();
            int xStyle = style.getX();
            // width and height scaled to the document size
            int xPos = (calculatePxPos(docWidth, xStyle, videoWidth));
            int yPos = (int) docHeight - (calculatePxPos(docHeight, yStyle, videoHeight));
            logger.debug("Table position at x: " + xPos + " y: " + yPos);

            // get the image
            byte[] content = docContainer.getContent();
            if (content != null) {
                Image img = null;
                try {
                    img = Image.getInstance(content);
                } catch (Exception e) {
                    logger.debug("Trying to evaluate response as a PDF file... ");
                    try {
                        PdfReader reader = new PdfReader(content);
                        PdfContentByte cb = writer.getDirectContent();
                        PdfImportedPage page = writer.getImportedPage(reader, 1);
                        float[] tm = getTransformationMatrix(page, xPos, yPos, tableWidth, tableHeight);
                        cb.addTemplate(page, tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]);
                    } catch (Exception x) {
                        logger.error("Error in inserting image for document " + label, e);
                        logger.error("Error in inserting pdf file for document " + label, x);
                    }
                    continue;
                }

                //if it is a REPORT and has more than one page, too large, you have to resize the image, but how to understand it?
                // if image size is more than double of the container size cut the first part,otherwise scale it
                if (docContainer.getDocumentType().equals("REPORT")) {
                    boolean cutImageWIdth = isToCutWidth(img, tableWidth);
                    boolean cutImageHeight = isToCutHeight(img, tableWidth);

                    if (cutImageWIdth == true || cutImageHeight == true) {
                        logger.debug(
                                "Report will be cut to width " + tableWidth + " and height " + tableHeight);
                        try {
                            img = cutImage(content, cutImageHeight, cutImageWIdth, tableHeight, tableWidth,
                                    (int) img.getWidth(), (int) img.getHeight());
                        } catch (Exception e) {
                            logger.error(
                                    "Error in image cut, cutt will be ignored and image will be drawn anyway ",
                                    e);
                        }
                    }
                }

                // this is percentage to resize
                // The image must be size within the cell               
                int percToResize = percentageToResize((int) img.getWidth(), (int) img.getHeight(), tableWidth,
                        tableHeight);
                logger.debug("image will be scaled of percentage " + percToResize);
                img.scalePercent(percToResize);

                PdfPCell cell = new PdfPCell(img);
                cell.setNoWrap(true);
                cell.setFixedHeight(tableHeight);
                cell.setBorderWidth(0);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setVerticalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);

                //table.setWidthPercentage(tableWidthPerc);
                table.setTotalWidth(tableWidth);
                table.setLockedWidth(true);
            } else {
                // TODO: setALT!
            }
            logger.debug("Add table");
            table.writeSelectedRows(0, -1, xPos, yPos, writer.getDirectContent());
            logger.debug("Document added");
        }

    }
    document.close();
    logger.debug("OUT");
    return fileOutputStream;
}

From source file:it.eng.spagobi.engines.exporters.ChartExporter.java

License:Mozilla Public License

public File getChartPDF(String uuid, boolean multichart, String orientation) throws Exception {
    logger.debug("IN");

    File tmpFile;//w  w w .j a  va 2  s  . c om

    try {
        tmpFile = null;
        String dir = System.getProperty("java.io.tmpdir");
        String path = (new StringBuilder(String.valueOf(dir))).append("/").append(uuid).append(".png")
                .toString();
        File dirF = new File(dir);
        tmpFile = File.createTempFile("tempPDFExport", ".pdf", dirF);
        Document pdfDocument = new Document();
        PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(tmpFile));
        //pdfDocument.open();
        if (multichart) {
            pdfDocument.open();

            List images = new ArrayList();
            for (int i = 0; i < MAX_NUM_IMG; i++) {
                String imgName = (new StringBuilder(String.valueOf(path.substring(0, path.indexOf(".png")))))
                        .append(i).append(".png").toString();
                Image png = Image.getInstance(imgName);
                if (png == null) {
                    break;
                }
                images.add(png);
            }

            Table table = new Table(images.size());
            for (int i = 0; i < images.size(); i++) {
                Image png = (Image) images.get(i);
                if (HORIZONTAL_ORIENTATION.equalsIgnoreCase(orientation)) {
                    Cell pngCell = new Cell(png);
                    pngCell.setBorder(0);
                    table.setBorder(0);
                    table.addCell(pngCell);
                } else {
                    png.setAlignment(5);
                    pdfDocument.add(png);
                }
            }

            pdfDocument.add(table);
        } else {
            Image jpg = Image.getInstance(path);
            float height = jpg.getHeight();
            float width = jpg.getWidth();

            // if in need to change layout
            if (width > MAX_WIDTH || height > MAX_HEIGHT) {
                changeLayout(pdfDocument, jpg, width, height);
            }

            pdfDocument.open();
            pdfDocument.add(jpg);
        }
        pdfDocument.close();
        docWriter.close();

        logger.debug("OUT");

        return tmpFile;

    } catch (Throwable e) {
        logger.error("An exception has occured", e);
        throw new Exception(e);
    } finally {

        //tmpFile.delete();

    }
}

From source file:it.eng.spagobi.engines.geo.service.DrawMapAction.java

License:Mozilla Public License

public void service(SourceBean serviceRequest, SourceBean serviceResponse) {

    String outputFormat = null;//from  ww  w .j a va 2s . c o  m
    String executionId = null;
    File maptmpfile = null;
    boolean inlineResponse;
    String responseFileName;
    Monitor totalTimeMonitor = null;
    Monitor totalTimePerFormatMonitor = null;
    Monitor flushingResponseTotalTimeMonitor = null;
    Monitor errorHitsMonitor = null;

    logger.debug("IN");

    try {
        super.service(serviceRequest, serviceResponse);

        totalTimeMonitor = MonitorFactory.start("GeoEngine.drawMapAction.totalTime");

        executionId = getAttributeAsString("SBI_EXECUTION_ID");

        outputFormat = getAttributeAsString(OUTPUT_FORMAT);
        logger.debug("Parameter [" + OUTPUT_FORMAT + "] is equal to [" + outputFormat + "]");

        inlineResponse = getAttributeAsBoolean(INLINE_RESPONSE, true);
        logger.debug("Parameter [" + INLINE_RESPONSE + "] is equal to [" + inlineResponse + "]");

        if (getAuditServiceProxy() != null)
            getAuditServiceProxy().notifyServiceStartEvent();

        if (outputFormat == null) {
            logger.info("Parameter [" + outputFormat + "] not specified into request");
            outputFormat = (String) getGeoEngineInstance().getEnv().get(GeoEngineConstants.ENV_OUTPUT_TYPE);
            logger.debug("Env Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] is equal to ["
                    + outputFormat + "]");
        }

        if (outputFormat == null) {
            logger.info(
                    "Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] not specified into environment");
            outputFormat = DEFAULT_OUTPUT_TYPE;
        }

        totalTimePerFormatMonitor = MonitorFactory
                .start("GeoEngine.drawMapAction." + outputFormat + "totalTime");

        try {
            if (outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)) {
                maptmpfile = getGeoEngineInstance().renderMap(GeoEngineConstants.JPEG);

            } else {
                maptmpfile = getGeoEngineInstance().renderMap(outputFormat);
            }
        } catch (Throwable t) {
            throw new DrawMapServiceException(getActionName(), "Impossible to render map", t);
        }

        responseFileName = "map.svg";

        IStreamEncoder encoder = null;
        File tmpFile = null;
        if (outputFormat.equalsIgnoreCase(GeoEngineConstants.JPEG)) {
            encoder = new SVGMapConverter();
            responseFileName = "map.jpeg";
        } else if (outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)) {

            encoder = new SVGMapConverter();
            BufferedInputStream bis = null;

            String dirS = System.getProperty("java.io.tmpdir");
            File imageFile = null;
            bis = new BufferedInputStream(new FileInputStream(maptmpfile));
            try {
                int contentLength = 0;
                int b = -1;
                String contentFileName = "tempJPEGExport";
                freezeHttpResponse();

                File dir = new File(dirS);
                imageFile = File.createTempFile("tempJPEGExport", ".jpeg", dir);
                FileOutputStream stream = new FileOutputStream(imageFile);

                encoder.encode(bis, stream);

                stream.flush();
                stream.close();

                File dirF = new File(dirS);
                tmpFile = File.createTempFile("tempPDFExport", ".pdf", dirF);
                Document pdfDocument = new Document();
                PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(tmpFile));
                pdfDocument.open();
                Image jpg = Image.getInstance(imageFile.getPath());
                jpg.setRotation(new Double(Math.PI / 2).floatValue());
                jpg.scaleAbsolute(770, 520);
                pdfDocument.add(jpg);
                pdfDocument.close();
                docWriter.close();
                maptmpfile = tmpFile;

            } finally {
                bis.close();
                if (imageFile != null)
                    imageFile.delete();
            }

            responseFileName = "map.pdf";
            encoder = null;

        }

        try {
            flushingResponseTotalTimeMonitor = MonitorFactory
                    .start("GeoEngine.drawMapAction.flushResponse.totalTime");
            writeBackToClient(maptmpfile, encoder, inlineResponse, responseFileName,
                    getContentType(outputFormat));

        } catch (IOException e) {
            logger.error("error while flushing output", e);
            if (getAuditServiceProxy() != null)
                getAuditServiceProxy().notifyServiceErrorEvent("Error while flushing output");
            throw new DrawMapServiceException(getActionName(), "Error while flushing output", e);
        }

        if (getAuditServiceProxy() != null)
            getAuditServiceProxy().notifyServiceEndEvent();

        maptmpfile.delete();
        if (tmpFile != null)
            tmpFile.delete();

    } catch (Throwable t) {
        errorHitsMonitor = MonitorFactory.start("GeoEngine.errorHits");
        errorHitsMonitor.stop();
        DrawMapServiceException wrappedException;
        if (t instanceof DrawMapServiceException) {
            wrappedException = (DrawMapServiceException) t;
        } else {
            wrappedException = new DrawMapServiceException(getActionName(),
                    "An unpredicted error occurred while executing " + getActionName() + " service", t);
        }

        wrappedException.setDescription(wrappedException.getRootCause());
        Throwable rootException = wrappedException.getRootException();
        if (rootException instanceof SpagoBIEngineRuntimeException) {
            wrappedException.setHints(((SpagoBIEngineRuntimeException) rootException).getHints());
        }

        throw wrappedException;
    } finally {
        if (flushingResponseTotalTimeMonitor != null)
            flushingResponseTotalTimeMonitor.stop();
        if (totalTimePerFormatMonitor != null)
            totalTimePerFormatMonitor.stop();
        if (totalTimeMonitor != null)
            totalTimeMonitor.stop();

    }

    logger.debug("OUT");
}

From source file:it.eng.spagobi.engines.geo.service.initializer.ExecutionProxyGeoEngineStartAction.java

License:Mozilla Public License

public void service(SourceBean serviceRequest, SourceBean serviceResponse) throws GeoEngineException {

    GeoEngineInstance geoEngineInstance;
    Map env;/*w  w  w .  ja v a 2  s . com*/
    byte[] analysisStateRowData;
    GeoEngineAnalysisState analysisState = null;
    String executionContext;
    String executionId;
    String documentLabel;
    String outputType;

    Monitor hitsPrimary = null;
    Monitor hitsByDate = null;
    Monitor hitsByUserId = null;
    Monitor hitsByDocumentId = null;
    Monitor hitsByExecutionContext = null;

    logger.debug("IN");

    try {
        setEngineName(ENGINE_NAME);
        super.service(serviceRequest, serviceResponse);

        //if(true) throw new SpagoBIEngineStartupException(getEngineName(), "Test exception");

        logger.debug("User Id: " + getUserId());
        logger.debug("Audit Id: " + getAuditId());
        logger.debug("Document Id: " + getDocumentId());
        logger.debug("Template: " + getTemplateAsSourceBean());

        hitsPrimary = MonitorFactory.startPrimary("GeoEngine.requestHits");
        hitsByDate = MonitorFactory.start(
                "GeoEngine.requestHits." + DateFormat.getDateInstance(DateFormat.SHORT).format(new Date()));
        hitsByUserId = MonitorFactory.start("GeoEngine.requestHits." + getUserId());
        hitsByDocumentId = MonitorFactory.start("GeoEngine.requestHits." + getDocumentId());

        executionContext = getAttributeAsString(EXECUTION_CONTEXT);
        logger.debug("Parameter [" + EXECUTION_CONTEXT + "] is equal to [" + executionContext + "]");

        executionId = getAttributeAsString(EXECUTION_ID);
        logger.debug("Parameter [" + EXECUTION_ID + "] is equal to [" + executionId + "]");

        documentLabel = getAttributeAsString(DOCUMENT_LABEL);
        logger.debug("Parameter [" + DOCUMENT_LABEL + "] is equal to [" + documentLabel + "]");

        outputType = getAttributeAsString(OUTPUT_TYPE);
        logger.debug("Parameter [" + OUTPUT_TYPE + "] is equal to [" + outputType + "]");

        logger.debug("Execution context: " + executionContext);
        String isDocumentCompositionModeActive = (executionContext != null
                && executionContext.equalsIgnoreCase("DOCUMENT_COMPOSITION")) ? "TRUE" : "FALSE";
        logger.debug("Document composition mode active: " + isDocumentCompositionModeActive);

        hitsByExecutionContext = MonitorFactory.start("GeoEngine.requestHits."
                + (isDocumentCompositionModeActive.equalsIgnoreCase("TRUE") ? "compositeDocument"
                        : "singleDocument"));

        env = getEnv("TRUE".equalsIgnoreCase(isDocumentCompositionModeActive), documentLabel, executionId);
        if (outputType != null) {
            env.put(GeoEngineConstants.ENV_OUTPUT_TYPE, outputType);
        }

        geoEngineInstance = GeoEngine.createInstance(getTemplateAsSourceBean(), env);
        geoEngineInstance.setAnalysisMetadata(getAnalysisMetadata());

        analysisStateRowData = getAnalysisStateRowData();
        if (analysisStateRowData != null) {
            logger.debug("AnalysisStateRowData: " + new String(analysisStateRowData));
            analysisState = new GeoEngineAnalysisState();
            analysisState.load(analysisStateRowData);
            logger.debug("AnalysisState: " + analysisState.toString());
        } else {
            logger.debug("AnalysisStateRowData: NULL");
        }
        if (analysisState != null) {
            geoEngineInstance.setAnalysisState(analysisState);
        }

        String selectedMeasureName = getAttributeAsString("default_kpi");
        logger.debug("Parameter [" + "default_kpi" + "] is equal to [" + selectedMeasureName + "]");

        if (!StringUtilities.isEmpty(selectedMeasureName)) {
            geoEngineInstance.getMapRenderer().setSelectedMeasureName(selectedMeasureName);
        }

        if ("TRUE".equalsIgnoreCase(isDocumentCompositionModeActive)) {
            setAttribute(DynamicPublisher.PUBLISHER_NAME, "SIMPLE_UI_PUBLISHER");
        } else {
            setAttribute(DynamicPublisher.PUBLISHER_NAME, "AJAX_UI_PUBLISHER");
        }

        String id = getAttributeAsString("SBI_EXECUTION_ID");
        setAttributeInSession(GEO_ENGINE_INSTANCE, geoEngineInstance);
    } catch (Exception e) {
        SpagoBIEngineStartupException serviceException = null;

        if (e instanceof SpagoBIEngineStartupException) {
            serviceException = (SpagoBIEngineStartupException) e;
        } else {
            Throwable rootException = e;
            while (rootException.getCause() != null) {
                rootException = rootException.getCause();
            }
            String str = rootException.getMessage() != null ? rootException.getMessage()
                    : rootException.getClass().getName();
            String message = "An unpredicted error occurred while executing " + getEngineName() + " service."
                    + "\nThe root cause of the error is: " + str;

            serviceException = new SpagoBIEngineStartupException(getEngineName(), message, e);
        }

        throw serviceException;
    } finally {
        if (hitsByExecutionContext != null)
            hitsByExecutionContext.stop();
        if (hitsByDocumentId != null)
            hitsByDocumentId.stop();
        if (hitsByUserId != null)
            hitsByUserId.stop();
        if (hitsByDate != null)
            hitsByDate.stop();
        if (hitsPrimary != null)
            hitsPrimary.stop();

    }

    // Put draw Map Action

    String outputFormat = null;
    File maptmpfile = null;
    boolean inlineResponse;
    String responseFileName;
    Monitor totalTimeMonitor = null;
    Monitor totalTimePerFormatMonitor = null;
    Monitor flushingResponseTotalTimeMonitor = null;
    Monitor errorHitsMonitor = null;

    logger.debug("IN");

    try {
        super.service(serviceRequest, serviceResponse);

        totalTimeMonitor = MonitorFactory.start("GeoEngine.drawMapAction.totalTime");

        //executionId = getAttributeAsString( "SBI_EXECUTION_ID" );

        outputFormat = getAttributeAsString(OUTPUT_FORMAT);
        logger.debug("Parameter [" + OUTPUT_FORMAT + "] is equal to [" + outputFormat + "]");

        inlineResponse = getAttributeAsBoolean(INLINE_RESPONSE, true);
        logger.debug("Parameter [" + INLINE_RESPONSE + "] is equal to [" + inlineResponse + "]");

        if (getAuditServiceProxy() != null)
            getAuditServiceProxy().notifyServiceStartEvent();

        IEngineInstance iEngInst = (IEngineInstance) getAttributeFromSession(EngineConstants.ENGINE_INSTANCE);
        GeoEngineInstance geoInstance = (GeoEngineInstance) iEngInst;

        if (outputFormat == null) {
            logger.info("Parameter [" + outputFormat + "] not specified into request");

            //outputFormat = (String)((GeoEngineInstance)).getEnv().get(GeoEngineConstants.ENV_OUTPUT_TYPE);
            outputFormat = (String) geoInstance.getEnv().get(GeoEngineConstants.ENV_OUTPUT_TYPE);
            logger.debug("Env Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] is equal to ["
                    + outputFormat + "]");
        }

        if (outputFormat == null) {
            logger.info(
                    "Parameter [" + GeoEngineConstants.ENV_OUTPUT_TYPE + "] not specified into environment");
            outputFormat = DEFAULT_OUTPUT_TYPE;
        }

        totalTimePerFormatMonitor = MonitorFactory
                .start("GeoEngine.drawMapAction." + outputFormat + "totalTime");

        try {
            if (outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)) {
                maptmpfile = geoInstance.renderMap(GeoEngineConstants.JPEG);

            } else {
                maptmpfile = geoInstance.renderMap(outputFormat);
            }
        } catch (Throwable t) {
            throw new DrawMapServiceException(getActionName(), "Impossible to render map", t);
        }

        responseFileName = "map.svg";

        IStreamEncoder encoder = null;
        File tmpFile = null;
        if (outputFormat.equalsIgnoreCase(GeoEngineConstants.JPEG)) {
            encoder = new SVGMapConverter();
            responseFileName = "map.jpeg";
        } else if (outputFormat.equalsIgnoreCase(GeoEngineConstants.PDF)) {

            encoder = new SVGMapConverter();
            BufferedInputStream bis = null;

            String dirS = System.getProperty("java.io.tmpdir");
            File imageFile = null;
            bis = new BufferedInputStream(new FileInputStream(maptmpfile));
            try {
                int contentLength = 0;
                int b = -1;
                String contentFileName = "tempJPEGExport";
                freezeHttpResponse();

                File dir = new File(dirS);
                imageFile = File.createTempFile("tempJPEGExport", ".jpeg", dir);
                FileOutputStream stream = new FileOutputStream(imageFile);

                encoder.encode(bis, stream);

                stream.flush();
                stream.close();

                File dirF = new File(dirS);
                tmpFile = File.createTempFile("tempPDFExport", ".pdf", dirF);
                Document pdfDocument = new Document();
                PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(tmpFile));
                pdfDocument.open();
                Image jpg = Image.getInstance(imageFile.getPath());
                jpg.setRotation(new Double(Math.PI / 2).floatValue());
                jpg.scaleAbsolute(770, 520);
                pdfDocument.add(jpg);
                pdfDocument.close();
                docWriter.close();
                maptmpfile = tmpFile;

            } finally {
                bis.close();
                if (imageFile != null)
                    imageFile.delete();
            }

            responseFileName = "map.pdf";
            encoder = null;

        }

        try {
            flushingResponseTotalTimeMonitor = MonitorFactory
                    .start("GeoEngine.drawMapAction.flushResponse.totalTime");
            writeBackToClient(maptmpfile, encoder, inlineResponse, responseFileName,
                    getContentType(outputFormat));

        } catch (IOException e) {
            logger.error("error while flushing output", e);
            if (getAuditServiceProxy() != null)
                getAuditServiceProxy().notifyServiceErrorEvent("Error while flushing output");
            throw new DrawMapServiceException(getActionName(), "Error while flushing output", e);
        }

        if (getAuditServiceProxy() != null)
            getAuditServiceProxy().notifyServiceEndEvent();

        maptmpfile.delete();
        if (tmpFile != null)
            tmpFile.delete();

    } catch (Throwable t) {
        errorHitsMonitor = MonitorFactory.start("GeoEngine.errorHits");
        errorHitsMonitor.stop();
        DrawMapServiceException wrappedException;
        if (t instanceof DrawMapServiceException) {
            wrappedException = (DrawMapServiceException) t;
        } else {
            wrappedException = new DrawMapServiceException(getActionName(),
                    "An unpredicted error occurred while executing " + getActionName() + " service", t);
        }

        wrappedException.setDescription(wrappedException.getRootCause());
        Throwable rootException = wrappedException.getRootException();
        if (rootException instanceof SpagoBIEngineRuntimeException) {
            wrappedException.setHints(((SpagoBIEngineRuntimeException) rootException).getHints());
        }

        throw wrappedException;
    } finally {
        if (flushingResponseTotalTimeMonitor != null)
            flushingResponseTotalTimeMonitor.stop();
        if (totalTimePerFormatMonitor != null)
            totalTimePerFormatMonitor.stop();
        if (totalTimeMonitor != null)
            totalTimeMonitor.stop();

    }

    logger.debug("OUT");

    logger.debug("OUT");
}

From source file:it.eng.spagobi.engines.worksheet.services.export.ExportChartAction.java

License:Mozilla Public License

private void transformSVGIntoPDF(InputStream inputStream, OutputStream outputStream)
        throws IOException, DocumentException {
    FileOutputStream imageFileOutputStream = null;
    File imageFile = null;//  w  w  w.  j ava2s  . c o m
    try {
        imageFile = File.createTempFile("chart", ".jpg");
        imageFileOutputStream = new FileOutputStream(imageFile);
        transformSVGIntoPNG(inputStream, imageFileOutputStream);

        Document pdfDocument = new Document(PageSize.A4.rotate());
        PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, outputStream);
        pdfDocument.open();
        Image jpg = Image.getInstance(imageFile.getPath());
        fitImage(jpg);

        pdfDocument.add(jpg);
        pdfDocument.close();
        docWriter.close();
    } finally {
        if (imageFileOutputStream != null) {
            try {
                imageFileOutputStream.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
        if (imageFile.exists()) {
            imageFile.delete();
        }
    }
}