Search in sources :

Example 21 with LSSerializer

use of org.w3c.dom.ls.LSSerializer in project tomee by apache.

the class XmlFormatter method format.

public static String format(final String in) {
    try {
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        final DocumentBuilder db = dbf.newDocumentBuilder();
        final InputSource is = new InputSource(new StringReader(in));
        final Document document = db.parse(is);
        final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        final DOMImplementationLS impl = DOMImplementationLS.class.cast(registry.getDOMImplementation("XML 3.0 LS 3.0"));
        if (impl == null) {
            return in;
        }
        final LSSerializer serializer = impl.createLSSerializer();
        if (serializer.getDomConfig().canSetParameter("format-pretty-print", Boolean.TRUE)) {
            serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
            final LSOutput lsOutput = impl.createLSOutput();
            lsOutput.setEncoding("UTF-8");
            final StringWriter stringWriter = new StringWriter();
            lsOutput.setCharacterStream(stringWriter);
            serializer.write(document, lsOutput);
            return stringWriter.toString().replace("\"UTF-8\"?><", "\"UTF-8\"?>\n<");
        }
        return in;
    } catch (final Throwable t) {
        // just to be more sexy so ignore it and use ugly xml
        return in;
    }
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) StringWriter(java.io.StringWriter) DocumentBuilder(javax.xml.parsers.DocumentBuilder) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) StringReader(java.io.StringReader) DOMImplementationRegistry(org.w3c.dom.bootstrap.DOMImplementationRegistry) LSSerializer(org.w3c.dom.ls.LSSerializer) Document(org.w3c.dom.Document) LSOutput(org.w3c.dom.ls.LSOutput)

Example 22 with LSSerializer

use of org.w3c.dom.ls.LSSerializer in project beast-mcmc by beast-dev.

the class ConfigPersister method load.

public void load(File f) throws ConfigPersisterException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(f);
        DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
        LSSerializer lsSerializer = domImplementation.createLSSerializer();
        String configString = lsSerializer.writeToString(doc);
        _config = (Config) _xstream.fromXML(convertToCurrent(configString));
        setConfigPath(f);
    } catch (Exception e) {
        throw new ConfigPersisterException(e);
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) LSSerializer(org.w3c.dom.ls.LSSerializer) Document(org.w3c.dom.Document) IOException(java.io.IOException)

Example 23 with LSSerializer

use of org.w3c.dom.ls.LSSerializer in project ddf by codice.

the class XsltResponseQueueTransformer method transform.

@Override
public ddf.catalog.data.BinaryContent transform(SourceResponse upstreamResponse, Map<String, Serializable> arguments) throws CatalogTransformerException {
    LOGGER.debug("Transforming ResponseQueue with XSLT tranformer");
    long grandTotal = -1;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        try {
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        } catch (ParserConfigurationException e) {
            LOGGER.debug("Unable to configure features on document builder.", e);
        }
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();
        Node resultsElement = doc.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "results", null));
        // TODO use streaming XSLT, not DOM
        List<Result> results = upstreamResponse.getResults();
        grandTotal = upstreamResponse.getHits();
        for (Result result : results) {
            Metacard metacard = result.getMetacard();
            if (metacard != null) {
                String metadata = metacard.getMetadata();
                if (metadata != null) {
                    Element metacardElement = createElement(doc, XML_RESULTS_NAMESPACE, "metacard", null);
                    if (metacard.getId() != null) {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "id", metacard.getId()));
                    }
                    if (metacard.getMetacardType().toString() != null) {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "type", metacard.getMetacardType().getName()));
                    }
                    if (metacard.getTitle() != null) {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "title", metacard.getTitle()));
                    }
                    if (result.getRelevanceScore() != null) {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "score", result.getRelevanceScore().toString()));
                    }
                    if (result.getDistanceInMeters() != null) {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "distance", result.getDistanceInMeters().toString()));
                    }
                    if (metacard.getSourceId() != null) {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "site", metacard.getSourceId()));
                    }
                    if (metacard.getContentTypeName() != null) {
                        String contentType = metacard.getContentTypeName();
                        Element typeElement = createElement(doc, XML_RESULTS_NAMESPACE, "content-type", contentType);
                        // TODO revisit what to put in the qualifier
                        typeElement.setAttribute("qualifier", "content-type");
                        metacardElement.appendChild(typeElement);
                    }
                    if (metacard.getResourceURI() != null) {
                        try {
                            metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "product", metacard.getResourceURI().toString()));
                        } catch (DOMException e) {
                            LOGGER.debug(" Unable to create resource uri element", e);
                        }
                    }
                    if (metacard.getThumbnail() != null) {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "thumbnail", Base64.getEncoder().encodeToString(metacard.getThumbnail())));
                        try {
                            String mimeType = URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(metacard.getThumbnail()));
                            metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", mimeType));
                        } catch (IOException e) {
                            metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", "image/png"));
                        }
                    }
                    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                    if (metacard.getCreatedDate() != null) {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "created", fmt.print(metacard.getCreatedDate().getTime())));
                    }
                    // looking at the date last modified
                    if (metacard.getModifiedDate() != null) {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "updated", fmt.print(metacard.getModifiedDate().getTime())));
                    }
                    if (metacard.getEffectiveDate() != null) {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "effective", fmt.print(metacard.getEffectiveDate().getTime())));
                    }
                    if (metacard.getLocation() != null) {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "location", metacard.getLocation()));
                    }
                    Element documentElement = doc.createElementNS(XML_RESULTS_NAMESPACE, "document");
                    metacardElement.appendChild(documentElement);
                    resultsElement.appendChild(metacardElement);
                    Node importedNode = doc.importNode(new XPathHelper(metadata).getDocument().getFirstChild(), true);
                    documentElement.appendChild(importedNode);
                } else {
                    LOGGER.debug("Null content/document returned to XSLT ResponseQueueTransformer");
                }
            }
        }
        if (LOGGER.isDebugEnabled()) {
            DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
            LSSerializer lsSerializer = domImplementation.createLSSerializer();
            LOGGER.debug("Generated XML input for transform: " + lsSerializer.writeToString(doc));
        }
        LOGGER.debug("Starting responsequeue xslt transform.");
        Transformer transformer;
        Map<String, Object> mergedMap = new HashMap<String, Object>();
        mergedMap.put(GRAND_TOTAL, grandTotal);
        if (arguments != null) {
            mergedMap.putAll(arguments);
        }
        BinaryContent resultContent;
        StreamResult resultOutput = null;
        Source source = new DOMSource(doc);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        resultOutput = new StreamResult(baos);
        try {
            transformer = templates.newTransformer();
        } catch (TransformerConfigurationException tce) {
            throw new CatalogTransformerException("Could not perform Xslt transform: ", tce);
        }
        for (Map.Entry<String, Object> entry : mergedMap.entrySet()) {
            LOGGER.trace("Adding parameter to transform {{}:{}}", entry.getKey(), entry.getValue());
            transformer.setParameter(entry.getKey(), entry.getValue());
        }
        try {
            transformer.transform(source, resultOutput);
            byte[] bytes = baos.toByteArray();
            LOGGER.debug("Transform complete.");
            resultContent = new XsltTransformedContent(bytes, mimeType);
        } catch (TransformerException te) {
            LOGGER.debug("Could not perform Xslt transform: ", te);
            throw new CatalogTransformerException("Could not perform Xslt transform: ", te);
        }
        return resultContent;
    } catch (ParserConfigurationException e) {
        LOGGER.debug("Error creating new document: ", e);
        throw new CatalogTransformerException("Error merging entries to xml feed.", e);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Transformer(javax.xml.transform.Transformer) QueryResponseTransformer(ddf.catalog.transform.QueryResponseTransformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) XPathHelper(ddf.util.XPathHelper) HashMap(java.util.HashMap) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) Document(org.w3c.dom.Document) BinaryContent(ddf.catalog.data.BinaryContent) DOMSource(javax.xml.transform.dom.DOMSource) Source(javax.xml.transform.Source) StreamResult(javax.xml.transform.stream.StreamResult) Result(ddf.catalog.data.Result) DOMException(org.w3c.dom.DOMException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) StreamResult(javax.xml.transform.stream.StreamResult) LSSerializer(org.w3c.dom.ls.LSSerializer) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Metacard(ddf.catalog.data.Metacard) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) HashMap(java.util.HashMap) Map(java.util.Map)

Example 24 with LSSerializer

use of org.w3c.dom.ls.LSSerializer in project ddf by codice.

the class XPathHelper method print.

/**
     * Prints a given node as a String
     *
     * @param n
     *            - the node to print as a String
     * @param encoding
     *            - the character encoding to use for the returned String
     * @return the Node as a String, null if an exception is thrown or null is passed in.
     */
public static String print(Node n, String encoding) {
    if (n == null) {
        return null;
    }
    try {
        Document document = null;
        if (n instanceof Document) {
            document = (Document) n;
        } else {
            document = n.getOwnerDocument();
        }
        StringWriter stringOut = new StringWriter();
        DOMImplementationLS domImpl = (DOMImplementationLS) document.getImplementation();
        LSSerializer serializer = domImpl.createLSSerializer();
        LSOutput lsOut = domImpl.createLSOutput();
        lsOut.setEncoding(encoding);
        lsOut.setCharacterStream(stringOut);
        serializer.write(n, lsOut);
        return stringOut.toString();
    } catch (DOMException | LSException e) {
        LOGGER.debug(e.getMessage(), e);
    }
    return null;
}
Also used : DOMException(org.w3c.dom.DOMException) StringWriter(java.io.StringWriter) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) LSSerializer(org.w3c.dom.ls.LSSerializer) Document(org.w3c.dom.Document) LSOutput(org.w3c.dom.ls.LSOutput) LSException(org.w3c.dom.ls.LSException)

Example 25 with LSSerializer

use of org.w3c.dom.ls.LSSerializer in project ddf by codice.

the class SAMLAuthenticationToken method getCredentialsAsXMLString.

@Override
public String getCredentialsAsXMLString() {
    String creds = "";
    Element element = getSAMLTokenAsElement();
    if (element != null) {
        DOMImplementationLS lsImpl = (DOMImplementationLS) element.getOwnerDocument().getImplementation().getFeature("LS", "3.0");
        if (null != lsImpl) {
            LSSerializer serializer = lsImpl.createLSSerializer();
            serializer.getDomConfig().setParameter("xml-declaration", //by default its true, so set it to false to get String without xml-declaration
            false);
            creds = serializer.writeToString(element);
        }
        LOGGER.trace("XML representation of SAML token: {}", creds);
    }
    return creds;
}
Also used : Element(org.w3c.dom.Element) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) LSSerializer(org.w3c.dom.ls.LSSerializer)

Aggregations

LSSerializer (org.w3c.dom.ls.LSSerializer)25 DOMImplementationLS (org.w3c.dom.ls.DOMImplementationLS)18 DOMException (org.w3c.dom.DOMException)8 StringWriter (java.io.StringWriter)7 DocumentBuilder (javax.xml.parsers.DocumentBuilder)7 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)7 Document (org.w3c.dom.Document)7 LSException (org.w3c.dom.ls.LSException)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 DOM3Serializer (org.apache.xml.serializer.DOM3Serializer)6 Serializer (org.apache.xml.serializer.Serializer)6 LSOutput (org.w3c.dom.ls.LSOutput)5 FileOutputStream (java.io.FileOutputStream)4 IOException (java.io.IOException)4 OutputStream (java.io.OutputStream)4 HttpURLConnection (java.net.HttpURLConnection)4 URL (java.net.URL)4 URLConnection (java.net.URLConnection)4 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)4 Element (org.w3c.dom.Element)4