Search in sources :

Example 91 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project stanbol by apache.

the class DOMUtils method getStringFromDoc.

/**
     * This returns a string representation of the given document.
     *
     * @param doc
     *            an XML <code>Document</code>
     * @param encoding
     *            a <code>String</code> with the encoding to use
     * @param docTypeDef
     *            a <code>String</code> with the DTD name; use <code>null</code>
     *            for no DTD
     * @return a <code>String</code> with the XML string
     */
public static String getStringFromDoc(Document doc, String encoding, String docTypeDef) {
    try {
        // use a Transformer for output
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer xformer = tFactory.newTransformer();
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");
        xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
        xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        xformer.setOutputProperty(OutputKeys.METHOD, "xml");
        if (null != docTypeDef) {
            xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docTypeDef);
        }
        DOMSource source = new DOMSource(doc);
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        xformer.transform(source, result);
        return sw.toString();
    } catch (TransformerConfigurationException tce) {
        // error generated by the parser
        System.err.println("** Transformer Factory error");
        System.err.println("   " + tce.getMessage());
        // use the contained exception, if any
        Throwable x = tce;
        if (tce.getException() != null) {
            x = tce.getException();
        }
        x.printStackTrace();
    } catch (TransformerException te) {
        // error generated by the parser
        System.err.println("** Transformation error");
        System.err.println("   " + te.getMessage());
        // use the contained exception, if any
        Throwable x = te;
        if (te.getException() != null) {
            x = te.getException();
        }
        x.printStackTrace();
    }
    return null;
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StringWriter(java.io.StringWriter) StreamResult(javax.xml.transform.stream.StreamResult) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) TransformerException(javax.xml.transform.TransformerException)

Example 92 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project tika by apache.

the class MimeTypesReader method read.

public void read(Document document) throws MimeTypeException {
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(new DOMSource(document), new SAXResult(this));
    } catch (TransformerException e) {
        throw new MimeTypeException("Failed to parse type registry", e);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) SAXResult(javax.xml.transform.sax.SAXResult) TransformerException(javax.xml.transform.TransformerException)

Example 93 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project stanbol by apache.

the class HtmlExtractionRegistry method initialize.

public void initialize(InputStream configFileStream) throws InitializationException {
    try {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xPath = factory.newXPath();
        DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = parser.parse(new InputSource(configFileStream));
        Node node;
        NodeList nodes = (NodeList) xPath.evaluate("/htmlextractors/extractor", document, XPathConstants.NODESET);
        if (nodes != null) {
            TransformerFactory transFac = TransformerFactory.newInstance();
            transFac.setURIResolver(new BundleURIResolver());
            for (int j = 0, iCnt = nodes.getLength(); j < iCnt; j++) {
                Node nd = nodes.item(j);
                node = (Node) xPath.evaluate("@id", nd, XPathConstants.NODE);
                String id = node.getNodeValue();
                Node srcNode = (Node) xPath.evaluate("source", nd, XPathConstants.NODE);
                if (srcNode != null) {
                    node = (Node) xPath.evaluate("@type", srcNode, XPathConstants.NODE);
                    String srcType = node.getNodeValue();
                    if (srcType.equals("xslt")) {
                        String rdfFormat = "rdfxml";
                        Syntax rdfSyntax = Syntax.RdfXml;
                        node = (Node) xPath.evaluate("@syntax", srcNode, XPathConstants.NODE);
                        if (node != null) {
                            rdfFormat = node.getNodeValue();
                            if (rdfFormat.equalsIgnoreCase("turtle")) {
                                rdfSyntax = Syntax.Turtle;
                            } else if (rdfFormat.equalsIgnoreCase("ntriple")) {
                                rdfSyntax = Syntax.Ntriples;
                            } else if (rdfFormat.equalsIgnoreCase("n3")) {
                                rdfSyntax = XsltExtractor.N3;
                            } else if (!rdfFormat.equalsIgnoreCase("rdfxml")) {
                                throw new InitializationException("Unknown RDF Syntax: " + rdfFormat + " for " + id + " extractor");
                            }
                        }
                        // TODO: do something about disjunctions of
                        // Extractors? Assume, only RDFa or Microformats are
                        // used?
                        String fileName = DOMUtils.getText(srcNode);
                        XsltExtractor xsltExtractor = new XsltExtractor(id, fileName, transFac);
                        xsltExtractor.setSyntax(rdfSyntax);
                        // name of URI/URL parameter of the script (default
                        // "uri")
                        node = (Node) xPath.evaluate("@uri", srcNode, XPathConstants.NODE);
                        if (node != null) {
                            xsltExtractor.setUriParameter(node.getNodeValue());
                        }
                        registry.put(id, xsltExtractor);
                        activeExtractors.add(id);
                    } else if (srcType.equals("java")) {
                        String clsName = srcNode.getNodeValue();
                        Object extractor = Class.forName(clsName).newInstance();
                        if (extractor instanceof HtmlExtractionComponent) {
                            registry.put(id, (HtmlExtractionComponent) extractor);
                            activeExtractors.add(id);
                        } else {
                            throw new InitializationException("clsName is not an HtmlExtractionComponent");
                        }
                    } else {
                        LOG.warn("No valid type for extractor found: " + id);
                    }
                    LOG.info("Extractor for: " + id);
                }
            }
        }
    } catch (FileNotFoundException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (XPathExpressionException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (DOMException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (ParserConfigurationException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (SAXException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (IOException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (ClassNotFoundException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (InstantiationException e) {
        throw new InitializationException(e.getMessage(), e);
    } catch (IllegalAccessException e) {
        throw new InitializationException(e.getMessage(), e);
    }
}
Also used : InputSource(org.xml.sax.InputSource) XPathExpressionException(javax.xml.xpath.XPathExpressionException) Node(org.w3c.dom.Node) FileNotFoundException(java.io.FileNotFoundException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) XPathFactory(javax.xml.xpath.XPathFactory) DOMException(org.w3c.dom.DOMException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) XPath(javax.xml.xpath.XPath) TransformerFactory(javax.xml.transform.TransformerFactory) NodeList(org.w3c.dom.NodeList) IOException(java.io.IOException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Syntax(org.ontoware.rdf2go.model.Syntax)

Example 94 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project ddf by codice.

the class XacmlClient method addNamespaceAndPrefixes.

/**
     * Adds namespaces and namespace prefixes to the XACML response returned by the XACML PDP. The
     * XACML PDP returns a response with no namespaces, so we need to add them to unmarshal the
     * response.
     *
     * @param xacmlResponse The XACML response as a string.
     * @return DOM representation of the XACML response with namespaces and namespace prefixes.
     * @throws PdpException
     */
private DOMResult addNamespaceAndPrefixes(String xacmlResponse) throws PdpException {
    XMLReader xmlReader = null;
    try {
        XMLReader xmlParser = XMLReaderFactory.createXMLReader();
        xmlParser.setFeature("http://xml.org/sax/features/external-general-entities", false);
        xmlParser.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        xmlParser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        xmlReader = new XMLFilterImpl(xmlParser) {

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                super.startElement(XACML30_NAMESPACE, localName, XACML_PREFIX + ":" + qName, attributes);
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                super.endElement(XACML30_NAMESPACE, localName, XACML_PREFIX + ":" + qName);
            }
        };
    } catch (SAXException e) {
        String message = "Unable to read XACML response:\n" + xacmlResponse;
        LOGGER.info(message);
        throw new PdpException(message, e);
    }
    DOMResult domResult;
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(XacmlClient.class.getClassLoader());
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        domResult = new DOMResult();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new SAXSource(xmlReader, new InputSource(new StringReader(xacmlResponse))), domResult);
    } catch (TransformerException e) {
        String message = "Unable to transform XACML response:\n" + xacmlResponse;
        LOGGER.info(message);
        throw new PdpException(message, e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }
    return domResult;
}
Also used : InputSource(org.xml.sax.InputSource) DOMResult(javax.xml.transform.dom.DOMResult) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) Attributes(org.xml.sax.Attributes) SAXException(org.xml.sax.SAXException) SAXSource(javax.xml.transform.sax.SAXSource) XMLFilterImpl(org.xml.sax.helpers.XMLFilterImpl) StringReader(java.io.StringReader) XMLReader(org.xml.sax.XMLReader) TransformerException(javax.xml.transform.TransformerException)

Example 95 with TransformerFactory

use of javax.xml.transform.TransformerFactory in project ddf by codice.

the class XMLUtils method transformation.

private static void transformation(Source sourceXml, TransformerProperties transformProperties, Result result) {
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(XMLUtils.class.getClassLoader());
    try {
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        for (Entry<String, String> entry : transformProperties.getOutputProperties()) {
            transformer.setOutputProperty(entry.getKey(), entry.getValue());
        }
        if (transformProperties.getErrorListener() != null) {
            transformer.setErrorListener(transformProperties.getErrorListener());
        }
        transformer.transform(sourceXml, result);
    } catch (TransformerException e) {
        LOGGER.debug("Unable to transform XML.", e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) TransformerException(javax.xml.transform.TransformerException)

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