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

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

Introduction

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

Prototype

public static DOMImplementationRegistry newInstance()
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, ClassCastException 

Source Link

Document

Obtain a new instance of a DOMImplementationRegistry.

Usage

From source file:Main.java

public static String serializeNode(Node node) throws LSException, IllegalAccessException, DOMException,
        InstantiationException, ClassNotFoundException, ClassCastException {
    String serializedElement = null;
    if (node != null) {
        System.setProperty(DOMImplementationRegistry.PROPERTY,
                "org.apache.xerces.dom.DOMImplementationSourceImpl");
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        serializedElement = writer.writeToString(node);
    }//from  ww  w  . ja v a2s . c  om
    return serializedElement;
}

From source file:Main.java

public static String serializeElement(Element element) throws LSException, IllegalAccessException, DOMException,
        InstantiationException, ClassNotFoundException, ClassCastException {
    String serializedElement = null;
    if (element != null) {
        System.setProperty(DOMImplementationRegistry.PROPERTY,
                "org.apache.xerces.dom.DOMImplementationSourceImpl");
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        serializedElement = writer.writeToString(element);
    }//from  ww w. ja  v a2s .c  o  m
    return serializedElement;
}

From source file:Main.java

private static void serializeXML(Element doc, Writer writer, boolean addXmlDeclaration) throws IOException {
    try {//from  ww w .j  av  a 2 s. c  o  m
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer serializer = impl.createLSSerializer();
        DOMConfiguration config = serializer.getDomConfig();
        config.setParameter("xml-declaration", addXmlDeclaration);
        // config.setParameter("format-pretty-print", true);
        // config.setParameter("normalize-characters", true);
        LSOutput out = impl.createLSOutput();
        out.setCharacterStream(writer);
        serializer.write(doc, out);
    } catch (Throwable e) {
        throw new IOException(e.getMessage());
    }
}

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

protected String formatHtml(String html) throws MojoExecutionException {
    try {/* w  ww  .  ja va  2s. co  m*/
        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:com.lostinsoftware.xsdparser.XSDParser.java

private static XSDElement parseXSD(InputStream inputStream, List<String> elements, boolean allElements)
        throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException,
        ClassCastException {// www. java 2s. c o  m

    XSDElement mainElement = null;

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

    XSImplementation impl = (XSImplementation) registry.getDOMImplementation("XS-Loader");

    XSLoader schemaLoader = impl.createXSLoader(null);

    DOMConfiguration config = schemaLoader.getConfig();

    // create Error Handler
    DOMErrorHandler errorHandler = new XSDParser();

    // set error handler
    config.setParameter("error-handler", errorHandler);

    // set validation feature
    config.setParameter("validate", Boolean.TRUE);

    // parse document
    LSInput input = new DOMInputImpl();
    input.setByteStream(inputStream);
    XSModel model = schemaLoader.load(input);
    if (model != null) {
        // Main element
        XSElementDeclaration element = model.getElementDeclaration(elements.get(0), null);
        mainElement = new XSDElement();
        mainElement.setName(elements.get(0));
        mainElement.setXsDeclaration(element);
        processElement(mainElement, elements, allElements);
    }
    return mainElement;
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * Public default constructor that performs basic initialization
 *//*from w  w w .  j  ava  2  s  . co m*/
public SAMLDelegatedAuthenticationService() {
    DOMImplementationRegistry registry;
    try {
        registry = DOMImplementationRegistry.newInstance();
        domLoadSaveImpl = (DOMImplementationLS) registry.getDOMImplementation("LS");
    } catch (ClassCastException ex) {
        logger.error(
                "Unable to initialize XML serializer implementation.  Make sure that the correct jar files are present.",
                ex);
    } catch (ClassNotFoundException ex) {
        logger.error(
                "Unable to initialize XML serializer implementation.  Make sure that the correct jar files are present.",
                ex);
    } catch (InstantiationException ex) {
        logger.error(
                "Unable to initialize XML serializer implementation.  Make sure that the correct jar files are present.",
                ex);
    } catch (IllegalAccessException ex) {
        logger.error(
                "Unable to initialize XML serializer implementation.  Make sure that the correct jar files are present.",
                ex);
    }
}

From source file:com.haulmont.cuba.restapi.XMLConverter.java

@Override
public CommitRequest parseCommitRequest(String content) {
    try {/*from   w w w .  j  ava  2 s. c  o m*/
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS lsImpl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSParser requestConfigParser = lsImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

        // Set options on the parser
        DOMConfiguration config = requestConfigParser.getDomConfig();
        config.setParameter("validate", Boolean.TRUE);
        config.setParameter("element-content-whitespace", Boolean.FALSE);
        config.setParameter("comments", Boolean.FALSE);
        requestConfigParser.setFilter(new LSParserFilter() {
            @Override
            public short startElement(Element elementArg) {
                return LSParserFilter.FILTER_ACCEPT;
            }

            @Override
            public short acceptNode(Node nodeArg) {
                return StringUtils.isBlank(nodeArg.getTextContent()) ? LSParserFilter.FILTER_REJECT
                        : LSParserFilter.FILTER_ACCEPT;
            }

            @Override
            public int getWhatToShow() {
                return NodeFilter.SHOW_TEXT;
            }
        });
        LSInput lsInput = lsImpl.createLSInput();
        lsInput.setStringData(content);
        Document commitRequestDoc = requestConfigParser.parse(lsInput);
        Node rootNode = commitRequestDoc.getFirstChild();
        if (!"CommitRequest".equals(rootNode.getNodeName()))
            throw new IllegalArgumentException("Not a CommitRequest xml passed: " + rootNode.getNodeName());

        CommitRequest result = new CommitRequest();

        NodeList children = rootNode.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            String childNodeName = child.getNodeName();
            if ("commitInstances".equals(childNodeName)) {
                NodeList entitiesNodeList = child.getChildNodes();

                Set<String> commitIds = new HashSet<>(entitiesNodeList.getLength());
                for (int j = 0; j < entitiesNodeList.getLength(); j++) {
                    Node idNode = entitiesNodeList.item(j).getAttributes().getNamedItem("id");
                    if (idNode == null)
                        continue;

                    String id = idNode.getTextContent();
                    if (id.startsWith("NEW-"))
                        id = id.substring(id.indexOf('-') + 1);
                    commitIds.add(id);
                }

                result.setCommitIds(commitIds);
                result.setCommitInstances(parseNodeList(result, entitiesNodeList));
            } else if ("removeInstances".equals(childNodeName)) {
                NodeList entitiesNodeList = child.getChildNodes();

                List removeInstances = parseNodeList(result, entitiesNodeList);
                result.setRemoveInstances(removeInstances);
            } else if ("softDeletion".equals(childNodeName)) {
                result.setSoftDeletion(Boolean.parseBoolean(child.getTextContent()));
            }
        }
        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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);// ww w  .  j ava2  s.  com

    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:XMLUtils.java

public static InputStream getInputStream(Document doc) throws Exception {
    DOMImplementationLS impl = null;
    DOMImplementation docImpl = doc.getImplementation();
    // Try to get the DOMImplementation from doc first before
    // defaulting to the sun implementation.
    if (docImpl != null && docImpl.hasFeature("LS", "3.0")) {
        impl = (DOMImplementationLS) docImpl.getFeature("LS", "3.0");
    } else {/*w  w w .ja  va2  s.  c om*/
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        if (impl == null) {
            System.setProperty(DOMImplementationRegistry.PROPERTY,
                    "com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
            registry = DOMImplementationRegistry.newInstance();
            impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
        }
    }
    LSOutput output = impl.createLSOutput();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    output.setByteStream(byteArrayOutputStream);
    LSSerializer writer = impl.createLSSerializer();
    writer.write(doc, output);
    byte[] buf = byteArrayOutputStream.toByteArray();
    return new ByteArrayInputStream(buf);
}