Search in sources :

Example 21 with SAXResult

use of javax.xml.transform.sax.SAXResult in project play-cookbook by spinscale.

the class RenderPDF method apply.

@Override
public void apply(Request request, Response response) {
    Template template = TemplateLoader.load(templateFile);
    response.setHeader("Content-Disposition", "inline; filename=\"" + request.actionMethod + ".pdf\"");
    setContentTypeIfNotSet(response, "application/pdf");
    try {
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, response.out);
        Transformer transformer = tFactory.newTransformer();
        Scope.RenderArgs args = Scope.RenderArgs.current();
        String content = template.render(args.data);
        Source src = new StreamSource(IOUtils.toInputStream(content));
        javax.xml.transform.Result res = new SAXResult(fop.getDefaultHandler());
        transformer.transform(src, res);
    } catch (FOPException e) {
        Logger.error(e, "Error creating pdf");
    } catch (TransformerException e) {
        Logger.error(e, "Error creating pdf");
    }
}
Also used : Transformer(javax.xml.transform.Transformer) Fop(org.apache.fop.apps.Fop) StreamSource(javax.xml.transform.stream.StreamSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) Template(play.templates.Template) FOPException(org.apache.fop.apps.FOPException) Scope(play.mvc.Scope) SAXResult(javax.xml.transform.sax.SAXResult) TransformerException(javax.xml.transform.TransformerException)

Example 22 with SAXResult

use of javax.xml.transform.sax.SAXResult in project spring-framework by spring-projects.

the class JibxMarshaller method marshalSaxHandlers.

@Override
protected void marshalSaxHandlers(Object graph, ContentHandler contentHandler, LexicalHandler lexicalHandler) throws XmlMappingException {
    try {
        // JiBX does not support SAX natively, so we write to a buffer first, and transform that to the handlers
        SAXResult saxResult = new SAXResult(contentHandler);
        saxResult.setLexicalHandler(lexicalHandler);
        transformAndMarshal(graph, saxResult);
    } catch (IOException ex) {
        throw new MarshallingFailureException("JiBX marshalling exception", ex);
    }
}
Also used : SAXResult(javax.xml.transform.sax.SAXResult) MarshallingFailureException(org.springframework.oxm.MarshallingFailureException) IOException(java.io.IOException)

Example 23 with SAXResult

use of javax.xml.transform.sax.SAXResult in project spring-framework by spring-projects.

the class Jaxb2MarshallerTests method marshalSAXResult.

@Test
public void marshalSAXResult() throws Exception {
    ContentHandler contentHandler = mock(ContentHandler.class);
    SAXResult result = new SAXResult(contentHandler);
    marshaller.marshal(flights, result);
    InOrder ordered = inOrder(contentHandler);
    ordered.verify(contentHandler).setDocumentLocator(isA(Locator.class));
    ordered.verify(contentHandler).startDocument();
    ordered.verify(contentHandler).startPrefixMapping("", "http://samples.springframework.org/flight");
    ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flights"), eq("flights"), isA(Attributes.class));
    ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flight"), eq("flight"), isA(Attributes.class));
    ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("number"), eq("number"), isA(Attributes.class));
    ordered.verify(contentHandler).characters(isA(char[].class), eq(0), eq(2));
    ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "number", "number");
    ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flight", "flight");
    ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flights", "flights");
    ordered.verify(contentHandler).endPrefixMapping("");
    ordered.verify(contentHandler).endDocument();
}
Also used : Locator(org.xml.sax.Locator) InOrder(org.mockito.InOrder) SAXResult(javax.xml.transform.sax.SAXResult) Attributes(org.xml.sax.Attributes) ContentHandler(org.xml.sax.ContentHandler) Test(org.junit.Test)

Example 24 with SAXResult

use of javax.xml.transform.sax.SAXResult in project spring-framework by spring-projects.

the class XStreamMarshallerTests method marshalSaxResult.

@Test
public void marshalSaxResult() throws Exception {
    ContentHandler contentHandler = mock(ContentHandler.class);
    SAXResult result = new SAXResult(contentHandler);
    marshaller.marshal(flight, result);
    InOrder ordered = inOrder(contentHandler);
    ordered.verify(contentHandler).startDocument();
    ordered.verify(contentHandler).startElement(eq(""), eq("flight"), eq("flight"), isA(Attributes.class));
    ordered.verify(contentHandler).startElement(eq(""), eq("flightNumber"), eq("flightNumber"), isA(Attributes.class));
    ordered.verify(contentHandler).characters(isA(char[].class), eq(0), eq(2));
    ordered.verify(contentHandler).endElement("", "flightNumber", "flightNumber");
    ordered.verify(contentHandler).endElement("", "flight", "flight");
    ordered.verify(contentHandler).endDocument();
}
Also used : InOrder(org.mockito.InOrder) SAXResult(javax.xml.transform.sax.SAXResult) Attributes(org.xml.sax.Attributes) ContentHandler(org.xml.sax.ContentHandler) Test(org.junit.Test)

Example 25 with SAXResult

use of javax.xml.transform.sax.SAXResult in project OpenClinica by OpenClinica.

the class PdfProcessingFunction method run.

/*
     * The run() method.  Note that we will assume that all variables (i.e. file
     * paths) are set here.
     * 
     * Running this will open a file stream, perform a transform with the *.fo 
     * file (note, does not necessarily have to have a *.fo suffix) and then 
     * return a success/fail message.
     * (non-Javadoc)
     * @see org.akaza.openclinica.bean.service.ProcessingInterface#run()
     */
public ProcessingResultType run() {
    // FopFactory fopFactory = FopFactory.newInstance(); 
    FopFactory fopFactory = FopFactory.newInstance();
    //   FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
    OutputStream out = null;
    File outputFile = null;
    String zipName = "_";
    File xslFile = null;
    try {
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
        //set the renderer to be PDF
        // the expected sequence here will be xml -> xslt -> fo -> pdf
        // where fo is the transformed file
        File procExportDirectory;
        File[] oldFiles = null;
        if (this.getExportFileName() != null && this.getLocation() != null) {
            procExportDirectory = new File(this.getLocation());
            if (!procExportDirectory.isDirectory()) {
                procExportDirectory.mkdir();
            }
            outputFile = new File(procExportDirectory + File.separator + this.getExportFileName() + ".pdf");
            zipName = (procExportDirectory + File.separator + this.getExportFileName() + ".zip");
        } else {
            //getODMFILENAme is a path of .fo object
            outputFile = new File(this.getODMXMLFileName() + ".pdf");
            zipName = this.getODMXMLFileName() + ".zip";
        }
        //transformfilename is abs path+file name(.fo) transformFileName and odmxmlfile name are same?
        xslFile = new File(this.getTransformFileName());
        out = new FileOutputStream(outputFile);
        out = new BufferedOutputStream(out);
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
        TransformerFactory factory = TransformerFactory.newInstance();
        // identity transformer
        Transformer transformer = factory.newTransformer();
        Source src = new StreamSource(xslFile);
        // Resulting SAX events (the generated FO) must be piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());
        // Start XSLT transformation and FOP processing
        transformer.transform(src, res);
        // Result processing
        FormattingResults foResults = fop.getResults();
        java.util.List pageSequences = foResults.getPageSequences();
        for (java.util.Iterator it = pageSequences.iterator(); it.hasNext(); ) {
            PageSequenceResults pageSequenceResults = (PageSequenceResults) it.next();
            logger.debug("PageSequence " + (String.valueOf(pageSequenceResults.getID()).length() > 0 ? pageSequenceResults.getID() : "<no id>") + " generated " + pageSequenceResults.getPageCount() + " pages.");
        }
        logger.debug("Generated " + foResults.getPageCount() + " pages in total.");
        out.close();
        if (isZip()) {
            if (outputFile != null) {
                ZipOutputStream zipOut = null;
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(outputFile);
                    zipOut = new ZipOutputStream(new FileOutputStream(new File(zipName)));
                    zipOut.putNextEntry(new ZipEntry(outputFile.getName()));
                    int bytesRead;
                    byte[] buff = new byte[512];
                    while ((bytesRead = fis.read(buff)) != -1) {
                        zipOut.write(buff, 0, bytesRead);
                    }
                    zipOut.closeEntry();
                    zipOut.finish();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (zipOut != null)
                        zipOut.close();
                    if (fis != null)
                        fis.close();
                }
            }
            setArchivedFileName(new File(zipName).getName());
        } else
            setArchivedFileName(outputFile.getName());
    } catch (Exception e) {
        e.printStackTrace();
        ProcessingResultType resultError = ProcessingResultType.FAIL;
        // view datasets page
        resultError.setUrl(CoreResources.getField("sysURL.base") + "ViewDatasets");
        resultError.setArchiveMessage("Failure thrown: " + e.getMessage());
        resultError.setDescription("Your job failed with the message of: " + e.getMessage());
        return resultError;
    } finally {
    }
    if (isDeleteOld()) {
        deleteOldFiles(this.getOldFiles(), outputFile, zipName);
    }
    if (isZip()) {
        outputFile.delete();
    }
    //delete intermediatory .fo file
    if (xslFile != null)
        xslFile.delete();
    // otherwise return a success with the URL link
    ProcessingResultType resultSuccess = ProcessingResultType.SUCCESS;
    resultSuccess.setUrl(CoreResources.getField("sysURL.base") + // to the pdf
    "AccessFile?fileId=");
    resultSuccess.setArchiveMessage("Success");
    resultSuccess.setDescription("Your job succeeded please find the URL below");
    return resultSuccess;
}
Also used : Transformer(javax.xml.transform.Transformer) FOUserAgent(org.apache.fop.apps.FOUserAgent) ZipOutputStream(java.util.zip.ZipOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ZipEntry(java.util.zip.ZipEntry) PageSequenceResults(org.apache.fop.apps.PageSequenceResults) FopFactory(org.apache.fop.apps.FopFactory) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult) BufferedOutputStream(java.io.BufferedOutputStream) TransformerFactory(javax.xml.transform.TransformerFactory) Fop(org.apache.fop.apps.Fop) StreamSource(javax.xml.transform.stream.StreamSource) FormattingResults(org.apache.fop.apps.FormattingResults) FileInputStream(java.io.FileInputStream) FOPException(org.apache.fop.apps.FOPException) SAXResult(javax.xml.transform.sax.SAXResult) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Aggregations

SAXResult (javax.xml.transform.sax.SAXResult)34 Transformer (javax.xml.transform.Transformer)15 TransformerException (javax.xml.transform.TransformerException)14 IOException (java.io.IOException)13 TransformerFactory (javax.xml.transform.TransformerFactory)10 StreamResult (javax.xml.transform.stream.StreamResult)10 StreamSource (javax.xml.transform.stream.StreamSource)10 Source (javax.xml.transform.Source)9 DOMResult (javax.xml.transform.dom.DOMResult)9 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)8 Result (javax.xml.transform.Result)8 ContentHandler (org.xml.sax.ContentHandler)8 Fop (org.apache.fop.apps.Fop)7 Document (org.w3c.dom.Document)7 DocumentBuilder (javax.xml.parsers.DocumentBuilder)6 Node (org.w3c.dom.Node)6 SAXException (org.xml.sax.SAXException)6 FileOutputStream (java.io.FileOutputStream)5 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)5 LexicalHandler (org.xml.sax.ext.LexicalHandler)5