Example usage for javax.xml.xpath XPathConstants NODE

List of usage examples for javax.xml.xpath XPathConstants NODE

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODE.

Prototype

QName NODE

To view the source code for javax.xml.xpath XPathConstants NODE.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Usage

From source file:org.eclipse.mdht.dita.ui.util.DitaUtil.java

private static String getFileNameFromMap(String ditaMapPath) {

    StringBuffer fileName = new StringBuffer();

    try {//from   w  ww. j  av  a2  s .  c om

        FileInputStream ditaMapStream;

        ditaMapStream = new FileInputStream(ditaMapPath);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);

        factory.setValidating(false);

        factory.setFeature("http://xml.org/sax/features/namespaces", false);
        factory.setFeature("http://xml.org/sax/features/validation", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        DocumentBuilder builder;

        Document doc = null;

        XPathExpression expr = null;

        builder = factory.newDocumentBuilder();

        doc = builder.parse(new InputSource(ditaMapStream));

        XPathFactory xFactory = XPathFactory.newInstance();

        XPath xpath = xFactory.newXPath();

        expr = xpath.compile("//bookmap/bookmeta/prodinfo/prodname");

        Node prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);

        if (prodNameNode != null) {

            fileName.append(prodNameNode.getTextContent());

            expr = xpath.compile("//bookmap/bookmeta/prodinfo/vrmlist");

            Element vrmlistNode = (Element) expr.evaluate(doc, XPathConstants.NODE);

            if (vrmlistNode != null) {
                NodeList versions = vrmlistNode.getElementsByTagName("vrm");
                if (versions.getLength() > 0) {

                    NamedNodeMap versionAttributes = versions.item(0).getAttributes();
                    Attr releaseAttr = (Attr) versionAttributes.getNamedItem("release");

                    if (releaseAttr != null) {
                        fileName.append(String.format("_%s", releaseAttr.getValue()));
                    }

                    Attr versionAttr = (Attr) versionAttributes.getNamedItem("version");

                    if (versionAttr != null) {
                        fileName.append(String.format("_%s", versionAttr.getValue()));
                    }
                }
            }
        } else {
            expr = xpath.compile("/bookmap");
            prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
            if (prodNameNode != null) {
                Node node = prodNameNode.getAttributes().getNamedItem("id");
                if (node != null) {
                    fileName.append(node.getTextContent());
                }
            } else {
                expr = xpath.compile("/map");
                prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
                if (prodNameNode != null) {
                    Node node = prodNameNode.getAttributes().getNamedItem("title");
                    if (node != null) {
                        fileName.append(node.getTextContent());
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println();
    }
    return fileName.toString();
}

From source file:org.eclipse.thym.android.core.adt.AndroidProjectGenerator.java

private void updateAppName(String appName) throws CoreException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);// w  w  w  .j a v  a2  s. c  o m
    DocumentBuilder db;

    try {
        db = dbf.newDocumentBuilder();
        IPath stringsPath = new Path(getDestination().toString()).append(DIR_RES).append(DIR_VALUES)
                .append(FILE_XML_STRINGS);
        File strings = stringsPath.toFile();
        Document configDocument = db.parse(strings);
        XPath xpath = XPathFactory.newInstance().newXPath();

        try {
            XPathExpression expr = xpath.compile("//string[@name=\"app_name\"]");
            Node node = (Node) expr.evaluate(configDocument, XPathConstants.NODE);
            node.setTextContent(appName);
            configDocument.setXmlStandalone(true);
            Source source = new DOMSource(configDocument);
            StreamResult result = new StreamResult(strings);
            // Write the DOM document to the file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer xformer = transformerFactory.newTransformer();
            xformer.transform(source, result);

        } catch (XPathExpressionException e) {//We continue because this affects the displayed app name
                                              // which is not a show stopper during development
            AndroidCore.log(IStatus.ERROR, "Error when updating the application name", e);
        } catch (TransformerConfigurationException e) {
            AndroidCore.log(IStatus.ERROR, "Error when updating the application name", e);
        } catch (TransformerException e) {
            AndroidCore.log(IStatus.ERROR, "Error when updating the application name", e);
        }

    } catch (ParserConfigurationException e) {
        throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID,
                "Parser error when parsing /res/values/strings.xml", e));
    } catch (SAXException e) {
        throw new CoreException(
                new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Parsing error on /res/values/strings.xml", e));
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID,
                "IO error when parsing /res/values/strings.xml", e));
    }
}

From source file:org.eclipse.thym.blackberry.core.bdt.BlackBerryProjectGenerator.java

private void updateAppName(String appName) throws CoreException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from w ww  .j a va 2s  .co m
    DocumentBuilder db;

    try {
        db = dbf.newDocumentBuilder();
        IPath stringsPath = new Path(getDestination().toString()).append(DIR_RES).append(DIR_VALUES)
                .append(FILE_XML_STRINGS);
        File strings = stringsPath.toFile();
        Document configDocument = db.parse(strings);
        XPath xpath = XPathFactory.newInstance().newXPath();

        try {
            XPathExpression expr = xpath.compile("//string[@name=\"app_name\"]");
            Node node = (Node) expr.evaluate(configDocument, XPathConstants.NODE);
            node.setTextContent(appName);

            configDocument.setXmlStandalone(true);

            Source source = new DOMSource(configDocument);

            StreamResult result = new StreamResult(strings);

            // Write the DOM document to the file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer xformer = transformerFactory.newTransformer();

            xformer.transform(source, result);

        } catch (XPathExpressionException e) {//We continue because this affects the displayed app name
                                              // which is not a show stopper during development
            BlackBerryCore.log(IStatus.ERROR, "Error when updating the application name", e);
        } catch (TransformerConfigurationException e) {
            BlackBerryCore.log(IStatus.ERROR, "Error when updating the application name", e);
        } catch (TransformerException e) {
            BlackBerryCore.log(IStatus.ERROR, "Error when updating the application name", e);
        }

    } catch (ParserConfigurationException e) {
        throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID,
                "Parser error when parsing /res/values/strings.xml", e));
    } catch (SAXException e) {
        throw new CoreException(
                new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Parsing error on /res/values/strings.xml", e));
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID,
                "IO error when parsing /res/values/strings.xml", e));
    }
}

From source file:org.eclipse.thym.core.plugin.test.InstallActionsTest.java

@Test
public void testXMLConfigFileActionInstall() throws FileNotFoundException, IOException, CoreException,
        SAXException, ParserConfigurationException, XPathExpressionException {

    final File target = TestUtils.createTempFile("AndroidManifest.xml");
    final String xml = "<config-file target=\"AndroidManifest.xml\" parent=\"/manifest\">"
            + "<uses-permission android:name=\"android.permission.BLUETOOTH\" />"
            + "<uses-permission android:name=\"android.permission.BLUETOOTH_ADMIN\" />" + "</config-file >";
    final String parentExpression = "/manifest";

    XMLConfigFileAction action = new XMLConfigFileAction(target, parentExpression, xml);
    action.install();//from   ww  w.  j a  va 2s. co  m

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = db.parse(target);
    Document node = db.parse(new InputSource(new StringReader(xml)));

    XPath xpath = XPathFactory.newInstance().newXPath();
    Node parentNode = (Node) xpath.evaluate(parentExpression, doc, XPathConstants.NODE);
    assertNotNull(parentNode);

    NodeList alienChildren = node.getDocumentElement().getChildNodes();

    Node[] importedNodes = new Node[alienChildren.getLength()];
    for (int i = 0; i < alienChildren.getLength(); i++) {
        importedNodes[i] = doc.importNode(alienChildren.item(i), true);
    }

    NodeList childNodes = parentNode.getChildNodes();
    int found = 0;
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node current = childNodes.item(i);
        for (int j = 0; j < importedNodes.length; j++) {
            if (current.isEqualNode(importedNodes[j])) {
                found++;
            }
        }
    }
    assertEquals(importedNodes.length, found); // found all imported nodes
}

From source file:org.eclipse.thym.core.plugin.test.InstallActionsTest.java

@Test
public void testXMLConfigFileActionUnInstall()
        throws IOException, CoreException, ParserConfigurationException, SAXException, XPathException {
    final File target = TestUtils.createTempFile("AndroidManifest.xml");
    final String xml = "<config-file target=\"AndroidManifest.xml\" parent=\"/manifest\">"
            + "<uses-permission android:name=\"android.permission.INTERNET\" />"
            + "<uses-permission android:name=\"android.permission.RECEIVE_SMS\" />" + "</config-file >";
    final String parentExpression = "/manifest";

    XMLConfigFileAction action = new XMLConfigFileAction(target, parentExpression, xml);
    action.unInstall();/*from www.j  a v  a2s .co  m*/

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = db.parse(target);
    Document node = db.parse(new InputSource(new StringReader(xml)));

    XPath xpath = XPathFactory.newInstance().newXPath();
    Node parentNode = (Node) xpath.evaluate(parentExpression, doc, XPathConstants.NODE);
    assertNotNull(parentNode);

    NodeList alienChildren = node.getDocumentElement().getChildNodes();

    Node[] importedNodes = new Node[alienChildren.getLength()];
    for (int i = 0; i < alienChildren.getLength(); i++) {
        importedNodes[i] = doc.importNode(alienChildren.item(i), true);
    }

    NodeList childNodes = parentNode.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node current = childNodes.item(i);
        for (int j = 0; j < importedNodes.length; j++) {
            assertFalse("Found a node that is not suppposed to be here", current.isEqualNode(importedNodes[j]));
        }
    }
}

From source file:org.entrystore.harvesting.oaipmh.jobs.ListRecordsJob.java

private static Node getMetadataNode(Element el, String metadataType) throws XPathExpressionException {
    initXpath();//  w w w . j a  v  a 2s  .c o  m
    if (metadataType.equals("oai_dc")) {
        expr = xpath.compile("oai:metadata/oai_dc:dc");
    } else if (metadataType.equals("rdn_dc")) {
        expr = xpath.compile("oai:metadata/rdn_dc:rdndc");
    } else if (metadataType.equals("oai_lom")) {
        expr = xpath.compile("oai:metadata/lom:lom");
    }
    return (Node) expr.evaluate(el, XPathConstants.NODE);
}

From source file:org.inaturalist.android.GuideXML.java

/**
 * Initialize the GuideXML class with a local file XML path
 * @param context the app context//from w ww  . j a  v  a2  s.c  o  m
 * @param guideId the guide identifier
 * @param path the local file name of the guide XML file
 */
public GuideXML(Context context, String guideId, String path) {
    mContext = context;
    mGuideId = guideId;

    FileReader fr = null;
    try {
        fr = new FileReader(path);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return;
    }
    InputSource inputSource = new InputSource(fr);

    mTagCounts = new HashMap<String, Integer>();
    mTags = new HashMap<String, Set<String>>();

    try {
        // Read root node so we won't re-parse the XML file every time we evaluate an XPath
        XPath xpath = XPathFactory.newInstance().newXPath();
        setRootNode((Node) xpath.evaluate("/", inputSource, XPathConstants.NODE));

        // Parse all taxon tags
        parseTags();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

}

From source file:org.infoscoop.service.ProxyConfService.java

public void updateProxyConfHeaders(String id, Collection<String> headers, Collection<String> sendingCookies) {
    Proxyconf proxyconf = proxyConfDAO.select();

    try {/*  www  . jav a  2 s  .  co  m*/
        XPath xpath = XPathFactory.newInstance().newXPath();
        Element element = proxyconf.getElement();
        Document document = element.getOwnerDocument();

        Element caseNode = (Element) xpath.evaluate("*[@id='" + id + "']", element, XPathConstants.NODE);
        if (caseNode == null)
            throw new RuntimeException("proxyConf[@id=" + id + "] not found");

        Node headersNode = (Node) xpath.evaluate("headers", caseNode, XPathConstants.NODE);
        if (headersNode != null)
            caseNode.removeChild(headersNode);

        if (headers != null) {
            headersNode = document.createElement("headers");
            caseNode.appendChild(headersNode);

            for (String header : headers) {
                Element headerNode = document.createElement("header");
                headerNode.appendChild(document.createTextNode(header));
                headersNode.appendChild(headerNode);
            }
        }

        Node sendingCookiesNode = (Node) xpath.evaluate("sendingcookies", caseNode, XPathConstants.NODE);
        if (sendingCookiesNode != null)
            caseNode.removeChild(sendingCookiesNode);

        if (sendingCookies != null) {
            sendingCookiesNode = document.createElement("sendingcookies");
            caseNode.appendChild(sendingCookiesNode);

            for (String cookie : sendingCookies) {
                Element sendingCookieNode = document.createElement("cookie");
                sendingCookieNode.appendChild(document.createTextNode(cookie));
                sendingCookiesNode.appendChild(sendingCookieNode);
            }
        }

        proxyconf.setElement(element);

        proxyConfDAO.update(proxyconf);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java

/**
   When user preferences are stored in the database for changes made to
   an incorporated node the node id can not be used because it does not
   represent a row in the up_layout_struct table for the user. The plfid
   must be used. Null will never be returned unless the layout or
   processing has really been screwed up. This is because changes made to
   the user prefs calls UserPrefsHandler which generates a shadow node in
   the db and sets the plfid of that node into the corresponding node in
   the PLF prior to the call to update the user prefs in the db.
 *//*from w  ww.j a  v  a 2 s .c o  m*/
private String getPlfId(Document PLF, String incdId) {
    Element element = null;
    try {
        final XPathFactory fac = XPathFactory.newInstance();
        final XPath xp = fac.newXPath();
        element = (Element) xp.evaluate("//*[@ID = '" + incdId + "']", PLF, XPathConstants.NODE);
    } catch (final XPathExpressionException xpee) {
        throw new RuntimeException(xpee);
    }
    if (element == null) {
        this.log.warn("The specified folderId was not found in the user's PLF:  " + incdId);
        return null;
    }
    final Attr attr = element.getAttributeNode(Constants.ATT_PLF_ID);
    if (attr == null) {
        return null;
    }
    return attr.getValue();
}

From source file:org.jboss.errai.ui.rebind.TranslationServiceGenerator.java

/**
 * Gets the root node of the template (within a potentially larger template HTML file).
 * //from  ww  w.  j  a v a 2  s . c om
 * @param templateNode
 * @param templateFragment
 */
private static Element getTemplateRootNode(Document templateNode, String templateFragment) {
    try {
        XPath xpath = XPathFactory.newInstance().newXPath();
        Element documentElement = templateNode.getDocumentElement();
        if (templateFragment == null || templateFragment.trim().length() == 0) {
            return (Element) xpath.evaluate("//body", documentElement, XPathConstants.NODE);
        } else {
            return (Element) xpath.evaluate("//*[@data-field='" + templateFragment + "']", documentElement,
                    XPathConstants.NODE);
        }
    } catch (XPathExpressionException e) {
        return null;
    }
}