List of usage examples for javax.xml.xpath XPathConstants NODESET
QName NODESET
To view the source code for javax.xml.xpath XPathConstants NODESET.
Click Source Link
The XPath 1.0 NodeSet data type.
Maps to Java org.w3c.dom.NodeList .
From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionNamespaceContextHelperTest.java
@Test public void testReturnNamespaceMapFromNode() throws Exception { //Retrieve ER xpath context XPath xpath;//from ww w . ja v a 2 s . c o m xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new EntityResolutionNamespaceContext()); //Get the test attribute parameters configuration InputStream attributeParametersStream = getClass().getResourceAsStream("/xml/TestAttributeParameters.xml"); assertNotNull(attributeParametersStream); //Convert to DOM document XmlConverter converter = new XmlConverter(); converter.getDocumentBuilderFactory().setNamespaceAware(true); Document attributeParametersDocument = converter.toDOMDocument(attributeParametersStream); NodeList parameterNodes = null; //Perform Xpath to retrieve attribute parameters parameterNodes = (NodeList) xpath.evaluate("er-ext:AttributeParameter", attributeParametersDocument.getDocumentElement(), XPathConstants.NODESET); //Loop through attribute parameters to retrieve namespace map associated with attribute xpath for (int i = 0; i < parameterNodes.getLength(); i++) { Node node = parameterNodes.item(i); String attributeXpathValue = xpath.evaluate("er-ext:AttributeXPath", node); Map<String, String> namespaceMap = EntityResolutionNamespaceContextHelpers .returnNamespaceMapFromNode(attributeXpathValue, node); for (Map.Entry<String, String> entry : namespaceMap.entrySet()) { LOG.debug("Namespace Map Entry, Prefix : " + entry.getKey() + " Namespace : " + entry.getValue()); } if (attributeXpathValue.equals("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName")) { assertEquals("http://niem.gov/niem/niem-core/2.0", namespaceMap.get("nc")); assertEquals("http://local.org/IEPD/Extensions/PersonSearchResults/1.0", namespaceMap.get("ext")); } if (attributeXpathValue.equals("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName")) { assertEquals("http://niem.gov/niem/niem-core/2.0", namespaceMap.get("nc")); assertEquals("http://local.org/IEPD/Extensions/PersonSearchResults/1.0", namespaceMap.get("ext")); } } }
From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.validation.BcrExperimentFieldValidator.java
/** * checks all tags in a file//from w ww. j a v a 2 s . co m * @param xmlFile to check for XSDElements */ private boolean checkXmlFile(final File xmlFile, final QcContext context, List<String> clinicalElementList) throws ProcessorException { NodeList nodes = null; try { final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile); final XPath xpath = XPathFactory.newInstance().newXPath(); nodes = (NodeList) xpath.evaluate(PATIENT_XPATH, document, XPathConstants.NODESET); } catch (XPathException e) { throw new ProcessorException("Unable to evaluate " + PATIENT_XPATH + " expression ", e); } catch (Exception e) { // same handling no matter what is thrown by parser throw new ProcessorException("Unable to parse file: " + xmlFile.getName(), e); } if (nodes.getLength() == 0) { throw new ProcessorException("No patient node found in file " + xmlFile.getName()); } if (nodes.getLength() > 1) { throw new ProcessorException("More than one patient node found in file " + xmlFile.getName()); } return parse(nodes.item(0), context, clinicalElementList, xmlFile.getName()); }
From source file:org.nira.wso2.nexus.ComponentVersion.java
/** * Loads the List of all the Dependencies in the DependencyManagement from the root * pom.xml/*from w ww . j a v a 2s. co m*/ * * @param pomFilePath : The path to the root pom.xml * @throws ComponentException */ private static void getDependencyManagement(String pomFilePath) throws ComponentException { String nodeName, nodeValue; DependencyComponent dependencyComponent; NodeList dependenciesList = Utils.getNodeListFromXPath(pomFilePath, Constants.DEPENDENCY_MANAGEMENT_XPATH); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); try { for (int i = 0; i < dependenciesList.getLength(); ++i) { Node dependency = dependenciesList.item(i); if (dependency != null && dependency.getNodeType() == Node.ELEMENT_NODE) { NodeList nodes = (NodeList) xpath.evaluate(Constants.SELECT_ALL, dependency, XPathConstants.NODESET); dependencyComponent = new DependencyComponent(); for (int j = 0; j < nodes.getLength(); ++j) { nodeName = nodes.item(j).getNodeName(); nodeValue = nodes.item(j).getTextContent(); if (nodeValue == null) { throw new ComponentException("Dependency value is NULL for " + nodeName + "!"); } switch (nodeName) { case Constants.GROUPID: dependencyComponent.setGroupId(nodeValue); break; case Constants.ARTIFACTID: dependencyComponent.setArtifactId(nodeValue); break; case Constants.VERSION: if (Constants.PROJECT_VERSION.equalsIgnoreCase(nodeValue)) { break; } //ToDo: Check for values like the one below: //<version.tomcat>7.0.59</version.tomcat> //<orbit.version.tomcat>${version.tomcat}.wso2v3</orbit.version.tomcat> while (!Character.isDigit(nodeValue.charAt(0))) { nodeValue = nodeValue.substring(2, nodeValue.length() - 1); nodeValue = dependencyComponentVersions.get(nodeValue); if (nodeValue == null) { throw new ComponentException("Dependency Version cannot be NULL!"); } } dependencyComponent.setVersion(nodeValue); break; } } if (dependencyComponent.getGroupId() != null && dependencyComponent.getArtifactId() != null && dependencyComponent.getVersion() != null) { getLatestComponentVersion(dependencyComponent); dependencyComponentList.add(dependencyComponent); } } } } catch (XPathExpressionException e) { throw new ComponentException("XPath Exception when retrieving Dependency Components!", e); } Collections.sort(dependencyComponentList, DependencyComponent.GroupIdArifactIdComparator); }
From source file:es.sistedes.handle.generator.Conversor.java
/** * Converts the XML data available in the <code>input</code> * {@link InputStream} and dumps the result in the <code>output</code> * {@link OutputStream}/*w w w .j ava 2 s . co m*/ * * @throws ConversionException * If any error occurs, check * {@link ConversionException#getCause()} to figure out the exact * cause */ public synchronized void generate() throws ConversionException { PrintWriter outputWriter = new PrintWriter(output); try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(input); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); NodeList list = (NodeList) xpath.evaluate( "//channel/item[link and guid and postmeta[meta_key/text()='handle']]", doc, XPathConstants.NODESET); Boolean useGuid = useGuid(); Boolean addDelete = addDelete(); Map<String, String> vars = new HashMap<String, String>(); vars.put(HandleVariables.prefix.toString(), prefix); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); String handle = xpath.evaluate("postmeta[meta_key/text()='handle']/meta_value/text()", node); if (filter() != null) { // We use a regex in the Node instead of a XPath filter in // the NodeList because Java only supports XPath 1 and the // "matches" function has been introduced in XPath 2 Pattern pattern = Pattern.compile(filter()); if (!pattern.matcher(handle).matches()) { continue; } } vars.put(HandleVariables.handle.toString(), handle); vars.put(HandleVariables.url.toString(), useGuid ? xpath.evaluate("guid/text()", node) : xpath.evaluate("link/text()", node)); if (addDelete) { outputWriter.println(StrSubstitutor.replace(commands.get("command.delete"), vars)); } outputWriter.println(StrSubstitutor.replace(commands.get("command.create"), vars)); outputWriter.println(StrSubstitutor.replace(commands.get("command.admin"), vars)); outputWriter.println(StrSubstitutor.replace(commands.get("command.url"), vars)); outputWriter.println(); } } catch (Exception e) { throw new ConversionException(e); } finally { outputWriter.flush(); } }
From source file:br.gov.lexml.parser.documentoarticulado.LexMLParserFromText.java
@Override public List<Element> getArtigos() { try {/* w w w . ja v a 2 s . com*/ NodeList nodelist = (NodeList) XPathFactory.newInstance().newXPath().compile(XPATH_1ST_LEVEL_ARTIGOS) .evaluate(LexMLUtil.toDocument(getArticulacao()), XPathConstants.NODESET); List<Element> elementslist = new ArrayList<Element>(); for (int i = 0; i < nodelist.getLength(); i++) if (!isAlteracao(nodelist.item(i))) elementslist.add((Element) nodelist.item(i)); return elementslist; } catch (XPathExpressionException e) { throw new IllegalArgumentException(e); } }
From source file:com.dianping.zebra.shard.jdbc.base.MultiDBBaseTestCase.java
private List<DBDataEntry> parseDataFile() throws Exception { List<DBDataEntry> datas = new ArrayList<DBDataEntry>(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document configDoc = builder// w w w . ja va 2s .com .parse(MultiDBBaseTestCase.class.getClassLoader().getResourceAsStream(getDataFile())); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); NodeList databaseList = (NodeList) xpath.compile("/dataset/database").evaluate(configDoc, XPathConstants.NODESET); for (int i = 0; i < databaseList.getLength(); i++) { DBDataEntry entry = new DBDataEntry(); Element ele = (Element) databaseList.item(i); entry.setDbName(ele.getAttribute("name")); NodeList scriptNodeList = ele.getChildNodes(); List<String> scripts = new ArrayList<String>(); for (int j = 0; j < scriptNodeList.getLength(); j++) { scripts.add(scriptNodeList.item(j).getTextContent()); } entry.setScripts(scripts); datas.add(entry); } return datas; }
From source file:eu.smartfp7.terrier.sensor.ParserUtility.java
public static EdgeNodeSnapShot parse(InputStream is) throws Exception { DocumentBuilderFactory xmlfact = DocumentBuilderFactory.newInstance(); xmlfact.setNamespaceAware(true);// w w w .j a va 2 s. co m Document document = xmlfact.newDocumentBuilder().parse(is); NamespaceContext ctx = new NamespaceContext() { @Override public Iterator getPrefixes(String namespaceURI) { // TODO Auto-generated method stub return null; } @Override public String getPrefix(String namespaceURI) { // TODO Auto-generated method stub return null; } @Override public String getNamespaceURI(String prefix) { String uri = null; /* * xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:smart="http://www.ait.gr/ait_web_site/faculty/apne/schema.xml#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:contact="http://www.w3.org/2000/10/swap/pim/contact#" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:time="http://www.w3.org/2006/time#" xml:base="http://www.ait.gr/ait_web_site/faculty/apne/report.xml" * */ if (prefix.equals("rdf")) { uri = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; } if (prefix.equals("smart")) { uri = "http://www.ait.gr/ait_web_site/faculty/apne/schema.xml#"; } if (prefix.equals("dc")) { uri = "http://purl.org/dc/elements/1.1/#"; } if (prefix.equals("geo")) { uri = "http://www.w3.org/2003/01/geo/wgs84_pos#"; } if (prefix.equals("time")) { uri = "http://www.w3.org/2006/time#"; } return uri; } }; // find the node data XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(ctx); String id = (String) xpath.compile("//smart:Node/@rdf:ID").evaluate(document, XPathConstants.STRING); String lat = (String) xpath.compile("//smart:Node/geo:lat/text()").evaluate(document, XPathConstants.STRING); String lon = (String) xpath.compile("//smart:Node/geo:long/text()").evaluate(document, XPathConstants.STRING); String fullName = (String) xpath.compile("//smart:Node/dc:fullName/text()").evaluate(document, XPathConstants.STRING); Node node = new Node(new Double(lat), new Double(lon), id, fullName); String time = (String) xpath.compile("//smart:Report/time:inXSDDateTime/text()").evaluate(document, XPathConstants.STRING); String reportId = (String) xpath.compile("//smart:Report/@rdf:ID").evaluate(document, XPathConstants.STRING); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); Calendar c = Calendar.getInstance(); ; c.setTime(df.parse(time)); String density = (String) xpath.compile("//smart:Crowd/smart:density/text()").evaluate(document, XPathConstants.STRING); String cameraGain = (String) xpath.compile("//smart:Crowd/smart:cameraGain/text()").evaluate(document, XPathConstants.STRING); NodeList list = (NodeList) xpath.compile("//smart:Crowd/smart:colour").evaluate(document, XPathConstants.NODESET); double[] colors = new double[list.getLength()]; for (int i = 0; i < list.getLength(); i++) { org.w3c.dom.Node colorNode = list.item(i); String v = colorNode.getFirstChild().getTextContent(); colors[i] = new Double(v); } CrowdReport crowdReport = new CrowdReport(reportId, new Double(density), new Double(cameraGain), colors); EdgeNodeSnapShot snapShot = new EdgeNodeSnapShot(node, id, c, crowdReport); return snapShot; }
From source file:com.amalto.core.storage.datasource.DataSourceFactory.java
private static Map<String, DataSourceDefinition> readDocument(InputStream configurationAsStream) { Document document;//from w w w. j a v a2 s .c o m try { DocumentBuilder documentBuilder = factory.newDocumentBuilder(); document = documentBuilder.parse(configurationAsStream); } catch (Exception e) { throw new RuntimeException("Exception occurred during data sources XML configuration parsing", e); } try { NodeList datasources = (NodeList) evaluate(document, "/datasources/datasource", XPathConstants.NODESET); Map<String, DataSourceDefinition> nameToDataSources = new HashMap<String, DataSourceDefinition>(); for (int i = 0; i < datasources.getLength(); i++) { Node currentDataSourceElement = datasources.item(i); String name = (String) evaluate(currentDataSourceElement, "@name", XPathConstants.STRING); //$NON-NLS-1$ DataSource master = getDataSourceConfiguration(currentDataSourceElement, name, "master"); //$NON-NLS-1$ if (master == null) { throw new IllegalArgumentException( "Data source '" + name + "'does not declare a master data section"); } DataSource staging = getDataSourceConfiguration(currentDataSourceElement, name, "staging"); //$NON-NLS-1$ DataSource system = getDataSourceConfiguration(currentDataSourceElement, name, "system"); //$NON-NLS-1$ nameToDataSources.put(name, new DataSourceDefinition(master, staging, system)); } return nameToDataSources; } catch (XPathExpressionException e) { throw new RuntimeException("Invalid data sources configuration.", e); } }
From source file:com.twentyn.patentExtractor.PatentDocumentFeatures.java
/** * Extracts sentence nodes from a POS-tagger XML document. These sentences are intended to provide some notion of * locality for identified chemical entities. * * @param docBuilder A document builder to use when producing single-sentence XML documents. * @param doc The POS-tagger XML document from which to extract sentences. * @return A list of single-sentence documents. * @throws ParserConfigurationException//from w w w.j a va2s . c o m * @throws XPathExpressionException */ private static List<Document> findSentences(DocumentBuilder docBuilder, Document doc) throws ParserConfigurationException, XPathExpressionException { if (doc != null) { // TODO: is there a more efficient yet still safe way to do this? XPath xpath = Util.getXPathFactory().newXPath(); // TODO: get rid of this inline xpath compilation, run during setup. NodeList nodes = (NodeList) xpath.evaluate(SENTENCE_PATH, doc, XPathConstants.NODESET); List<Document> docList = new ArrayList<>(nodes.getLength()); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); /* With help from: * http://examples.javacodegeeks.com/core-java/xml/dom/copy-nodes-subtree-from-one-dom-document-to-another/ */ org.w3c.dom.Document newDoc = docBuilder.newDocument(); Element rootElement = newDoc.createElement(SENTENCE_DOC_HEADER); Node newNode = newDoc.importNode(n, true); rootElement.appendChild(newNode); newDoc.appendChild(rootElement); docList.add(newDoc); } return docList; } else { // TODO: log here. return new ArrayList<>(0); } }
From source file:com.streak.logging.utils.AnalysisUtility.java
public static void fetchCloudStorageUris(String bucketName, String startKey, String endKey, HttpRequestFactory requestFactory, List<String> urisToProcess, boolean readSchemas) throws IOException { String bucketUri = "http://commondatastorage.googleapis.com/" + bucketName; HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(bucketUri + "?marker=" + startKey)); HttpResponse response = request.execute(); try {/*w w w . j a va 2 s.co m*/ Document responseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(response.getContent()); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.evaluate("//Contents/Key/text()", responseDoc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { String key = nodes.item(i).getNodeValue(); if (key.compareTo(endKey) >= 0) { break; } if (key.endsWith(".schema") ^ readSchemas) { continue; } if (readSchemas) { key = key.substring(0, key.length() - ".schema".length()); } urisToProcess.add("gs://" + bucketName + "/" + key); } } catch (SAXException e) { throw new IOException("Error parsing cloud storage response", e); } catch (ParserConfigurationException e) { throw new IOException("Error configuring cloud storage parser", e); } catch (XPathExpressionException e) { throw new IOException("Error finding keys", e); } }