Search in sources :

Example 56 with DocumentBuilderFactory

use of javax.xml.parsers.DocumentBuilderFactory in project qi4j-sdk by Qi4j.

the class RssReaderTest method testReadRssFeed.

@Test
public void testReadRssFeed() {
    Client client = new Client(Protocol.HTTPS);
    Reference ref = new Reference("https://github.com/Qi4j/qi4j-sdk/commits/develop.atom");
    ContextResourceClientFactory contextResourceClientFactory = module.newObject(ContextResourceClientFactory.class, client);
    contextResourceClientFactory.registerResponseReader(new ResponseReader() {

        @Override
        public Object readResponse(Response response, Class<?> resultType) throws ResourceException {
            if (resultType.equals(Document.class)) {
                try {
                    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                    documentBuilderFactory.setNamespaceAware(false);
                    return documentBuilderFactory.newDocumentBuilder().parse(response.getEntity().getStream());
                } catch (Exception e) {
                    throw new ResourceException(e);
                }
            }
            return null;
        }
    });
    contextResourceClientFactory.setErrorHandler(new ErrorHandler().onError(ErrorHandler.RECOVERABLE_ERROR, new ResponseHandler() {

        @Override
        public HandlerCommand handleResponse(Response response, ContextResourceClient client) {
            System.out.println(">> REFRESH on recoverable error: " + response.getStatus());
            return refresh();
        }
    }));
    crc = contextResourceClientFactory.newClient(ref);
    crc.onResource(new ResultHandler<Document>() {

        Iterator<Node> itemNodes;

        @Override
        public HandlerCommand handleResult(Document result, ContextResourceClient client) {
            try {
                final XPath xPath = XPathFactory.newInstance().newXPath();
                System.out.println("== " + xPath.evaluate("feed/title", result) + " ==");
                final NodeList nodes = (NodeList) xPath.evaluate("feed/entry", result, XPathConstants.NODESET);
                List<Node> items = new ArrayList<>();
                for (int i = 0; i < nodes.getLength(); i++) {
                    items.add(nodes.item(i));
                }
                itemNodes = items.iterator();
                return processEntry(xPath);
            } catch (XPathExpressionException e) {
                throw new ResourceException(e);
            }
        }

        private HandlerCommand processEntry(final XPath xPath) throws XPathExpressionException {
            if (!itemNodes.hasNext()) {
                return null;
            }
            Node item = itemNodes.next();
            String title = xPath.evaluate("title", item);
            String detailUrl = xPath.evaluate("link/@href", item);
            System.out.println("-- " + title + " --");
            System.out.println("-- " + detailUrl + " --");
            return processEntry(xPath);
        }
    });
    crc.start();
}
Also used : ContextResourceClientFactory(org.qi4j.library.rest.client.api.ContextResourceClientFactory) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) ResponseHandler(org.qi4j.library.rest.client.spi.ResponseHandler) XPathExpressionException(javax.xml.xpath.XPathExpressionException) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) HandlerCommand(org.qi4j.library.rest.client.api.HandlerCommand) ResourceException(org.restlet.resource.ResourceException) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) ContextResourceClient(org.qi4j.library.rest.client.api.ContextResourceClient) Client(org.restlet.Client) ContextResourceClient(org.qi4j.library.rest.client.api.ContextResourceClient) XPath(javax.xml.xpath.XPath) ErrorHandler(org.qi4j.library.rest.client.api.ErrorHandler) Reference(org.restlet.data.Reference) NodeList(org.w3c.dom.NodeList) XPathExpressionException(javax.xml.xpath.XPathExpressionException) ResourceException(org.restlet.resource.ResourceException) AssemblyException(org.qi4j.bootstrap.AssemblyException) Response(org.restlet.Response) ResponseReader(org.qi4j.library.rest.client.spi.ResponseReader) AbstractQi4jTest(org.qi4j.test.AbstractQi4jTest) Test(org.junit.Test)

Example 57 with DocumentBuilderFactory

use of javax.xml.parsers.DocumentBuilderFactory in project tinker by Tencent.

the class AndroidParser method parse.

private void parse() throws ParserException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    Document document;
    try {
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        document = builder.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
        Node manifestNode = document.getElementsByTagName("manifest").item(0);
        NodeList nodes = manifestNode.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            String nodeName = node.getNodeName();
            if (nodeName.equals("application")) {
                NodeList children = node.getChildNodes();
                for (int j = 0; j < children.getLength(); j++) {
                    Node child = children.item(j);
                    String childName = child.getNodeName();
                    switch(childName) {
                        case "service":
                            services.add(getAndroidComponent(child, TYPE_SERVICE));
                            break;
                        case "activity":
                            activities.add(getAndroidComponent(child, TYPE_ACTIVITY));
                            break;
                        case "receiver":
                            receivers.add(getAndroidComponent(child, TYPE_BROADCAST_RECEIVER));
                            break;
                        case "provider":
                            providers.add(getAndroidComponent(child, TYPE_CONTENT_PROVIDER));
                            break;
                        case "meta-data":
                            NamedNodeMap attributes = child.getAttributes();
                            metaDatas.put(getAttribute(attributes, "android:name"), getAttribute(attributes, "android:value"));
                            break;
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new ParserException("Error parsing AndroidManifest.xml", e);
    }
}
Also used : ParserException(net.dongliu.apk.parser.exception.ParserException) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) NamedNodeMap(org.w3c.dom.NamedNodeMap) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) IOException(java.io.IOException) ParserException(net.dongliu.apk.parser.exception.ParserException) ParseException(java.text.ParseException)

Example 58 with DocumentBuilderFactory

use of javax.xml.parsers.DocumentBuilderFactory in project tinker by Tencent.

the class JavaXmlUtil method getDocumentBuilder.

/**
     * get document builder
     *
     * @return DocumentBuilder
     */
private static DocumentBuilder getDocumentBuilder() {
    DocumentBuilder documentBuilder = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (Exception e) {
        throw new JavaXmlUtilException(e);
    }
    return documentBuilder;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder)

Example 59 with DocumentBuilderFactory

use of javax.xml.parsers.DocumentBuilderFactory in project malmo by Microsoft.

the class SchemaHelper method getRootNodeName.

/** Retrieve the name of the root node in an XML string.
     * @param xml The XML string to parse.
     * @return The name of the root node, or null if parsing failed.
     */
public static String getRootNodeName(String xml) {
    String rootNodeName = null;
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setExpandEntityReferences(false);
        DocumentBuilder dBuilder = dbf.newDocumentBuilder();
        InputSource inputSource = new InputSource(new StringReader(xml));
        Document doc = dBuilder.parse(inputSource);
        doc.getDocumentElement().normalize();
        rootNodeName = doc.getDocumentElement().getNodeName();
    } catch (SAXException e) {
        System.out.println("SAX exception: " + e);
    } catch (IOException e) {
        System.out.println("IO exception: " + e);
    } catch (ParserConfigurationException e) {
        System.out.println("ParserConfiguration exception: " + e);
    }
    return rootNodeName;
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) StringReader(java.io.StringReader) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException)

Example 60 with DocumentBuilderFactory

use of javax.xml.parsers.DocumentBuilderFactory in project Mycat-Server by MyCATApache.

the class FirewallConfig method updateToFile.

public static synchronized void updateToFile(String host, List<UserConfig> userConfigs) throws Exception {
    LOGGER.debug("set white host:" + host + "user:" + userConfigs);
    String filename = SystemConfig.getHomePath() + File.separator + "conf" + File.separator + "server.xml";
    //String filename = "E:\\MyProject\\Mycat-Server\\src\\main\\resources\\server.xml";
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(new IgnoreDTDEntityResolver());
    Document xmldoc = builder.parse(filename);
    Element whitehost = (Element) xmldoc.getElementsByTagName("whitehost").item(0);
    Element firewall = (Element) xmldoc.getElementsByTagName("firewall").item(0);
    if (firewall == null) {
        firewall = xmldoc.createElement("firewall");
        Element root = xmldoc.getDocumentElement();
        root.appendChild(firewall);
        if (whitehost == null) {
            whitehost = xmldoc.createElement("whitehost");
            firewall.appendChild(whitehost);
        }
    }
    for (UserConfig userConfig : userConfigs) {
        String user = userConfig.getName();
        Element hostEle = xmldoc.createElement("host");
        hostEle.setAttribute("host", host);
        hostEle.setAttribute("user", user);
        whitehost.appendChild(hostEle);
    }
    TransformerFactory factory2 = TransformerFactory.newInstance();
    Transformer former = factory2.newTransformer();
    String systemId = xmldoc.getDoctype().getSystemId();
    if (systemId != null) {
        former.setOutputProperty(javax.xml.transform.OutputKeys.DOCTYPE_SYSTEM, systemId);
    }
    former.transform(new DOMSource(xmldoc), new StreamResult(new File(filename)));
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) File(java.io.File)

Aggregations

DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)759 DocumentBuilder (javax.xml.parsers.DocumentBuilder)622 Document (org.w3c.dom.Document)526 Element (org.w3c.dom.Element)244 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)232 NodeList (org.w3c.dom.NodeList)209 IOException (java.io.IOException)197 InputSource (org.xml.sax.InputSource)193 SAXException (org.xml.sax.SAXException)173 Node (org.w3c.dom.Node)145 StringReader (java.io.StringReader)142 Test (org.junit.Test)117 File (java.io.File)86 DOMSource (javax.xml.transform.dom.DOMSource)77 ByteArrayInputStream (java.io.ByteArrayInputStream)72 InputStream (java.io.InputStream)63 StreamResult (javax.xml.transform.stream.StreamResult)50 ArrayList (java.util.ArrayList)47 SAXParseException (org.xml.sax.SAXParseException)46 Transformer (javax.xml.transform.Transformer)44