Example usage for javax.xml.xpath XPathConstants NODESET

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

Introduction

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

Prototype

QName NODESET

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

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Maps to Java org.w3c.dom.NodeList .

Usage

From source file:org.eclipse.lyo.testsuite.oslcv2.ServiceProviderXmlTests.java

@Test
public void prefixDefinitionsAreValid() throws XPathExpressionException {
    //Get all the prefix definitions
    NodeList prefixes = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_v2:PrefixDefinition", doc,
            XPathConstants.NODESET);

    for (int i = 0; i < prefixes.getLength(); i++) {
        NodeList subNodes = (NodeList) OSLCUtils.getXPath().evaluate("./*", prefixes.item(i),
                XPathConstants.NODESET);
        int prefixCount = 0;
        int baseCount = 0;
        //Check all the children of this prefix definition
        for (int j = 0; j < subNodes.getLength(); j++) {
            Node pChild = subNodes.item(j);
            if (pChild.getLocalName() == null) {
                continue;
            }//from   w ww .  j av  a2s  .com
            if (pChild.getLocalName().equals("prefix")
                    && pChild.getNamespaceURI().equals(OSLCConstants.OSLC_V2)) {
                prefixCount++;
            }
            if (pChild.getLocalName().equals("prefixBase")
                    && pChild.getNamespaceURI().equals(OSLCConstants.OSLC_V2)) {
                baseCount++;
            }
        }
        //Make sure the prefix definition had 1 prefix and 1 prefixBase
        assertEquals(1, prefixCount);
        assertEquals(1, baseCount);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.xml.XmlReaderXPath.java

private void ensureIdValidity(Node node) {
    NodeList idNodes = null;/*from ww  w  .jav a2s. c  om*/
    try {
        idNodes = (NodeList) compiledIdXPath.evaluate(node, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        // Already checked in initialize(), should not happen.
        getUimaContext().getLogger().log(Level.WARNING, e.getLocalizedMessage());
        return;
    }

    if (idNodes.getLength() == 0) {
        // DocID not found
        throw new IllegalStateException(
                "DocID tag \"" + docIdTag + "\" not found: " + currentFileResource.getFile().getAbsolutePath());
    } else if (idNodes.getLength() != 1) {
        // DocID not unique (two id elements in one doc)
        throw new IllegalStateException("DocID tag \"" + docIdTag + "\" has multiple occurences: "
                + currentFileResource.getFile().getAbsolutePath());
    }

    Node idNode = idNodes.item(0);
    String id = idNode.getTextContent();
    if (StringUtils.isEmpty(id)) {
        // Empty DocID (e.g. <num></num>)
        throw new IllegalStateException("Emtpy DocID tag \"" + docIdTag + "\" in file: "
                + currentFileResource.getFile().getAbsolutePath());
    }

    getUimaContext().getLogger().log(Level.INFO, "ID '" + id + "' found");
}

From source file:org.springsource.ide.eclipse.commons.core.SpringCoreUtils.java

public static IFile getDeploymentDescriptor(IProject project) {
    if (SpringCoreUtils.hasProjectFacet(project, "jst.web")) {
        IFile settingsFile = project.getFile(".settings/org.eclipse.wst.common.component");
        if (settingsFile.exists()) {
            try {
                NodeList nodes = (NodeList) EXPRESSION.evaluate(parseDocument(settingsFile),
                        XPathConstants.NODESET);
                for (int i = 0; i < nodes.getLength(); i++) {
                    Element element = (Element) nodes.item(i);
                    if ("/".equals(element.getAttribute(DEPLOY_PATH))) {
                        String path = element.getAttribute(SOURCE_PATH);
                        if (path != null) {
                            IFile deploymentDescriptor = project
                                    .getFile(new Path(path).append("WEB-INF").append("web.xml"));
                            if (deploymentDescriptor.exists()) {
                                return deploymentDescriptor;
                            }/*  w w  w  .  j  a v a  2 s . co  m*/
                        }
                    }
                }
            } catch (Exception e) {
                StatusHandler.log(new Status(IStatus.WARNING, CorePlugin.PLUGIN_ID, 1, e.getMessage(), e));
            }
        }
    }
    return null;
}

From source file:org.ala.harvester.WikipediaImageHarvester.java

protected List<String> getXPathValues(Document document, String xpathAsString) throws Exception {

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    List<String> extractedValues = new ArrayList<String>();
    NodeList nodes = (NodeList) xpath.evaluate(xpathAsString, document, XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        String value = (nodes.item(i)).getNodeValue().trim();
        value = StringUtils.trimToNull(value);
        if (value != null) {
            extractedValues.add(value);//from  w  ww .j a v  a 2s. c o  m
        }
    }
    return extractedValues;
}

From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestXmlTests.java

@Test
public void changeRequestHasAtMostOneFixedElement() throws XPathExpressionException {
    NodeList fixedEles = (NodeList) OSLCUtils.getXPath()
            .evaluate("//oslc_cm_v2:ChangeRequest/" + "oslc_cm_v2:fixed", doc, XPathConstants.NODESET);
    assertTrue(getFailureMessage(), fixedEles.getLength() <= 1);
}

From source file:com.mnxfst.testing.server.cfg.PTestServerConfigurationParser.java

/**
 * Evaluates the given expression on the referenced document and returns a result object of type {@link NodeList} 
 * @param expression//from w w  w . j a v a  2  s. c o m
 * @param document
 * @return
 * @throws XPathExpressionException
 */
protected NodeList evaluateNodeList(XPathExpression expression, Object document)
        throws XPathExpressionException {
    if (expression == null)
        throw new XPathExpressionException("Null is not a valid expression");
    if (document == null)
        throw new XPathExpressionException("An xpath expression must not be applied to a NULL document");

    return (NodeList) expression.evaluate(document, XPathConstants.NODESET);
}

From source file:edu.cornell.mannlib.vitro.utilities.containerneutral.CheckContainerNeutrality.java

/**
 * Search for an Xpath within a node of web.xml, returning a handy list.
 *///from w w  w . j  a  v  a2 s  .  co m
private List<Node> findNodes(String pattern, Node context) {
    try {
        XPathExpression xpe = xpath.compile(pattern);
        NodeList nodes = (NodeList) xpe.evaluate(context, XPathConstants.NODESET);
        List<Node> list = new ArrayList<Node>();
        for (int i = 0; i < nodes.getLength(); i++) {
            list.add(nodes.item(i));
        }
        return list;
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.bps.course.nodes.vc.provider.adobe.AdobeConnectProvider.java

private String getScoIdFor(String roomId) {
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("action", "sco-search-by-field");
    parameters.put("query", PREFIX + roomId);
    parameters.put("filter-type", "meeting");
    Document responseDoc = getResponseDocument(sendRequest(parameters));
    if (!evaluateOk(responseDoc))
        return null;

    Object result = evaluate(responseDoc, "//sco/url-path[text()='/" + PREFIX + roomId + "/']",
            XPathConstants.NODESET);
    if (result == null)
        return null;
    NodeList nodes = (NodeList) result;
    if (nodes.getLength() == 1) {
        String scoId = evaluate(responseDoc, "//sco[1]/attribute::sco-id");
        return scoId;
    } else if (nodes.getLength() > 1)
        throw new AssertException("More than one Adobe Connect room found for one course node!");
    else//from w  ww. ja  va 2s .  c o m
        return null;
}

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  ww.j  a v  a2  s . c o m
 * 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:org.openmrs.module.sdmxhddataexport.web.controller.dataelement.DataElementController.java

@RequestMapping(value = "/module/sdmxhddataexport/listDataElement.form", method = RequestMethod.POST)
public String deleteDataElement(@RequestParam(value = "ids", required = false) String[] ids,
        @RequestParam(value = "files", required = false) MultipartFile uploadItem, HttpServletRequest request,
        @RequestParam(value = "upload", required = false) String upload,
        @RequestParam(value = "IncludeQueries", required = false) String IncludeQueries, Object command,
        SessionStatus status) {//from   w w  w . ja  va2  s.c o  m
    String temp = "";
    HttpSession httpSession = request.getSession();
    Integer dataElementId = null;
    System.out.println(" done " + upload);
    if (upload != null) {
        System.out.println("1st part truly done");
        //FileUpload file = uploadItem;
        String fileName = "";
        if (uploadItem != null) {
            fileName = uploadItem.getOriginalFilename();
            System.out.println("2nd part truly done " + fileName);

            byte[] byteArray = null;
            try {
                byteArray = uploadItem.getBytes();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println("Bad file name");

                e.printStackTrace();
            }

            String data = new String(byteArray);
            System.out.println("3rd part truly done " + data);
            XPath xpath = XPathFactory.newInstance().newXPath();
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            DocumentBuilder builder = null;
            try {
                builder = domFactory.newDocumentBuilder();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();

            }
            Document doc = null;
            try {
                doc = builder.parse(uploadItem.getInputStream());
            } catch (SAXException e1) {
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "Unsupported Document type is uploaded ");

                //or we can use httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "sdmxhddataexport.UploadedFile.Wrong" );

                return "redirect:/module/sdmxhddataexport/listDataElement.form";

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "error in reading Document type  ");

                //e1.printStackTrace();

            }
            XPathExpression expr = null;
            XPathExpression exprDesc = null;
            XPathExpression exprQuery = null;
            try {
                expr = xpath.compile(
                        "//*[local-name(.)='CodeList' and @id='CL_DATAELEMENT']/*[local-name(.)='Code']");
                exprDesc = xpath.compile("//[local-name(.)='Description']");

                exprQuery = xpath.compile("//[local-name(.)='Query']");
            } catch (XPathExpressionException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Error parsing document ");

            }
            Object result = null;
            try {
                result = expr.evaluate(doc, XPathConstants.NODESET);
            } catch (XPathExpressionException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Error parsing document ");

                // e.printStackTrace();
            }
            NodeList nodes = (NodeList) result;
            ArrayList<DataElement> dataElements = new ArrayList<DataElement>();
            for (int i = 0; i < nodes.getLength(); i++) {
                boolean putItIn = false;
                DataElement de = new DataElement();
                System.out.println(nodes.item(i).getLocalName());

                NamedNodeMap nmp = nodes.item(i).getAttributes();
                System.out.println(nmp.getNamedItem("value").getNodeValue() + "  hellooo..");
                de.setCode(nmp.getNamedItem("value").getNodeValue());
                //Node tempNode = (Node)nodes.item(i); 
                NodeList innerNodeList = nodes.item(i).getChildNodes();
                System.out.println("length: " + innerNodeList.getLength());
                for (int j = 0; j < innerNodeList.getLength(); j++) {
                    if (innerNodeList.item(j).getLocalName() != null) {
                        System.out.println("hehe " + innerNodeList.item(j).getLocalName());
                        if (innerNodeList.item(j).getLocalName().equals(new String("Description"))) {
                            System.out.println("Description: " + innerNodeList.item(j).getTextContent());
                            de.setName(innerNodeList.item(j).getTextContent());

                            putItIn = true;
                        }

                        if (innerNodeList.item(j).getLocalName().equals(new String("Query"))
                                && IncludeQueries != null) {
                            System.out.println("Query: " + innerNodeList.item(j).getTextContent());
                            de.setSqlQuery(innerNodeList.item(j).getTextContent());
                        }
                    }
                }
                if (putItIn) {

                    boolean bool;
                    DataElementValidator valid = new DataElementValidator();
                    bool = valid.fileValidate(de);
                    if (bool == true)
                        dataElements.add(de);

                }
            }
            ListIterator<DataElement> li = dataElements.listIterator();
            DataElement de;
            while (li.hasNext()) {
                de = (DataElement) li.next();
                System.out.println("Element 1 = " + de.getName());
                de.setCreatedOn(new java.util.Date());
                de.setCreatedBy(Context.getAuthenticatedUser().getGivenName());
                SDMXHDDataExportService sDMXHDDataExportService = Context
                        .getService(SDMXHDDataExportService.class);

                sDMXHDDataExportService.saveDataElement(de);

            }

            status.setComplete();
        }

        return "redirect:/module/sdmxhddataexport/listDataElement.form";
    }
    try {
        SDMXHDDataExportService sDMXHDDataExportService = Context.getService(SDMXHDDataExportService.class);
        if (ids != null && ids.length > 0) {
            for (String sId : ids) {
                dataElementId = Integer.parseInt(sId);
                if (dataElementId != null && dataElementId > 0 && CollectionUtils.isEmpty(
                        sDMXHDDataExportService.listReportDataElement(null, dataElementId, null, 0, 1))) {
                    sDMXHDDataExportService
                            .deleteDataElement(sDMXHDDataExportService.getDataElementById(dataElementId));
                } else {
                    //temp += "We can't delete store="+store.getName()+" because that store is using please check <br/>";
                    temp = "This dataElement cannot be deleted as it is in use";
                }
            }
        }
    } catch (Exception e) {
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Can not delete dataElement ");
        log.error(e);
    }
    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
            StringUtils.isBlank(temp) ? "sdmxhddataexport.dataElement.deleted" : temp);

    return "redirect:/module/sdmxhddataexport/listDataElement.form";
}