Example usage for javax.xml.xpath XPathFactory newXPath

List of usage examples for javax.xml.xpath XPathFactory newXPath

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newXPath.

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:org.kuali.mobility.maps.service.LocationServiceImpl.java

private List<Location> buildLocationsByCampusCodeFromXml(String groupCode, String xml) {
    List<Location> locations = new ArrayList<Location>();
    MapsGroup mapsGroup = this.getMapsGroupByCode(groupCode);
    if (mapsGroup != null) {
        if (!"".equals(xml)) {
            XPathFactory factory = XPathFactory.newInstance();
            XPath xPath = factory.newXPath();
            DocumentBuilderFactory dbf;
            try {
                dbf = DocumentBuilderFactory.newInstance();
                Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
                //Get all markers from XML
                NodeList nodes = (NodeList) xPath.evaluate("/markers/marker", doc, XPathConstants.NODESET);
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    if (node != null) {
                        NamedNodeMap nodeMap = node.getAttributes();
                        Location loc = new Location();
                        //                     loc.setCampus(campusCode);
                        // Code should be updated to assign an MIU-specific code
                        if (isNotNullNotEmptyAttribute(nodeMap, "miu")) {
                            loc.setCode(nodeMap.getNamedItem("miu").getNodeValue());
                        }//from   w ww.j  a  va 2  s .  co m
                        if (isNotNullNotEmptyAttribute(nodeMap, "scd")) {
                            loc.setShortCode(nodeMap.getNamedItem("scd").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "cd")) {
                            loc.setBuildingCode(nodeMap.getNamedItem("cd").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "nm")) {
                            loc.setName(nodeMap.getNamedItem("nm").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "snm")) {
                            loc.setShortName(nodeMap.getNamedItem("snm").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "cty")) {
                            loc.setCity(nodeMap.getNamedItem("cty").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "sta")) {
                            loc.setState(nodeMap.getNamedItem("sta").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "str")) {
                            loc.setStreet(nodeMap.getNamedItem("str").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "zip")) {
                            loc.setZip(nodeMap.getNamedItem("zip").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "active")) {
                            Boolean active = new Boolean(nodeMap.getNamedItem("active").getNodeValue());
                            loc.setActive(active);
                        } else {
                            loc.setActive(true);
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "override")) {
                            Boolean override = new Boolean(nodeMap.getNamedItem("override").getNodeValue());
                            loc.setOverride(override);
                        } else {
                            loc.setOverride(false);
                        }

                        try {
                            loc.setLatitude(new Double(nodeMap.getNamedItem("lat").getNodeValue()));
                        } catch (Exception e) {
                        }
                        try {
                            loc.setLongitude(new Double(nodeMap.getNamedItem("lng").getNodeValue()));
                        } catch (Exception e) {
                        }

                        Set<MapsGroup> mapsGroups = new HashSet<MapsGroup>();
                        try {
                            if (isNotNullNotEmptyAttribute(nodeMap, "grp")) {
                                MapsGroup mapsGroupForThisLocation = this
                                        .getMapsGroupByCode(nodeMap.getNamedItem("grp").getNodeValue());
                                if (mapsGroupForThisLocation != null) {
                                    mapsGroups.add(mapsGroupForThisLocation);
                                } else {
                                    //                              LOG.info("Location " + loc.getName() + " (" + loc.getShortName() + ") assigned to default group because group " + nodeMap.getNamedItem("grp").getNodeValue() + " does not exist.");
                                    mapsGroups.add(mapsGroup);
                                }
                            } else {
                                mapsGroups.add(mapsGroup);
                            }
                        } catch (Exception e) {
                        }
                        loc.setMapsGroups(mapsGroups);
                        locations.add(loc);
                    }
                }
            } catch (Exception e) {
                //               LOG.info("Error loading data to group code: " + groupCode);
            }
        }
    } else {
        //         LOG.info("Error loading data to group code due to missing group: " + groupCode);
    }
    return locations;
}

From source file:org.openmrs.module.rheashradapter.web.controller.RHEApatientController.java

private Map<String, String> identifyPreUpdateIdentifiers(String message) {
    Map<String, String> preUpdateIdentifiers = new HashMap<String, String>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from  w  w w  .  j  ava 2 s.  co  m
    org.w3c.dom.Document doc = null;
    XPathExpression expr = null;
    XPathExpression exprIdType = null;

    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(new InputSource(new StringReader(message)));

        XPathFactory xFactory = XPathFactory.newInstance();

        XPath xpath = xFactory.newXPath();
        expr = xpath.compile("//preUpdateIdentifiers/preUpdateIdentifier/identifier/text()");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        XPath xpathIdType = xFactory.newXPath();
        exprIdType = xpathIdType.compile(
                "//preUpdateIdentifiers/preUpdateIdentifier/identifierDomain/universalIdentifierTypeCode/text()");
        Object resultIdType = exprIdType.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        NodeList nodesIdType = (NodeList) resultIdType;

        for (int i = 0; i < nodes.getLength(); i++) {
            preUpdateIdentifiers.put(nodesIdType.item(i).getTextContent(), nodes.item(i).getTextContent());
        }

    } catch (XPathExpressionException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return preUpdateIdentifiers;
}

From source file:org.openmrs.module.rheashradapter.web.controller.RHEApatientController.java

private Map<String, String> identifyPostUpdateIdentifiers(String message) {
    Map<String, String> postUpdateIdentifiers = new HashMap<String, String>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from w ww  . j a  v  a 2 s .  co m*/
    org.w3c.dom.Document doc = null;
    XPathExpression expr = null;
    XPathExpression exprIdType = null;

    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(new InputSource(new StringReader(message)));

        XPathFactory xFactory = XPathFactory.newInstance();

        XPath xpath = xFactory.newXPath();
        expr = xpath.compile("//postUpdateIdentifiers/postUpdateIdentifier/identifier/text()");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        XPath xpathIdType = xFactory.newXPath();
        exprIdType = xpathIdType.compile(
                "//postUpdateIdentifiers/postUpdateIdentifier/identifierDomain/universalIdentifierTypeCode/text()");
        Object resultIdType = exprIdType.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        NodeList nodesIdType = (NodeList) resultIdType;

        for (int i = 0; i < nodes.getLength(); i++) {
            postUpdateIdentifiers.put(nodesIdType.item(i).getTextContent(), nodes.item(i).getTextContent());
        }

    } catch (XPathExpressionException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return postUpdateIdentifiers;
}

From source file:com.peter.mavenrunner.MavenRunnerTopComponent.java

void refreshTree(boolean showEmptyNode) {
    log("refreshTree");
    try {/*from   www  .ja  va2 s . c om*/
        root.removeAllChildren();

        String searchString = searchTextField.getText().trim();

        for (Project p : OpenProjects.getDefault().getOpenProjects()) {
            ProjectInformation projectInformation = p.getLookup().lookup(ProjectInformation.class);
            log(projectInformation.getDisplayName());
            if (!new File(p.getProjectDirectory().getPath() + File.separator + "pom.xml").exists()) {
                continue;
            }
            MyTreeNode node = new MyTreeNode(projectInformation.getDisplayName(), null, null, null, false,
                    "project", p, projectInformation);
            node.icon = projectInformation.getIcon();

            // load goals from nbactions.xml
            if (!hideDefaultGoalButton.isSelected()) {
                if (new File(p.getProjectDirectory().getPath() + File.separator + "nbactions.xml").exists()) {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document doc = builder
                            .parse(p.getProjectDirectory().getPath() + File.separator + "nbactions.xml");
                    XPathFactory xPathfactory = XPathFactory.newInstance();
                    XPath xpath = xPathfactory.newXPath();
                    XPathExpression expr = xpath.compile("//action");
                    NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
                    for (int x = 0; x < nl.getLength(); x++) {
                        NodeList childs = nl.item(x).getChildNodes();
                        String displayName = null;
                        String actionName = null;
                        String goals = "";
                        String profiles = "";
                        List<String> properties = new ArrayList<String>();
                        boolean skipTest = false;

                        for (int y = 0; y < childs.getLength(); y++) {
                            //log(childs.item(y).getNodeName());
                            if (childs.item(y).getNodeName().equals("displayName")) {
                                displayName = childs.item(y).getTextContent();
                            } else if (childs.item(y).getNodeName().equals("actionName")) {
                                actionName = childs.item(y).getTextContent();
                            } else if (childs.item(y).getNodeName().equals("goals")) {
                                NodeList goalNodes = childs.item(y).getChildNodes();
                                for (int z = 0; z < goalNodes.getLength(); z++) {
                                    if (goalNodes.item(z).getNodeName().equals("goal")) {
                                        goals += goalNodes.item(z).getTextContent() + " ";
                                    }
                                }
                            } else if (childs.item(y).getNodeName().equals("activatedProfiles")) {
                                NodeList profileNodes = childs.item(y).getChildNodes();
                                for (int z = 0; z < profileNodes.getLength(); z++) {
                                    if (profileNodes.item(z).getNodeName().equals("activatedProfile")) {
                                        profiles += profileNodes.item(z).getTextContent() + " ";
                                    }
                                }
                            } else if (childs.item(y).getNodeName().equals("properties")) {
                                NodeList profileNodes = childs.item(y).getChildNodes();
                                for (int z = 0; z < profileNodes.getLength(); z++) {
                                    if (!profileNodes.item(z).getNodeName().equals("#text")) {
                                        properties.add(">" + profileNodes.item(z).getNodeName() + "="
                                                + profileNodes.item(z).getTextContent().trim());
                                        if (profileNodes.item(z).getNodeName().equals("skipTests")) {
                                            skipTest = Boolean
                                                    .parseBoolean(profileNodes.item(z).getTextContent().trim());
                                        }
                                    }
                                }
                            }
                        }
                        //                     log(displayName == null ? actionName : displayName + "=" + goals + ", " + profiles + ", " + skipTest);
                        //                     for (String pp : properties) {
                        //                        log("   " + pp);
                        //                     }
                        //                     log("--------");
                        MyTreeNode goalNode = new MyTreeNode(displayName == null ? actionName : displayName,
                                goals, profiles, properties, skipTest, "default goal", node.project,
                                node.projectInformation);
                        if ((searchString.equals("")
                                || goalNode.name.toLowerCase().contains(searchString.toLowerCase()))
                                && !goalNode.name.trim().equals("") && goalNode.type.equals("default goal")) {
                            node.add(goalNode);
                            goalNode.icon = (new javax.swing.ImageIcon(
                                    getClass().getResource("/com/peter/mavenrunner/star.png")));
                        }
                    }
                }
            }
            // end load goals from nbactions.xml

            // load goals
            try {
                String key = node.projectInformation.getDisplayName();
                String value = NbPreferences.forModule(this.getClass()).get("data", null);
                //log("value=" + value);
                data = fromString(value);
                if (data == null) {
                    data = new Hashtable<String, ArrayList<PersistData>>();
                    //log("  create new data");
                }
                if (data.get(key) == null) {
                    data.put(key, new ArrayList<PersistData>());
                    //log("  add " + key + " to data");
                }
                ArrayList<PersistData> persistData = data.get(key);
                if (persistData != null) {
                    for (PersistData n : persistData) {
                        if ((searchString.equals("")
                                || n.name.toLowerCase().contains(searchString.toLowerCase()))
                                && !n.name.trim().equals("") && n.type.equals("goal")) {
                            node.add(new MyTreeNode(n.name, n.goals, n.profile, n.properties, n.skipTests,
                                    n.type, node.project, node.projectInformation));
                        }
                    }
                }
            } catch (Exception ex) {
                log(ExceptionUtils.getStackTrace(ex));
                // old version of data throws here
                data = new Hashtable<String, ArrayList<PersistData>>();
                NbPreferences.forModule(this.getClass()).put("data", toString(data));
            }
            // load goals end

            if (showEmptyNode || node.getChildCount() > 0) {
                root.add(node);
            }
        }
    } catch (Exception ex) {
        log(ExceptionUtils.getStackTrace(ex));
    }

    treeModel.nodeStructureChanged(root);
    expandAll(projectTree, true);
}

From source file:de.mpg.mpdl.inge.xmltransforming.TestBase.java

/**
 * Delivers the value of one distinct node in an <code>org.w3c.dom.Document</code>.
 * //from   w  w  w . ja v  a2  s .c o  m
 * @param document The <code>org.w3c.dom.Document</code>
 * @param xpathExpression The XPath expression as string
 * 
 * @return The value of the node
 * 
 * @throws TransformerException Thrown when the transformation failed
 */
protected String getValue(Document document, String xpathExpression) throws TransformerException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    try {
        return xPath.evaluate(xpathExpression, document);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:erwins.util.repack.xml.XMLBuilder.java

/**
 * Return the result of evaluating an XPath query on the builder's DOM
 * using the given namespace. Returns null if the query finds nothing,
 * or finds a node that does not match the type specified by returnType.
 *
 * @param xpath// w  w  w  . j a  v a  2  s .  c  om
 * an XPath expression
 * @param type
 * the type the XPath is expected to resolve to, e.g:
 * {@link XPathConstants#NODE}, {@link XPathConstants#NODESET},
 * {@link XPathConstants#STRING}.
 * @param nsContext
 * a mapping of prefixes to namespace URIs that allows the XPath expression
 * to use namespaces, or null for a non-namespaced document.
 *
 * @return
 * a builder node representing the first Element that matches the
 * XPath expression.
 *
 * @throws XPathExpressionException
 * If the XPath is invalid, or if does not resolve to at least one
 * {@link Node#ELEMENT_NODE}.
 */
public Object xpathQuery(String xpath, QName type, NamespaceContext nsContext) throws XPathExpressionException {
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xPath = xpathFactory.newXPath();
    if (nsContext != null) {
        xPath.setNamespaceContext(nsContext);
    }
    XPathExpression xpathExp = xPath.compile(xpath);
    try {
        return xpathExp.evaluate(this.xmlNode, type);
    } catch (IllegalArgumentException e) {
        // Thrown if item found does not match expected type
        return null;
    }
}

From source file:com.rapidminer.tools.Tools.java

/**
 * Reads a text file into a single string. Process files created with RapidMiner 5.2.008 or
 * earlier will be read with the system encoding (for compatibility reasons); all other files
 * will be read with UTF-8 encoding./*from   www.  j av a  2s .  c o m*/
 * */
public static String readTextFile(File file) throws IOException {
    FileInputStream inStream = new FileInputStream(file);

    // due to a bug in pre-5.2.009, process files were stored in System encoding instead of
    // UTF-8. So we have to check the process version, and if it's less than 5.2.009 we have
    // to retrieve the file again with System encoding.
    // If anything goes wrong while parsing the version number, we continue with the old
    // method. If something goes wrong, the file is either not utf-8 encoded (so the old
    // method will probably work), or it is not a valid process file (which will also be
    // detected by the old method).
    boolean useFallback = false;
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document processXmlDocument = documentBuilder.parse(inStream);
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();
        String versionString = xPath.evaluate("/process/@version", processXmlDocument);
        VersionNumber version = new VersionNumber(versionString);
        if (version.isAtMost(5, 2, 8)) {
            useFallback = true;
        }
    } catch (XPathExpressionException e) {
        useFallback = true;
    } catch (SAXException e) {
        useFallback = true;
    } catch (ParserConfigurationException e) {
        useFallback = true;
    } catch (IOException e) {
        useFallback = true;
    } catch (NumberFormatException e) {
        useFallback = true;
    }

    InputStreamReader reader = null;

    try {
        inStream = new FileInputStream(file);
        if (useFallback) {
            // default reader (as in old versions)
            reader = new InputStreamReader(inStream);
        } else {
            // utf8 reader
            reader = new InputStreamReader(inStream, XMLImporter.PROCESS_FILE_CHARSET);
        }

        return readTextFile(reader);
    } finally {
        try {
            inStream.close();
        } catch (IOException e) {
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:erwins.util.repack.xml.XMLBuilder.java

/**
 * Find and delete from the underlying Document any text nodes that
 * contain nothing but whitespace, such as newlines and tab or space
 * characters used to indent or pretty-print an XML document.
 *
 * Uses approach I documented on StackOverflow:
 * http://stackoverflow.com/a/979606/4970
 *
 * @return/*from w  w w .j  a  va 2 s  .c  om*/
 * a builder node at the same location as before the operation.
 * @throws XPathExpressionException
 */
public XMLBuilder stripWhitespaceOnlyTextNodes() throws XPathExpressionException {
    XPathFactory xpathFactory = XPathFactory.newInstance();
    // XPath to find empty text nodes.
    XPathExpression xpathExp = xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");
    NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(this.getDocument(), XPathConstants.NODESET);

    // Remove each empty text node from document.
    for (int i = 0; i < emptyTextNodes.getLength(); i++) {
        Node emptyTextNode = emptyTextNodes.item(i);
        emptyTextNode.getParentNode().removeChild(emptyTextNode);
    }
    return this;
}

From source file:net.firejack.platform.api.content.ContentServiceTest.java

@Test
public void exportImportCollectionTest() {
    Folder folder = createFolder(domain.getId());

    Collection collection = new Collection();
    collection.setName(time + "-collection");
    collection.setParentId(folder.getId());
    collection.setType("COLLECTION");
    collection.setDescription("Some Description");

    ServiceResponse<RegistryNodeTree> response2 = OPFEngine.ContentService.createCollection(collection);
    Assert.assertTrue("Collection should be created.", response2.isSuccess());

    RegistryNodeTree registryNodeTree2 = response2.getItem();
    Assert.assertNotNull("Should not be null.", registryNodeTree2);
    collection.setId(registryNodeTree2.getId());

    ServiceResponse<FileInfo> response3 = OPFEngine.ContentService
            .exportCollectionArchiveFile(collection.getId());
    FileInfo fileInfo = response3.getItem();
    Assert.assertNotNull("Should not be null.", fileInfo);

    File contentArchive;/*from   w  w  w . java2  s .c o m*/
    try {
        File tempDir = FileUtils.getTempDirectory();
        contentArchive = FileUtils.create(tempDir, "content.zip");
        InputStream stream = fileInfo.getStream();
        FileUtils.writeToFile(contentArchive, stream);
        IOUtils.closeQuietly(stream);

        ArchiveUtils.unZIP(contentArchive, tempDir);

        File contentXml = FileUtils.create(tempDir, "content.xml");

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document document = factory.newDocumentBuilder().parse(contentXml);
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xpath = xPathFactory.newXPath();
        Object evaluate = xpath.evaluate("/content/collection", document, XPathConstants.NODE);
        String collectionName = (String) xpath.evaluate("@name", evaluate, XPathConstants.STRING);
        Assert.assertEquals("Exported collection should be equal name.", collection.getName(), collectionName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    ServiceResponse response4 = OPFEngine.ContentService.deleteCollection(collection.getId());
    Assert.assertTrue("Collection should be deleted.", response4.isSuccess());

    try {
        InputStream contentStream = FileUtils.openInputStream(contentArchive);
        ServiceResponse<FileInfo> response5 = OPFEngine.ContentService
                .importCollectionArchiveFile(contentStream);
        Assert.assertTrue("Import should be completed.", response5.isSuccess());
        IOUtils.closeQuietly(contentStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    ServiceResponse<Collection> response6 = OPFEngine.ContentService
            .readCollectionsByLikeLookup(folder.getLookup());
    Assert.assertTrue("Collections should be retrieved.", response6.isSuccess());

    Collection collection2 = response6.getItem();
    Assert.assertNotNull("Should not be null.", collection2);
    Assert.assertEquals("Should be the same name.", collection.getName(), collection2.getName());

    deleteFolder(folder);
}