Search in sources :

Example 41 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project zaproxy by zaproxy.

the class ReportGenerator method stringToHtml.

public static String stringToHtml(String inxml, String infilexsl) {
    Document doc = null;
    // factory.setNamespaceAware(true);
    // factory.setValidating(true);
    File stylesheet = null;
    StringReader inReader = new StringReader(inxml);
    StringWriter writer = new StringWriter();
    try {
        stylesheet = new File(infilexsl);
        DocumentBuilder builder = XmlUtils.newXxeDisabledDocumentBuilderFactory().newDocumentBuilder();
        doc = builder.parse(new InputSource(inReader));
        // Use a Transformer for output
        TransformerFactory tFactory = TransformerFactory.newInstance();
        StreamSource stylesource = new StreamSource(stylesheet);
        Transformer transformer = tFactory.newTransformer(stylesource);
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
    } catch (TransformerException | SAXException | ParserConfigurationException | IOException e) {
        showDialogForGUI();
        logger.error(e.getMessage(), e);
    } finally {
    }
    // we should really adopt something other than XSLT ;)
    return writer.toString().replace("&lt;p&gt;", "<p>").replace("&lt;/p&gt;", "</p>");
}
Also used : InputSource(org.xml.sax.InputSource) DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) StringWriter(java.io.StringWriter) DocumentBuilder(javax.xml.parsers.DocumentBuilder) StringReader(java.io.StringReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) File(java.io.File) TransformerException(javax.xml.transform.TransformerException)

Example 42 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project enclojure by EricThorsen.

the class Processor method process.

public int process() throws TransformerException, IOException, SAXException {
    ZipInputStream zis = new ZipInputStream(input);
    final ZipOutputStream zos = new ZipOutputStream(output);
    final OutputStreamWriter osw = new OutputStreamWriter(zos);
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    TransformerFactory tf = TransformerFactory.newInstance();
    if (!tf.getFeature(SAXSource.FEATURE) || !tf.getFeature(SAXResult.FEATURE)) {
        return 0;
    }
    SAXTransformerFactory saxtf = (SAXTransformerFactory) tf;
    Templates templates = null;
    if (xslt != null) {
        templates = saxtf.newTemplates(xslt);
    }
    // configuring outHandlerFactory
    // ///////////////////////////////////////////////////////
    EntryElement entryElement = getEntryElement(zos);
    ContentHandler outDocHandler = null;
    switch(outRepresentation) {
        case BYTECODE:
            outDocHandler = new OutputSlicingHandler(new ASMContentHandlerFactory(zos, computeMax), entryElement, false);
            break;
        case MULTI_XML:
            outDocHandler = new OutputSlicingHandler(new SAXWriterFactory(osw, true), entryElement, true);
            break;
        case SINGLE_XML:
            ZipEntry outputEntry = new ZipEntry(SINGLE_XML_NAME);
            zos.putNextEntry(outputEntry);
            outDocHandler = new SAXWriter(osw, false);
            break;
    }
    // configuring inputDocHandlerFactory
    // /////////////////////////////////////////////////
    ContentHandler inDocHandler;
    if (templates == null) {
        inDocHandler = outDocHandler;
    } else {
        inDocHandler = new InputSlicingHandler("class", outDocHandler, new TransformerHandlerFactory(saxtf, templates, outDocHandler));
    }
    ContentHandlerFactory inDocHandlerFactory = new SubdocumentHandlerFactory(inDocHandler);
    if (inDocHandler != null && inRepresentation != SINGLE_XML) {
        inDocHandler.startDocument();
        inDocHandler.startElement("", "classes", "classes", new AttributesImpl());
    }
    int i = 0;
    ZipEntry ze;
    while ((ze = zis.getNextEntry()) != null) {
        update(ze.getName(), n++);
        if (isClassEntry(ze)) {
            processEntry(zis, ze, inDocHandlerFactory);
        } else {
            OutputStream os = entryElement.openEntry(getName(ze));
            copyEntry(zis, os);
            entryElement.closeEntry();
        }
        i++;
    }
    if (inDocHandler != null && inRepresentation != SINGLE_XML) {
        inDocHandler.endElement("", "classes", "classes");
        inDocHandler.endDocument();
    }
    if (outRepresentation == SINGLE_XML) {
        zos.closeEntry();
    }
    zos.flush();
    zos.close();
    return i;
}
Also used : SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) TransformerFactory(javax.xml.transform.TransformerFactory) ZipEntry(java.util.zip.ZipEntry) ZipOutputStream(java.util.zip.ZipOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) Templates(javax.xml.transform.Templates) ContentHandler(org.xml.sax.ContentHandler) ZipInputStream(java.util.zip.ZipInputStream) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ZipOutputStream(java.util.zip.ZipOutputStream) OutputStreamWriter(java.io.OutputStreamWriter)

Example 43 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project series-rest-api by 52North.

the class PDFReportGenerator method encodeAndWriteTo.

@Override
public void encodeAndWriteTo(DataCollection<QuantityData> data, OutputStream stream) throws IoParseException {
    try {
        generateOutput(data);
        DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder();
        Configuration cfg = cfgBuilder.build(document.newInputStream());
        FopFactory fopFactory = new FopFactoryBuilder(baseURI).setConfiguration(cfg).build();
        final String mimeType = MimeType.APPLICATION_PDF.getMimeType();
        Fop fop = fopFactory.newFop(mimeType, stream);
        //FopFactory fopFactory = FopFactory.newInstance(cfg);
        //Fop fop = fopFactory.newFop(APPLICATION_PDF.getMimeType(), stream);
        //FopFactory fopFactory = fopFactoryBuilder.build();
        //Fop fop = fopFactory.newFop(APPLICATION_PDF.getMimeType(), stream);
        // Create PDF via XSLT transformation
        TransformerFactory transFact = TransformerFactory.newInstance();
        StreamSource transformationRule = getTransforamtionRule();
        Transformer transformer = transFact.newTransformer(transformationRule);
        Source source = new StreamSource(document.newInputStream());
        Result result = new SAXResult(fop.getDefaultHandler());
        if (LOGGER.isDebugEnabled()) {
            try {
                File tempFile = File.createTempFile(TEMP_FILE_PREFIX, ".xml");
                StreamResult debugResult = new StreamResult(tempFile);
                transformer.transform(source, debugResult);
                String xslResult = XmlObject.Factory.parse(tempFile).xmlText();
                LOGGER.debug("xsl-fo input (locale '{}'): {}", i18n.getTwoDigitsLanguageCode(), xslResult);
            } catch (IOException | TransformerException | XmlException e) {
                LOGGER.error("Could not debug XSL result output!", e);
            }
        }
        // XXX debug, diagram is not embedded
        transformer.transform(source, result);
    } catch (FOPException e) {
        throw new IoParseException("Failed to create Formatting Object Processor (FOP)", e);
    } catch (SAXException | ConfigurationException | IOException e) {
        throw new IoParseException("Failed to read config for Formatting Object Processor (FOP)", e);
    } catch (TransformerConfigurationException e) {
        throw new IoParseException("Invalid transform configuration. Inspect xslt!", e);
    } catch (TransformerException e) {
        throw new IoParseException("Could not generate PDF report!", e);
    }
}
Also used : IoParseException(org.n52.io.IoParseException) DefaultConfigurationBuilder(org.apache.avalon.framework.configuration.DefaultConfigurationBuilder) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) Configuration(org.apache.avalon.framework.configuration.Configuration) StreamResult(javax.xml.transform.stream.StreamResult) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) Fop(org.apache.fop.apps.Fop) StreamSource(javax.xml.transform.stream.StreamSource) FopFactory(org.apache.fop.apps.FopFactory) IOException(java.io.IOException) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult) SAXException(org.xml.sax.SAXException) FopFactoryBuilder(org.apache.fop.apps.FopFactoryBuilder) FOPException(org.apache.fop.apps.FOPException) SAXResult(javax.xml.transform.sax.SAXResult) ConfigurationException(org.apache.avalon.framework.configuration.ConfigurationException) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) XmlException(org.apache.xmlbeans.XmlException) File(java.io.File) TransformerException(javax.xml.transform.TransformerException)

Example 44 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project OpenClinica by OpenClinica.

the class XalanTransformJob method executeInternal.

protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
    // need to generate a Locale so that user beans and other things will
    // generate normally
    // TODO make dynamic?
    Locale locale = new Locale("en-US");
    ResourceBundleProvider.updateLocale(locale);
    ResourceBundle pageMessages = ResourceBundleProvider.getPageMessagesBundle();
    JobDataMap dataMap = context.getMergedJobDataMap();
    // get the file information from the job
    String alertEmail = dataMap.getString(EMAIL);
    try {
        TransformerFactory tFactory = TransformerFactory.newInstance();
        // Use the TransformerFactory to instantiate a Transformer that will work with  
        // the stylesheet you specify. This method call also processes the stylesheet
        // into a compiled Templates object.
        java.io.InputStream in = new java.io.FileInputStream(dataMap.getString(XSL_FILE_PATH));
        // tFactory.setAttribute("use-classpath", Boolean.TRUE);
        // tFactory.setErrorListener(new ListingErrorHandler());
        Transformer transformer = tFactory.newTransformer(new StreamSource(in));
        // Use the Transformer to apply the associated Templates object to an XML document
        // (foo.xml) and write the output to a file (foo.out).
        //  System.out.println("--> job starting: ");
        final long start = System.currentTimeMillis();
        transformer.transform(new StreamSource(dataMap.getString(XML_FILE_PATH)), new StreamResult(new FileOutputStream(dataMap.getString(SQL_FILE_PATH))));
        final long done = System.currentTimeMillis() - start;
    // System.out.println("--> job completed in " + done + " ms");
    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : Locale(java.util.Locale) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) JobDataMap(org.quartz.JobDataMap) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) StreamSource(javax.xml.transform.stream.StreamSource) FileNotFoundException(java.io.FileNotFoundException) FileOutputStream(java.io.FileOutputStream) ResourceBundle(java.util.ResourceBundle) TransformerException(javax.xml.transform.TransformerException)

Example 45 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project OpenClinica by OpenClinica.

the class OpenRosaServices method getUserXml.

private String getUserXml(ServletContext context) throws Exception {
    HashMap<String, String> value = getSubjectContextCacheValue(context);
    String studySubjectOid = value.get("studySubjectOID");
    StudySubject ssBean = ssDao.findByOcOID(studySubjectOid);
    StudyBean study = getStudy(ssBean.getStudy().getOc_oid());
    StudyBean parentStudy = getParentStudy(ssBean.getStudy().getOc_oid());
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    Element root = doc.createElement("root");
    doc.appendChild(root);
    List<UserAccount> users = userAccountDao.findNonRootNonParticipateUsersByStudyId(study.getId(), parentStudy.getId());
    for (UserAccount userAccount : users) {
        Element item = doc.createElement("item");
        Element userName = doc.createElement("user_name");
        userName.appendChild(doc.createTextNode(userAccount.getUserName()));
        Element firstName = doc.createElement("first_name");
        firstName.appendChild(doc.createTextNode(userAccount.getFirstName()));
        Element lastName = doc.createElement("last_name");
        lastName.appendChild(doc.createTextNode(userAccount.getLastName()));
        item.appendChild(userName);
        item.appendChild(firstName);
        item.appendChild(lastName);
        root.appendChild(item);
    }
    DOMSource dom = new DOMSource(doc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.transform(dom, result);
    String userXml = writer.toString();
    return userXml;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) StudyBean(org.akaza.openclinica.bean.managestudy.StudyBean) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) StringWriter(java.io.StringWriter) StudySubject(org.akaza.openclinica.domain.datamap.StudySubject) DocumentBuilder(javax.xml.parsers.DocumentBuilder) UserAccount(org.akaza.openclinica.domain.user.UserAccount)

Aggregations

TransformerFactory (javax.xml.transform.TransformerFactory)257 Transformer (javax.xml.transform.Transformer)221 StreamResult (javax.xml.transform.stream.StreamResult)198 DOMSource (javax.xml.transform.dom.DOMSource)157 TransformerException (javax.xml.transform.TransformerException)86 StringWriter (java.io.StringWriter)77 StreamSource (javax.xml.transform.stream.StreamSource)77 Document (org.w3c.dom.Document)67 Source (javax.xml.transform.Source)56 IOException (java.io.IOException)55 File (java.io.File)47 DocumentBuilder (javax.xml.parsers.DocumentBuilder)43 ByteArrayOutputStream (java.io.ByteArrayOutputStream)37 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)37 Element (org.w3c.dom.Element)36 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)35 Result (javax.xml.transform.Result)32 ByteArrayInputStream (java.io.ByteArrayInputStream)29 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)29 StringReader (java.io.StringReader)28