Example usage for org.w3c.dom.bootstrap DOMImplementationRegistry getDOMImplementation

List of usage examples for org.w3c.dom.bootstrap DOMImplementationRegistry getDOMImplementation

Introduction

In this page you can find the example usage for org.w3c.dom.bootstrap DOMImplementationRegistry getDOMImplementation.

Prototype

public DOMImplementation getDOMImplementation(final String features) 

Source Link

Document

Return the first implementation that has the desired features, or null if none is found.

Usage

From source file:com.espertech.esper.event.xml.XSDSchemaMapper.java

private static XSModel readSchemaInternal(String schemaResource, String schemaText)
        throws IllegalAccessException, InstantiationException, ClassNotFoundException, ConfigurationException,
        URISyntaxException {// w w w  .j a va2 s .  c o m
    LSInputImpl input = null;
    String baseURI = null;
    if (schemaResource != null) {
        URL url = ResourceLoader.resolveClassPathOrURLResource("schema", schemaResource);
        baseURI = url.toURI().toString();
    } else {
        input = new LSInputImpl(schemaText);
    }

    // Uses Xerxes internal classes
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    registry.addSource(new DOMXSImplementationSourceImpl());
    Object xsImplementation = registry.getDOMImplementation("XS-Loader");
    if (xsImplementation == null) {
        throw new ConfigurationException(
                "Failed to retrieve XS-Loader implementation from registry obtained via DOMImplementationRegistry.newInstance, please check that registry.getDOMImplementation(\"XS-Loader\") returns an instance");
    }
    if (!JavaClassHelper.isImplementsInterface(xsImplementation.getClass(), XSImplementation.class)) {
        String message = "The XS-Loader instance returned by the DOM registry class '"
                + xsImplementation.getClass().getName() + "' does not implement the interface '"
                + XSImplementation.class.getName()
                + "'; If you have a another Xerces distribution in your classpath please ensure the classpath order loads the JRE Xerces distribution or set the DOMImplementationRegistry.PROPERTY system property";
        throw new ConfigurationException(message);
    }
    XSImplementation impl = (XSImplementation) xsImplementation;
    XSLoader schemaLoader = impl.createXSLoader(null);
    XSModel xsModel;
    if (input != null) {
        xsModel = schemaLoader.load(input);
    } else {
        xsModel = schemaLoader.loadURI(baseURI);
    }

    if (xsModel == null) {
        throw new ConfigurationException("Failed to read schema via URL '" + schemaResource + '\'');
    }

    return xsModel;
}

From source file:Main.java

public static String prettyPrint(Document document) {
    // Pretty-prints a DOM document to XML using DOM Load and Save's
    // LSSerializer.
    // Note that the "format-pretty-print" DOM configuration parameter can
    // only be set in JDK 1.6+.

    DOMImplementationRegistry domImplementationRegistry;
    try {//from  w w  w.  ja  v a 2s .  c  om
        domImplementationRegistry = DOMImplementationRegistry.newInstance();
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | ClassCastException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    DOMImplementation domImplementation = document.getImplementation();
    if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) {
        /*DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation
          .getFeature("LS", "3.0");*/
        DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementationRegistry
                .getDOMImplementation("LS");

        LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
        DOMConfiguration domConfiguration = lsSerializer.getDomConfig();
        if (domConfiguration.canSetParameter("format-pretty-print", Boolean.TRUE)) {
            lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
            LSOutput lsOutput = domImplementationLS.createLSOutput();
            lsOutput.setEncoding("UTF-8");
            StringWriter stringWriter = new StringWriter();
            lsOutput.setCharacterStream(stringWriter);
            lsSerializer.write(document, lsOutput);
            return stringWriter.toString();
        } else {
            throw new RuntimeException("DOMConfiguration 'format-pretty-print' parameter isn't settable.");
        }
    } else {
        throw new RuntimeException("DOM 3.0 LS and/or DOM 2.0 Core not supported.");
    }
}

From source file:eu.europa.esig.dss.DSSXMLUtils.java

/**
 * Document Object Model (DOM) Level 3 Load and Save Specification See: http://www.w3.org/TR/2004/REC-DOM-Level-3-LS-20040407/
 *
 * @param xmlNode The node to be serialized.
 * @return//from   w ww  .j  a  v a 2s .c om
 */
public static byte[] serializeNode(final Node xmlNode) {

    try {

        final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        final LSSerializer writer = impl.createLSSerializer();

        final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        final LSOutput output = impl.createLSOutput();
        output.setByteStream(buffer);
        writer.write(xmlNode, output);

        final byte[] bytes = buffer.toByteArray();
        return bytes;
    } catch (Exception e) {
        throw new DSSException(e);
    }
}

From source file:fr.fastconnect.factory.tibco.bw.codereview.pages.CodeReviewIndexMojo.java

protected String formatHtml(String html) throws MojoExecutionException {
    try {//from   ww  w.ja v  a2  s.  c  om
        InputSource src = new InputSource(new StringReader(html));
        Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src)
                .getDocumentElement();
        Boolean keepDeclaration = Boolean.valueOf(html.startsWith("<?xml"));

        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();

        writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
        writer.getDomConfig().setParameter("xml-declaration", keepDeclaration);

        return writer.writeToString(document);
    } catch (Exception e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:it.unibas.spicy.persistence.xml.operators.GenerateXSDNodeTree.java

private XSModel initModel(String fileName) throws Exception {
    System.setProperty(DOMImplementationRegistry.PROPERTY,
            "org.apache.xerces.dom.DOMXSImplementationSourceImpl");
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    XSImplementation impl = (XSImplementation) registry.getDOMImplementation("XS-Loader");
    XSLoader schemaLoader = impl.createXSLoader(null);
    DOMConfiguration config = schemaLoader.getConfig();
    config.setParameter("validate", Boolean.TRUE);
    return schemaLoader.loadURI(fileName);
}

From source file:no.difi.sdp.client.asice.signature.CreateSignatureTest.java

private String prettyPrint(final Signature signature)
        throws TransformerException, ClassNotFoundException, InstantiationException, IllegalAccessException {
    StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(signature.getBytes()));
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    DOMResult outputTarget = new DOMResult();
    transformer.transform(xmlSource, outputTarget);

    final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
    final LSSerializer writer = impl.createLSSerializer();

    writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
    writer.getDomConfig().setParameter("xml-declaration", Boolean.FALSE);

    return writer.writeToString(outputTarget.getNode());
}

From source file:com.msopentech.odatajclient.engine.performance.BasicPerfTest.java

@Test
public void writeAtomViaLowerlevelLibs() throws ParserConfigurationException, ClassNotFoundException,
        InstantiationException, IllegalAccessException {

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.newDocument();

    final Element entry = doc.createElement("entry");
    entry.setAttribute("xmlns", "http://www.w3.org/2005/Atom");
    entry.setAttribute("xmlns:m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
    entry.setAttribute("xmlns:d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
    entry.setAttribute("xmlns:gml", "http://www.opengis.net/gml");
    entry.setAttribute("xmlns:georss", "http://www.georss.org/georss");
    doc.appendChild(entry);// w  w  w .ja  v  a 2 s. c  o  m

    final Element category = doc.createElement("category");
    category.setAttribute("term", "Microsoft.Test.OData.Services.AstoriaDefaultService.Customer");
    category.setAttribute("scheme", "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme");
    entry.appendChild(category);

    final Element properties = doc.createElement("m:properties");
    entry.appendChild(properties);

    final Element name = doc.createElement("d:Name");
    name.setAttribute("m:type", "Edm.String");
    name.appendChild(doc.createTextNode("A name"));
    properties.appendChild(name);

    final Element customerId = doc.createElement("d:CustomerId");
    customerId.setAttribute("m:type", "Edm.Int32");
    customerId.appendChild(doc.createTextNode("0"));
    properties.appendChild(customerId);

    final Element bci = doc.createElement("d:BackupContactInfo");
    bci.setAttribute("m:type",
            "Collection(Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails)");
    properties.appendChild(bci);

    final Element topelement = doc.createElement("d:element");
    topelement.setAttribute("m:type", "Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails");
    bci.appendChild(topelement);

    final Element altNames = doc.createElement("d:AlternativeNames");
    altNames.setAttribute("m:type", "Collection(Edm.String)");
    topelement.appendChild(altNames);

    final Element element1 = doc.createElement("d:element");
    element1.setAttribute("m:type", "Edm.String");
    element1.appendChild(doc.createTextNode("myname"));
    altNames.appendChild(element1);

    final Element emailBag = doc.createElement("d:EmailBag");
    emailBag.setAttribute("m:type", "Collection(Edm.String)");
    topelement.appendChild(emailBag);

    final Element element2 = doc.createElement("d:element");
    element2.setAttribute("m:type", "Edm.String");
    element2.appendChild(doc.createTextNode("myname@mydomain.com"));
    emailBag.appendChild(element2);

    final Element contactAlias = doc.createElement("d:ContactAlias");
    contactAlias.setAttribute("m:type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases");
    topelement.appendChild(contactAlias);

    final Element altNames2 = doc.createElement("d:AlternativeNames");
    altNames2.setAttribute("m:type", "Collection(Edm.String)");
    contactAlias.appendChild(altNames2);

    final Element element3 = doc.createElement("d:element");
    element3.setAttribute("m:type", "Edm.String");
    element3.appendChild(doc.createTextNode("myAlternativeName"));
    altNames2.appendChild(element3);

    final StringWriter writer = new StringWriter();

    final DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
    final DOMImplementationLS impl = (DOMImplementationLS) reg.getDOMImplementation("LS");
    final LSSerializer serializer = impl.createLSSerializer();
    final LSOutput lso = impl.createLSOutput();
    lso.setCharacterStream(writer);
    serializer.write(doc, lso);

    assertFalse(writer.toString().isEmpty());
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java

@Override
public Document extendSignatures(Document document, Document originalData, SignatureParameters parameters)
        throws IOException {
    InputStream input = document.openStream();

    if (this.tspSource == null) {
        throw new ConfigurationException(MSG.CONFIGURE_TSP_SERVER);
    }/*  w  w w  .  ja v a2s.com*/

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = db.parse(input);

        NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (signatureNodeList.getLength() == 0) {
            throw new RuntimeException(
                    "Impossible to perform the extension of the signature, the document is not signed.");
        }
        for (int i = 0; i < signatureNodeList.getLength(); i++) {
            Element signatureEl = (Element) signatureNodeList.item(i);
            extendSignatureTag(signatureEl, originalData, parameters.getSignatureFormat());
        }

        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(buffer);
        writer.write(doc, output);

        return new InMemoryDocument(buffer.toByteArray());

    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException e) {
        throw new IOException("Cannot parse document", e);
    } catch (ClassCastException e) {
        throw new IOException("Cannot save document", e);
    } catch (ClassNotFoundException e) {
        throw new IOException("Cannot save document", e);
    } catch (InstantiationException e) {
        throw new IOException("Cannot save document", e);
    } catch (IllegalAccessException e) {
        throw new IOException("Cannot save document", e);
    } finally {
        if (input != null) {
            input.close();
        }
    }

}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java

@Override
public Document extendSignature(Object signatureId, Document document, Document originalData,
        SignatureParameters parameters) throws IOException {
    InputStream input = document.openStream();

    if (this.tspSource == null) {
        throw new ConfigurationException(MSG.CONFIGURE_TSP_SERVER);
    }/*ww  w.ja  v a  2  s .co  m*/

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = db.parse(input);

        NodeList signatureNodeList = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (signatureNodeList.getLength() == 0) {
            throw new RuntimeException(
                    "Impossible to perform the extension of the signature, the document is not signed.");
        }
        for (int i = 0; i < signatureNodeList.getLength(); i++) {
            Element signatureEl = (Element) signatureNodeList.item(i);
            String sid = signatureEl.getAttribute("Id");
            if (signatureId.equals(sid)) {
                extendSignatureTag(signatureEl, originalData, parameters.getSignatureFormat());
            }
        }

        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(buffer);
        writer.write(doc, output);

        return new InMemoryDocument(buffer.toByteArray());

    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException e) {
        throw new IOException("Cannot parse document", e);
    } catch (ClassCastException e) {
        throw new IOException("Cannot save document", e);
    } catch (ClassNotFoundException e) {
        throw new IOException("Cannot save document", e);
    } catch (InstantiationException e) {
        throw new IOException("Cannot save document", e);
    } catch (IllegalAccessException e) {
        throw new IOException("Cannot save document", e);
    } finally {
        if (input != null) {
            input.close();
        }
    }

}

From source file:gov.nih.nci.cacis.common.util.ExtractSchematron.java

/**
 * Creates new instance of the schematron extractor.
 * /*from   ww w . j  a va 2  s  .c om*/
 * @throws ClassCastException if there is an error getting a SchemaLoader
 * @throws ClassNotFoundException if there is an error getting a SchemaLoader
 * @throws InstantiationException if there is an error getting a SchemaLoader
 * @throws IllegalAccessException if there is an error getting a SchemaLoader
 * @throws TransformerFactoryConfigurationError if there is an error getting a serializer
 * @throws TransformerConfigurationException if there is an error getting a serializer
 * @throws XPathExpressionException if there is an error compiling expressions
 */
public ExtractSchematron()
        throws ClassCastException, ClassNotFoundException, InstantiationException, IllegalAccessException,
        TransformerConfigurationException, TransformerFactoryConfigurationError, XPathExpressionException {
    final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    final XSImplementation impl = (XSImplementation) registry.getDOMImplementation("XS-Loader");

    this.dfactory = DocumentBuilderFactory.newInstance();
    this.dfactory.setNamespaceAware(true);

    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new SchNamespaceContext());

    this.serializer = TransformerFactory.newInstance().newTransformer();
    this.serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    this.patternExpr = xpath.compile("//sch:pattern");

    this.schemaLoader = impl.createXSLoader(null);
}