Example usage for org.w3c.dom.ls DOMImplementationLS createLSParser

List of usage examples for org.w3c.dom.ls DOMImplementationLS createLSParser

Introduction

In this page you can find the example usage for org.w3c.dom.ls DOMImplementationLS createLSParser.

Prototype

public LSParser createLSParser(short mode, String schemaType) throws DOMException;

Source Link

Document

Create a new LSParser.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("XML 3.0 LS 3.0");
    if (impl == null) {
        System.out.println("No DOMImplementation found !");
        System.exit(0);//from w  w  w.  j  a  v  a  2s  . c  o  m
    }

    System.out.printf("DOMImplementationLS: %s\n", impl.getClass().getName());

    LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, "http://www.w3.org/TR/REC-xml");
    // http://www.w3.org/2001/XMLSchema
    System.out.printf("LSParser: %s\n", parser.getClass().getName());

    Document doc = parser.parseURI("");

    LSSerializer serializer = impl.createLSSerializer();
    LSOutput output = impl.createLSOutput();
    output.setEncoding("UTF-8");
    output.setByteStream(System.out);
    serializer.write(doc, output);
    System.out.println();
}

From source file:DOM3.java

public static void main(String[] argv) {

    if (argv.length == 0) {
        printUsage();/*w w  w  .j  a  v a 2  s.  c o  m*/
        System.exit(1);
    }

    try {

        // get DOM Implementation using DOM Registry
        System.setProperty(DOMImplementationRegistry.PROPERTY,
                "org.apache.xerces.dom.DOMXSImplementationSourceImpl");
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");

        // create DOMBuilder
        builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

        DOMConfiguration config = builder.getDomConfig();

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

        // create filter
        LSParserFilter filter = new DOM3();

        builder.setFilter(filter);

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

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

        // set schema language
        config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema");
        // config.setParameter("psvi",Boolean.TRUE);
        // config.setParameter("schema-type","http://www.w3.org/TR/REC-xml");

        // set schema location
        config.setParameter("schema-location", "personal.xsd");

        // parse document
        System.out.println("Parsing " + argv[0] + "...");
        Document doc = builder.parseURI(argv[0]);

        // set error handler on the Document
        config = doc.getDomConfig();

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

        // set validation feature
        config.setParameter("validate", Boolean.TRUE);
        config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema");
        // config.setParameter("schema-type","http://www.w3.org/TR/REC-xml");
        config.setParameter("schema-location", "data/personal.xsd");

        // remove comments from the document
        config.setParameter("comments", Boolean.FALSE);

        System.out.println("Normalizing document... ");
        doc.normalizeDocument();

        // create DOMWriter
        LSSerializer domWriter = impl.createLSSerializer();

        System.out.println("Serializing document... ");
        config = domWriter.getDomConfig();
        config.setParameter("xml-declaration", Boolean.FALSE);
        // config.setParameter("validate",errorHandler);

        // serialize document to standard output
        // domWriter.writeNode(System.out, doc);
        LSOutput dOut = impl.createLSOutput();
        dOut.setByteStream(System.out);
        domWriter.write(doc, dOut);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

private static Document parse(LSInput input, boolean validateIfSchema) {
    DOMImplementationLS impl = getDOMImpl();
    LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
    DOMConfiguration config = parser.getDomConfig();
    config.setParameter("element-content-whitespace", false);
    config.setParameter("namespaces", true);
    config.setParameter("validate-if-schema", validateIfSchema);
    return parser.parse(input);
}

From source file:javatojs.DomUtil.java

public static Document readDocument(String uri) {
    Document document = null;/*  w ww. jav  a 2  s.c  om*/
    try {
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();

        DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");

        LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

        System.out.println("In readDocument uri: " + uri);
        document = builder.parseURI(uri);
        if (document == null) {
            System.out.println("Null doc returned!!!!!!!!");
        }
        System.out.println("Read toc: \n " + document);
    } catch (Exception e) {
        System.out.println("ERROR reading toc: \n ");
        e.printStackTrace();
    }
    return document;
}

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  a  va 2 s  .com*/
 *
 * @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;/*from www . ja va  2s.com*/

    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:edu.ur.ir.ir_import.service.DefaultCollectionImportService.java

/**
 * Load the dspace collection information from the xml file.
 * @throws DuplicateNameException /*from   w  w  w . j av a  2s.  c om*/
 * 
 * @see edu.ur.dspace.load.CollectionImporter#getCollections(java.io.File)
 */
private void getCollections(File communityXmlFile, Repository repo, ZipFile zip)
        throws IOException, DuplicateNameException {
    if (log.isDebugEnabled()) {
        log.debug("get collections");
    }
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException(e);
    }

    DOMImplementation impl = builder.getDOMImplementation();
    DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSInput lsIn = domLs.createLSInput();
    LSParser parser = domLs.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

    lsIn.setEncoding("UTF-8");

    FileInputStream fileInputStream;
    try {
        fileInputStream = new FileInputStream(communityXmlFile);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e);
    }
    InputStreamReader inputStreamReader;
    try {
        inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }
    lsIn.setCharacterStream(inputStreamReader);

    Document doc = parser.parse(lsIn);
    Element root = doc.getDocumentElement();

    NodeList nodeList = root.getChildNodes();

    log.debug("node list length = " + nodeList.getLength());
    for (int index = 0; index < nodeList.getLength(); index++) {
        Node child = nodeList.item(index);
        importCollection(child, repo, zip);
    }
}

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

@Override
public CommitRequest parseCommitRequest(String content) {
    try {/*w ww .  j a  v  a  2 s  .c  om*/
        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.apache.syncope.core.logic.init.CamelRouteLoader.java

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 {//from  w w w .j a  v a 2  s .c om
            TransformerFactory tf = null;
            DOMImplementationLS domImpl = null;
            NodeList routeNodes;
            if (IS_JBOSS) {
                tf = TransformerFactory.newInstance();
                tf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                dbFactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document doc = dBuilder.parse(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);
        }
    }
}

From source file:org.apache.syncope.core.provisioning.camel.SyncopeCamelContext.java

private void loadContext(final Collection<String> routes) {
    try {/*from  ww w .  ja  v a 2 s .  com*/
        DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
        DOMImplementationLS domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS");
        LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);

        JAXBContext jaxbContext = JAXBContext.newInstance(Constants.JAXB_CONTEXT_PACKAGES);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        List<RouteDefinition> routeDefs = new ArrayList<>();
        for (String route : routes) {
            try (InputStream input = IOUtils.toInputStream(route, StandardCharsets.UTF_8)) {
                LSInput lsinput = domImpl.createLSInput();
                lsinput.setByteStream(input);

                Node routeElement = parser.parse(lsinput).getDocumentElement();
                routeDefs.add(unmarshaller.unmarshal(routeElement, RouteDefinition.class).getValue());
            }
        }
        camelContext.addRouteDefinitions(routeDefs);
    } catch (Exception e) {
        LOG.error("While loading Camel context {}", e);
        throw new CamelException(e);
    }
}