Example usage for com.lowagie.text.pdf PdfWriter close

List of usage examples for com.lowagie.text.pdf PdfWriter close

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfWriter close.

Prototype

public void close() 

Source Link

Document

Signals that the Document was closed and that no other Elements will be added.

Usage

From source file:fr.univlorraine.mondossierweb.controllers.CalendrierController.java

License:Apache License

/**
 * //from w ww.ja v  a 2 s.  c om
 * @return le fichier pdf du calendrier des examens.
 */
public com.vaadin.server.Resource exportPdf() {

    String nomFichier = applicationContext.getMessage("pdf.calendrier.title", null, Locale.getDefault()) + " "
            + MainUI.getCurrent().getEtudiant().getNom().replace('.', ' ').replace(' ', '_') + ".pdf";

    nomFichier = nomFichier.replaceAll(" ", "_");

    StreamResource.StreamSource source = new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
                PdfWriter docWriter = null;
                Document document = configureDocument(MARGE_PDF);
                docWriter = PdfWriter.getInstance(document, baosPDF);
                docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                docWriter.setStrictImageSequence(true);
                creerPdfCalendrier(document, MainUI.getCurrent().getEtudiant());
                docWriter.close();
                baosPDF.close();
                //Creation de l'export
                byte[] bytes = baosPDF.toByteArray();
                return new ByteArrayInputStream(bytes);
            } catch (DocumentException e) {
                LOG.error("Erreur  la gnration du calendrier des examens : DocumentException ", e);
                return null;
            } catch (IOException e) {
                LOG.error("Erreur  la gnration du calendrier des examens : IOException ", e);
                return null;
            }

        }
    };

    // Cration de la ressource 
    StreamResource resource = new StreamResource(source, nomFichier);
    resource.setMIMEType("application/force-download;charset=UTF-8");
    resource.setCacheTime(0);
    return resource;

}

From source file:fr.univlorraine.mondossierweb.controllers.InscriptionController.java

License:Apache License

/**
 * //from w  w  w . j  a v a2s  .co  m
 * @return le fichier pdf.
 */
public com.vaadin.server.Resource exportPdf(Inscription inscription) {

    // verifie les autorisations
    if (!etudiantController.proposerCertificat(inscription, MainUI.getCurrent().getEtudiant())) {
        return null;
    }

    String nomFichier = applicationContext.getMessage("pdf.certificat.title", null, Locale.getDefault()) + "_"
            + inscription.getCod_etp() + "_" + inscription.getCod_anu().replace('/', '-') + "_"
            + MainUI.getCurrent().getEtudiant().getNom().replace('.', ' ').replace(' ', '_') + ".pdf";
    nomFichier = nomFichier.replaceAll(" ", "_");

    StreamResource.StreamSource source = new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
                PdfWriter docWriter = null;
                Document document = configureDocument();
                docWriter = PdfWriter.getInstance(document, baosPDF);
                docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                docWriter.setStrictImageSequence(true);
                creerPdfCertificatScolarite(document, MainUI.getCurrent().getEtudiant(), inscription);
                docWriter.close();
                baosPDF.close();
                //Creation de l'export
                byte[] bytes = baosPDF.toByteArray();
                return new ByteArrayInputStream(bytes);
            } catch (DocumentException e) {
                LOG.error("Erreur  la gnration du certificat : DocumentException ", e);
                return null;
            } catch (IOException e) {
                LOG.error("Erreur  la gnration du certificat : IOException ", e);
                return null;
            }

        }
    };

    // Cration de la ressource 
    StreamResource resource = new StreamResource(source, nomFichier);
    resource.setMIMEType("application/force-download;charset=UTF-8");
    resource.setCacheTime(0);
    return resource;
}

From source file:fr.univlorraine.mondossierweb.controllers.ListeInscritsController.java

License:Apache License

/**
 * Retourne le trombinoscope en pdf//from  w w w  . ja  v  a 2s  .c  o  m
 * @param linscrits
 * @param listecodind
 * @return
 */
public InputStream getPdfStream(List<Inscrit> linscrits, List<String> listecodind, String libObj,
        String annee) {

    LOG.debug("generation pdf : " + libObj + " " + annee + " " + linscrits.size() + " " + listecodind.size());
    try {
        ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
        PdfWriter docWriter = null;
        Document document = configureDocument(MARGE_PDF);
        docWriter = PdfWriter.getInstance(document, baosPDF);
        docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
        docWriter.setStrictImageSequence(true);
        creerPdfTrombinoscope(document, linscrits, listecodind, libObj, annee);
        docWriter.close();
        baosPDF.close();
        //Creation de l'export
        byte[] bytes = baosPDF.toByteArray();
        return new ByteArrayInputStream(bytes);
    } catch (DocumentException e) {
        LOG.error("Erreur  la gnration du trombinoscope : DocumentException ", e);
        return null;
    } catch (IOException e) {
        LOG.error("Erreur  la gnration du trombinoscope : IOException ", e);
        return null;
    }

}

From source file:fr.univlorraine.mondossierweb.controllers.NoteController.java

License:Apache License

/**
 * /*from   w  ww .ja v a  2  s.c om*/
 * @return le fichier pdf du rsum des notes.
 */
public com.vaadin.server.Resource exportPdfResume() {

    String nomFichier = applicationContext.getMessage("pdf.notes.title", null, Locale.getDefault()) + " "
            + MainUI.getCurrent().getEtudiant().getNom().replace('.', ' ').replace(' ', '_') + ".pdf";
    nomFichier = nomFichier.replaceAll(" ", "_");

    StreamResource.StreamSource source = new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
                PdfWriter docWriter = null;
                Document document = configureDocument(MARGE_PDF);
                docWriter = PdfWriter.getInstance(document, baosPDF);
                docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                docWriter.setStrictImageSequence(true);
                if (configController.isInsertionFiligranePdfNotes()) {
                    docWriter.setPageEvent(new Watermark());
                }
                creerPdfResume(document, MainUI.getCurrent().getEtudiant());
                docWriter.close();
                baosPDF.close();
                //Creation de l'export
                byte[] bytes = baosPDF.toByteArray();
                return new ByteArrayInputStream(bytes);
            } catch (DocumentException e) {
                LOG.error("Erreur  la gnration du rsum des notes : DocumentException ", e);
                return null;
            } catch (IOException e) {
                LOG.error("Erreur  la gnration du rsum des notes : IOException ", e);
                return null;
            }

        }
    };

    // Cration de la ressource 
    StreamResource resource = new StreamResource(source, nomFichier);
    resource.setMIMEType("application/force-download;charset=UTF-8");
    resource.setCacheTime(0);
    return resource;
}

From source file:fr.univlorraine.mondossierweb.controllers.NoteController.java

License:Apache License

/**
 * /*ww w.j ava 2s . c o m*/
 * @return le fichier pdf du detail des notes.
 */
public com.vaadin.server.Resource exportPdfDetail(Etape etape) {

    String nomFichier = applicationContext.getMessage("pdf.detail.title", null, Locale.getDefault()) + " "
            + MainUI.getCurrent().getEtudiant().getNom().replace('.', ' ').replace(' ', '_') + ".pdf";
    nomFichier = nomFichier.replaceAll(" ", "_");

    StreamResource.StreamSource source = new StreamResource.StreamSource() {
        private static final long serialVersionUID = 1L;

        @Override
        public InputStream getStream() {
            try {
                ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(OUTPUTSTREAM_SIZE);
                PdfWriter docWriter = null;
                Document document = configureDocument(MARGE_PDF);
                docWriter = PdfWriter.getInstance(document, baosPDF);
                docWriter.setEncryption(null, null, PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
                docWriter.setStrictImageSequence(true);
                if (configController.isInsertionFiligranePdfNotes()) {
                    docWriter.setPageEvent(new Watermark());
                }
                creerPdfDetail(document, MainUI.getCurrent().getEtudiant(), etape);
                docWriter.close();
                baosPDF.close();
                //Creation de l'export
                byte[] bytes = baosPDF.toByteArray();
                return new ByteArrayInputStream(bytes);
            } catch (DocumentException e) {
                LOG.error("Erreur  la gnration du dtail des notes : DocumentException ", e);
                return null;
            } catch (IOException e) {
                LOG.error("Erreur  la gnration du dtail des notes : IOException ", e);
                return null;
            }

        }
    };

    // Cration de la ressource 
    StreamResource resource = new StreamResource(source, nomFichier);
    resource.getStream().setParameter("Content-Disposition", "attachment; filename=" + nomFichier);
    //resource.setMIMEType("application/unknow");
    resource.setMIMEType("application/force-download;charset=UTF-8");
    resource.setCacheTime(0);
    return resource;
}

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;/*from  w w  w  . jav  a  2  s  . 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();
        }
    }
}

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.  jav  a2 s  .c  o  m

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