Example usage for org.w3c.dom.ls LSInput setStringData

List of usage examples for org.w3c.dom.ls LSInput setStringData

Introduction

In this page you can find the example usage for org.w3c.dom.ls LSInput setStringData.

Prototype

public void setStringData(String stringData);

Source Link

Document

String data to parse.

Usage

From source file:Main.java

public static Document parse(String s, boolean validateIfSchema) {
    DOMImplementationLS impl = getDOMImpl();
    LSInput input = impl.createLSInput();
    input.setStringData(s);
    return parse(input, validateIfSchema);
}

From source file:Main.java

/**
 * This method converts xml string to DOM Document
 *
 * @param xmlString//from www. ja va2s  .  c  o m
 *            XML string @return DOM Document @throws Exception @throws
 */
public static Document loadXmlFromString(String xmlString) throws Exception {
    LSParser builder = getDOMImplementationLS().createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
    LSInput input = getDOMImplementationLS().createLSInput();
    input.setStringData(xmlString);
    return builder.parse(input);
}

From source file:Main.java

/**
 * Normalize and pretty-print XML so that it can be compared using string
 * compare. The following code does the following: - Removes comments -
 * Makes sure attributes are ordered consistently - Trims every element -
 * Pretty print the document/*from   w  w w  . j  ava2 s.  c o m*/
 *
 * @param xml The XML to be normalized
 * @return The equivalent XML, but now normalized
 */
public static String normalizeXML(String xml) throws Exception {
    // Remove all white space adjoining tags ("trim all elements")
    xml = xml.replaceAll("\\s*<", "<");
    xml = xml.replaceAll(">\\s*", ">");

    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS domLS = (DOMImplementationLS) registry.getDOMImplementation("LS");
    LSParser lsParser = domLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

    LSInput input = domLS.createLSInput();
    input.setStringData(xml);
    Document document = lsParser.parse(input);

    LSSerializer lsSerializer = domLS.createLSSerializer();
    lsSerializer.getDomConfig().setParameter("comments", Boolean.FALSE);
    lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
    return lsSerializer.writeToString(document);
}

From source file:Main.java

private static Element convertXmlToElementWorker(String xml) throws Exception {
    Element element = null;// w w w.j av a 2  s  .  c o  m

    System.setProperty(DOMImplementationRegistry.PROPERTY, "org.apache.xerces.dom.DOMImplementationSourceImpl");
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
    LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS,
            "http://www.w3.org/2001/XMLSchema");
    LSInput lsInput = impl.createLSInput();
    lsInput.setStringData(xml);
    Document doc = parser.parse(lsInput);
    if (doc != null) {
        element = doc.getDocumentElement();
    }
    return element;
}

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

@Override
public CommitRequest parseCommitRequest(String content) {
    try {/*from  w  ww .j  ava 2s.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:org.alfresco.web.forms.xforms.SchemaUtil.java

public static XSModel parseSchema(final Document schemaDocument, final boolean failOnError)
        throws FormBuilderException {
    try {/*ww w.  ja  va2 s  . c o  m*/
        // Get DOM Implementation using DOM Registry
        System.setProperty(DOMImplementationRegistry.PROPERTY,
                "org.apache.xerces.dom.DOMXSImplementationSourceImpl");

        final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

        final DOMImplementationLS lsImpl = (DOMImplementationLS) registry
                .getDOMImplementation("XML 1.0 LS 3.0");
        if (lsImpl == null) {
            throw new FormBuilderException("unable to create DOMImplementationLS using " + registry);
        }
        final LSInput in = lsImpl.createLSInput();
        in.setStringData(XMLUtil.toString(schemaDocument));

        final XSImplementation xsImpl = (XSImplementation) registry.getDOMImplementation("XS-Loader");
        final XSLoader schemaLoader = xsImpl.createXSLoader(null);
        final DOMConfiguration config = (DOMConfiguration) schemaLoader.getConfig();
        final LinkedList<DOMError> errors = new LinkedList<DOMError>();
        config.setParameter("error-handler", new DOMErrorHandler() {
            public boolean handleError(final DOMError domError) {
                errors.add(domError);
                return true;
            }
        });

        final XSModel result = schemaLoader.load(in);
        if (failOnError && errors.size() != 0) {
            final HashSet<String> messages = new HashSet<String>();
            StringBuilder message = null;
            for (DOMError e : errors) {
                message = new StringBuilder();
                final DOMLocator dl = e.getLocation();
                if (dl != null) {
                    message.append("at line ").append(dl.getLineNumber()).append(" column ")
                            .append(dl.getColumnNumber());
                    if (dl.getRelatedNode() != null) {
                        message.append(" node ").append(dl.getRelatedNode().getNodeName());
                    }
                    message.append(": ").append(e.getMessage());
                }
                messages.add(message.toString());
            }

            message = new StringBuilder();
            message.append(messages.size() > 1 ? "errors" : "error").append(" parsing schema: \n");
            for (final String s : messages) {
                message.append(s).append("\n");
            }

            throw new FormBuilderException(message.toString());
        }

        if (result == null) {
            throw new FormBuilderException("invalid schema");
        }
        return result;
    } catch (ClassNotFoundException x) {
        throw new FormBuilderException(x);
    } catch (InstantiationException x) {
        throw new FormBuilderException(x);
    } catch (IllegalAccessException x) {
        throw new FormBuilderException(x);
    }
}

From source file:org.globus.wsrf.tools.wsdl.WSDLPreprocessor.java

private static XSModel loadSchema(Element schema, Definition def) {
    // add namespaces from definition element
    Map definitionNameSpaces = def.getNamespaces();
    Set nameSpaces = definitionNameSpaces.entrySet();
    Iterator nameSpacesIterator = nameSpaces.iterator();

    while (nameSpacesIterator.hasNext()) {
        Entry nameSpaceEntry = (Entry) nameSpacesIterator.next();
        if (!"".equals((String) nameSpaceEntry.getKey())
                && !schema.hasAttributeNS("http://www.w3.org/2000/xmlns/", (String) nameSpaceEntry.getKey())) {
            Attr nameSpace = schema.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/",
                    "xmlns:" + nameSpaceEntry.getKey());
            nameSpace.setValue((String) nameSpaceEntry.getValue());
            schema.setAttributeNode(nameSpace);
        }/*  ww w  .  j  a  v  a2s  .co  m*/
    }

    LSInput schemaInput = new DOMInputImpl();
    schemaInput
            .setStringData("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + XmlUtils.getElementAsString(schema));
    log.info("Loading schema in types section of definition " + def.getDocumentBaseURI());
    schemaInput.setSystemId(def.getDocumentBaseURI());
    XMLSchemaLoader schemaLoader = new XMLSchemaLoader();
    XSModel schemaModel = schemaLoader.load(schemaInput);
    log.info("Done loading");
    return schemaModel;
}

From source file:org.phenotips.tools.PropertyDisplayerTest.java

/** Displaying phenotypes in edit mode should output hidden empty values which allow unselecting all values. */
@Test//w ww  .  j  a  v  a 2s.co  m
public void testDisplayOutputsHiddenEmptyValues() {
    FormData configuration = new FormData();
    configuration.setMode(DisplayMode.Edit);
    com.xpn.xwiki.api.Document doc = Mockito.mock(com.xpn.xwiki.api.Document.class);
    configuration.setDocument(doc);
    Mockito.when(doc.getObjects("PhenoTips.PhenotypeMetaClass"))
            .thenReturn(new Vector<com.xpn.xwiki.api.Object>());
    configuration.setPositiveFieldName("PhenoTips.PatientClass_0_phenotype");
    Collection<Map<String, ?>> data = Collections.emptySet();
    Vocabulary ontologyService = Mockito.mock(Vocabulary.class);
    Mockito.doReturn(new LinkedList<VocabularyTerm>()).when(ontologyService)
            .search(Matchers.anyMapOf(String.class, Object.class));

    PropertyDisplayer displayer = new PropertyDisplayer(data, configuration, ontologyService);
    String output = displayer.display();
    Assert.assertTrue(StringUtils.isNotBlank(output));
    LSInput input = this.domls.createLSInput();
    input.setStringData("<div>" + output + "</div>");
    Document xmldoc = XMLUtils.parse(input);
    NodeList inputs = xmldoc.getElementsByTagName("input");
    Assert.assertEquals(1, inputs.getLength());
    Element positive = (Element) inputs.item(0);
    Assert.assertEquals("PhenoTips.PatientClass_0_phenotype", positive.getAttribute("name"));
    Assert.assertEquals("", positive.getAttribute("value"));
    Assert.assertEquals("hidden", positive.getAttribute("type"));

    configuration.setNegativeFieldName("PhenoTips.PatientClass_0_negative_phenotype");
    displayer = new PropertyDisplayer(data, configuration, ontologyService);
    output = displayer.display();
    Assert.assertTrue(StringUtils.isNotBlank(output));
    input = this.domls.createLSInput();
    input.setStringData("<div>" + output + "</div>");
    xmldoc = XMLUtils.parse(input);
    inputs = xmldoc.getElementsByTagName("input");
    Assert.assertEquals(2, inputs.getLength());
    positive = (Element) inputs.item(0);
    Assert.assertEquals("PhenoTips.PatientClass_0_phenotype", positive.getAttribute("name"));
    Assert.assertEquals("", positive.getAttribute("value"));
    Assert.assertEquals("hidden", positive.getAttribute("type"));
    Element negative = (Element) inputs.item(1);
    Assert.assertEquals("PhenoTips.PatientClass_0_negative_phenotype", negative.getAttribute("name"));
    Assert.assertEquals("", negative.getAttribute("value"));
    Assert.assertEquals("hidden", negative.getAttribute("type"));

    configuration.setMode(DisplayMode.View);
    displayer = new PropertyDisplayer(data, configuration, ontologyService);
    output = displayer.display();
    Assert.assertTrue(StringUtils.isBlank(output));
}