Search in sources :

Example 36 with DOMImplementationLS

use of org.w3c.dom.ls.DOMImplementationLS in project syncope by apache.

the class CamelRouteLoader method loadRoutes.

private void loadRoutes(final String domain, final DataSource dataSource, final Resource resource, final AnyTypeKind anyTypeKind) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    boolean shouldLoadRoutes = jdbcTemplate.queryForList(String.format("SELECT * FROM %s WHERE ANYTYPEKIND = ?", CamelRoute.class.getSimpleName()), new Object[] { anyTypeKind.name() }).isEmpty();
    if (shouldLoadRoutes) {
        try {
            TransformerFactory tf = null;
            DOMImplementationLS domImpl = null;
            NodeList routeNodes;
            if (IS_JBOSS) {
                tf = TransformerFactory.newInstance();
                tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                tf.setURIResolver((href, base) -> null);
                Document doc = StaxUtils.read(resource.getInputStream());
                routeNodes = doc.getDocumentElement().getElementsByTagName("route");
            } else {
                DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
                domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS");
                LSInput lsinput = domImpl.createLSInput();
                lsinput.setByteStream(resource.getInputStream());
                LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
                routeNodes = parser.parse(lsinput).getDocumentElement().getElementsByTagName("route");
            }
            for (int s = 0; s < routeNodes.getLength(); s++) {
                Node routeElement = routeNodes.item(s);
                String routeContent = IS_JBOSS ? nodeToString(routeNodes.item(s), tf) : nodeToString(routeNodes.item(s), domImpl);
                String routeId = ((Element) routeElement).getAttribute("id");
                jdbcTemplate.update(String.format("INSERT INTO %s(ID, ANYTYPEKIND, CONTENT) VALUES (?, ?, ?)", CamelRoute.class.getSimpleName()), new Object[] { routeId, anyTypeKind.name(), routeContent });
                LOG.info("[{}] Route successfully loaded: {}", domain, routeId);
            }
        } catch (Exception e) {
            LOG.error("[{}] Route load failed", domain, e);
        }
    }
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) LSParser(org.w3c.dom.ls.LSParser) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) CamelRoute(org.apache.syncope.core.persistence.api.entity.CamelRoute) Document(org.w3c.dom.Document) TransformerException(javax.xml.transform.TransformerException) LSInput(org.w3c.dom.ls.LSInput) DOMImplementationRegistry(org.w3c.dom.bootstrap.DOMImplementationRegistry)

Example 37 with DOMImplementationLS

use of org.w3c.dom.ls.DOMImplementationLS in project syncope by apache.

the class XMLUtils method createXMLFile.

public static void createXMLFile(final InputStream sis, final String filePath) throws Exception {
    DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
    DOMImplementationLS domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS");
    LSInput lsinput = domImpl.createLSInput();
    lsinput.setByteStream(sis);
    LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    tf.newTransformer().transform(new DOMSource(parser.parse(lsinput)), new StreamResult(new File(filePath)));
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) StreamResult(javax.xml.transform.stream.StreamResult) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) LSInput(org.w3c.dom.ls.LSInput) DOMImplementationRegistry(org.w3c.dom.bootstrap.DOMImplementationRegistry) LSParser(org.w3c.dom.ls.LSParser) File(java.io.File)

Example 38 with DOMImplementationLS

use of org.w3c.dom.ls.DOMImplementationLS in project openj9 by eclipse.

the class PrefixJUnitResults method process.

private void process(File xmlFile) throws IOException, SAXException {
    File outputFile = getOutputFile(xmlFile);
    if (verbose) {
        log("Mapping " + xmlFile.getAbsolutePath() + " to " + outputFile.getAbsolutePath());
    }
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    Document doc = builder.parse(new InputSource(new FileReader(xmlFile)));
    /* Find the testsuite nodes and prefix the name element */
    NodeList testSuiteNodes = doc.getElementsByTagName("testsuite");
    if (testSuiteNodes.getLength() == 0) {
        log("Couldn't find testsuite node in " + xmlFile.getAbsolutePath());
    }
    for (int i = 0; i < testSuiteNodes.getLength(); i++) {
        Node thisTestSuite = testSuiteNodes.item(i);
        NamedNodeMap attributes = thisTestSuite.getAttributes();
        Attr nameNode = (Attr) attributes.getNamedItem("name");
        if (null == nameNode) {
            log("Couldn't find name attribute on testsuite element in " + xmlFile.getAbsolutePath());
            continue;
        }
        String oldValue = nameNode.getValue();
        nameNode.setValue(prefix + "." + oldValue);
    }
    /* Do the same for the testcase nodes */
    NodeList testCaseNodes = doc.getElementsByTagName("testcase");
    for (int i = 0; i < testCaseNodes.getLength(); i++) {
        Node thisTestCase = testCaseNodes.item(i);
        NamedNodeMap attributes = thisTestCase.getAttributes();
        Attr classNameNode = (Attr) attributes.getNamedItem("classname");
        if (null == classNameNode) {
            log("Couldn't find classname attribute on testcase element in " + xmlFile.getAbsolutePath());
            continue;
        }
        String oldValue = classNameNode.getValue();
        classNameNode.setValue(prefix + "." + oldValue);
    }
    /* Write out to new location */
    DOMImplementationLS ls = (DOMImplementationLS) builder.getDOMImplementation();
    LSSerializer serializer = ls.createLSSerializer();
    LSOutput xmlSink = ls.createLSOutput();
    xmlSink.setCharacterStream(new FileWriter(outputFile));
    serializer.write(doc, xmlSink);
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) NamedNodeMap(org.w3c.dom.NamedNodeMap) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) DOMImplementationLS(org.w3c.dom.ls.DOMImplementationLS) FileWriter(java.io.FileWriter) LSSerializer(org.w3c.dom.ls.LSSerializer) Document(org.w3c.dom.Document) Attr(org.w3c.dom.Attr) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileReader(java.io.FileReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) LSOutput(org.w3c.dom.ls.LSOutput) File(java.io.File)

Example 39 with DOMImplementationLS

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

the class XsltResponseQueueTransformer method transform.

@Override
public BinaryContent transform(SourceResponse upstreamResponse, Map<String, Serializable> arguments) throws CatalogTransformerException {
    LOGGER.debug("Transforming ResponseQueue with XSLT tranformer");
    long grandTotal = -1;
    try {
        DocumentBuilder builder = XML_UTILS.getSecureDocumentBuilder(true);
        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(TRANSFORMATION_FAILURE_MSG, 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(TRANSFORMATION_FAILURE_MSG, te);
            throw new CatalogTransformerException(TRANSFORMATION_FAILURE_MSG, 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) 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 40 with DOMImplementationLS

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

the class SAMLAuthenticationToken method getCredentialsAsString.

@Override
public String getCredentialsAsString() {
    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
            false);
            // xml-declaration
            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

DOMImplementationLS (org.w3c.dom.ls.DOMImplementationLS)54 LSSerializer (org.w3c.dom.ls.LSSerializer)43 Document (org.w3c.dom.Document)22 DOMImplementationRegistry (org.w3c.dom.bootstrap.DOMImplementationRegistry)21 LSOutput (org.w3c.dom.ls.LSOutput)18 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)14 IOException (java.io.IOException)13 DocumentBuilder (javax.xml.parsers.DocumentBuilder)13 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)12 Node (org.w3c.dom.Node)12 DOMImplementation (org.w3c.dom.DOMImplementation)10 Element (org.w3c.dom.Element)10 StringWriter (java.io.StringWriter)9 LSParser (org.w3c.dom.ls.LSParser)8 InputSource (org.xml.sax.InputSource)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 StringReader (java.io.StringReader)5 TransformerException (javax.xml.transform.TransformerException)5 NodeList (org.w3c.dom.NodeList)5 LSInput (org.w3c.dom.ls.LSInput)5