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:com.persistent.cloudninja.service.impl.RunningInstancesJSONDataServiceImpl.java
/** * Parse the response from deployment monitoring and get role name, instance name and instance status. * @param response The XML response of deployment monitoring task. * @return List of InstanceHealthRoleInstanceEntity * @throws ParserConfigurationException//from w w w . j a va 2 s .co m * @throws SAXException * @throws IOException * @throws XPathExpressionException */ private List<InstanceHealthRoleInstanceEntity> parseResponse(StringBuffer response) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { DocumentBuilder documentBuilder = null; Document document = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setIgnoringElementContentWhitespace(true); documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.parse(new InputSource(new StringReader(response.toString()))); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); NodeList roleNameList = (NodeList) xPath.evaluate("/Deployment/RoleInstanceList/RoleInstance/RoleName", document, XPathConstants.NODESET); NodeList instanceNameList = (NodeList) xPath.evaluate( "/Deployment/RoleInstanceList/RoleInstance/InstanceName", document, XPathConstants.NODESET); NodeList instanceStatusList = (NodeList) xPath.evaluate( "/Deployment/RoleInstanceList/RoleInstance/InstanceStatus", document, XPathConstants.NODESET); List<InstanceHealthRoleInstanceEntity> list = new ArrayList<InstanceHealthRoleInstanceEntity>(); for (int index = 0; index < roleNameList.getLength(); index++) { Element roleElement = (Element) roleNameList.item(index); Element instanceElement = (Element) instanceNameList.item(index); Element statusElement = (Element) instanceStatusList.item(index); InstanceHealthRoleInstanceEntity roleInstanceEntity = new InstanceHealthRoleInstanceEntity(); roleInstanceEntity.setRoleName(roleElement.getTextContent()); roleInstanceEntity.setInstanceName(instanceElement.getTextContent()); roleInstanceEntity.setInstanceStatus(statusElement.getTextContent()); list.add(roleInstanceEntity); } return list; }
From source file:io.fabric8.forge.ipaas.repository.NexusConnectionRepository.java
protected void indexNexus() throws Exception { // must have q parameter so use connector to find all connectors String query = nexusUrl + "?q=connector"; URL url = new URL(query); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);/*w w w . j ava 2 s . c om*/ factory.setIgnoringElementContentWhitespace(true); factory.setIgnoringComments(true); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); InputStream is = url.openStream(); Document dom = documentBuilder.parse(is); XPathFactory xpFactory = XPathFactory.newInstance(); XPath exp = xpFactory.newXPath(); NodeList list = (NodeList) exp.evaluate("//classifier[text() = '" + CLASSIFIER + "']", dom, XPathConstants.NODESET); Set<NexusArtifactDto> newArtifacts = new LinkedHashSet<>(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); Node parent = node.getParentNode(); String g = getNodeText(parent.getChildNodes(), "groupId"); String a = getNodeText(parent.getChildNodes(), "artifactId"); String v = getNodeText(parent.getChildNodes(), "version"); String l = getNodeText(parent.getChildNodes(), "artifactLink"); if (g != null & a != null & v != null & l != null) { NexusArtifactDto dto = new NexusArtifactDto(); dto.setGroupId(g); dto.setArtifactId(a); dto.setVersion(v); dto.setArtifactLink(l); System.out.println("Found connector: " + dto.getGroupId() + ":" + dto.getArtifactId() + ":" + dto.getVersion()); // is it a new artifact boolean newArtifact = true; for (NexusArtifactDto existing : indexedArtifacts) { if (existing.getGroupId().equals(dto.getGroupId()) && existing.getArtifactId().equals(dto.getArtifactId()) && existing.getVersion().equals(dto.getVersion())) { newArtifact = false; break; } } if (newArtifact) { newArtifacts.add(dto); } } } // now download the new artifact JARs and look inside to find more details for (NexusArtifactDto dto : newArtifacts) { try { // download using url classloader reader URL jarUrl = new URL(dto.getArtifactLink()); String json = loadCamelConnectorJSonSchema(jarUrl); ObjectMapper mapper = new ObjectMapper(); ConnectionCatalogDto cat = mapper.readerFor(ConnectionCatalogDto.class).readValue(json); indexedArtifacts.add(dto); connectors.putIfAbsent(dto, cat); System.out.println("Added connector: " + dto.getGroupId() + ":" + dto.getArtifactId() + ":" + dto.getVersion()); } catch (Exception e) { System.err.println("Error downloading connector JAR " + dto.getArtifactLink() + ". This exception is ignored. " + e.getMessage()); } } IOHelpers.close(is); }
From source file:org.eclipse.lyo.testsuite.oslcv2.CoreResourceXmlTests.java
@Test public void CoreResourceHasAtMostOneModifiedDate() throws XPathExpressionException { String eval = "//" + getNode() + "/" + "dc:modified"; NodeList modifiedDates = (NodeList) OSLCUtils.getXPath().evaluate(eval, doc, XPathConstants.NODESET); assertTrue(getFailureMessage(), modifiedDates.getLength() <= 1); //If there is a modified date, verify the format. if (modifiedDates.getLength() > 0) { try {/*from w ww. j a va2 s . c o m*/ final String dateString = modifiedDates.item(0).getTextContent(); DatatypeConverter.parseDateTime(dateString); } catch (Exception e) { fail("Modified date not in valid XSD format"); } } }
From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionServiceIntermediaryTest.java
private void performSortTest(File inputMessageFile, int factor1, int factor2, int factor3) throws Exception { senderExchange.getIn().setBody(inputMessageFile); Exchange returnExchange = template.send("direct:entityResolutionRequestServiceEndpoint", senderExchange); if (returnExchange.getException() != null) { throw new Exception(returnExchange.getException()); }/*from w w w . j a v a2 s .com*/ Thread.sleep(3000); entityResolutionResponseMock.assertIsSatisfied(); entityResolutionResponseMock.expectedMessageCount(1); Exchange ex = entityResolutionResponseMock.getExchanges().get(0); Document responseDocument = ex.getIn().getBody(Document.class); // String docString = new XmlConverter().toString(responseDocument, ex); // log.info("\n" + docString + "\n"); XPath xp = XPathFactory.newInstance().newXPath(); xp.setNamespaceContext(testNamespaceContext); NodeList personNodes = (NodeList) xp.evaluate( "/merge-result:EntityMergeResultMessage/merge-result:EntityContainer/merge-result-ext:Entity/ext:PersonSearchResult/ext:Person", responseDocument, XPathConstants.NODESET); assertEquals(5, personNodes.getLength()); List<Node> lastNameNodes = new ArrayList<Node>(); List<Node> firstNameNodes = new ArrayList<Node>(); List<Node> idNodes = new ArrayList<Node>(); for (int i = 0; i < personNodes.getLength(); i++) { Node personNode = personNodes.item(i); Node lastNameNode = (Node) xp.evaluate("nc:PersonName/nc:PersonSurName", personNode, XPathConstants.NODE); lastNameNodes.add(lastNameNode); Node firstNameNode = (Node) xp.evaluate("nc:PersonName/nc:PersonGivenName", personNode, XPathConstants.NODE); firstNameNodes.add(firstNameNode); Node idNode = (Node) xp.evaluate( "jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID", personNode, XPathConstants.NODE); idNodes.add(idNode); } assertTrue(compareTextNodeLists(personNodes.getLength(), lastNameNodes, firstNameNodes, idNodes, factor1, factor2, factor3)); }
From source file:de.pangaea.fixo3.xml.ProcessXmlFiles.java
private void run() throws FileNotFoundException, SAXException, IOException, ParserConfigurationException, XPathExpressionException { // src/test/resources/, src/main/resources/files File folder = new File("src/main/resources/files"); File[] files = folder.listFiles(new FileFilter() { @Override/* ww w. j ava 2s . c o m*/ public boolean accept(File pathname) { if (pathname.getName().endsWith(".xml")) return true; return false; } }); JsonArrayBuilder json = Json.createArrayBuilder(); Document doc; String deviceLabel, deviceComment, deviceImage; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); final Map<String, String> prefixToNS = new HashMap<>(); prefixToNS.put(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI); prefixToNS.put(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI); prefixToNS.put("sml", "http://www.opengis.net/sensorml/2.0"); prefixToNS.put("gml", "http://www.opengis.net/gml/3.2"); prefixToNS.put("gmd", "http://www.isotc211.org/2005/gmd"); XPath x = XPathFactory.newInstance().newXPath(); x.setNamespaceContext(new NamespaceContext() { @Override public String getNamespaceURI(String prefix) { Objects.requireNonNull(prefix, "Namespace prefix cannot be null"); final String uri = prefixToNS.get(prefix); if (uri == null) { throw new IllegalArgumentException("Undeclared namespace prefix: " + prefix); } return uri; } @Override public String getPrefix(String namespaceURI) { throw new UnsupportedOperationException(); } @Override public Iterator<?> getPrefixes(String namespaceURI) { throw new UnsupportedOperationException(); } }); XPathExpression exGmlName = x.compile("/sml:PhysicalSystem/gml:name"); XPathExpression exGmlDescription = x.compile("/sml:PhysicalSystem/gml:description"); XPathExpression exGmdUrl = x.compile( "/sml:PhysicalSystem/sml:documentation/sml:DocumentList/sml:document/gmd:CI_OnlineResource/gmd:linkage/gmd:URL"); XPathExpression exTerm = x .compile("/sml:PhysicalSystem/sml:classification/sml:ClassifierList/sml:classifier/sml:Term"); int m = 0; int n = 0; for (File file : files) { log.info(file.getName()); doc = dbf.newDocumentBuilder().parse(new FileInputStream(file)); deviceLabel = exGmlName.evaluate(doc).trim(); deviceComment = exGmlDescription.evaluate(doc).trim(); deviceImage = exGmdUrl.evaluate(doc).trim(); NodeList terms = (NodeList) exTerm.evaluate(doc, XPathConstants.NODESET); JsonObjectBuilder jobDevice = Json.createObjectBuilder(); jobDevice.add("name", toUri(deviceLabel)); jobDevice.add("label", deviceLabel); jobDevice.add("comment", toAscii(deviceComment)); jobDevice.add("image", deviceImage); JsonArrayBuilder jabSubClasses = Json.createArrayBuilder(); for (int i = 0; i < terms.getLength(); i++) { Node term = terms.item(i); NodeList attributes = term.getChildNodes(); String attributeLabel = null; String attributeValue = null; for (int j = 0; j < attributes.getLength(); j++) { Node attribute = attributes.item(j); String attributeName = attribute.getNodeName(); if (attributeName.equals("sml:label")) { attributeLabel = attribute.getTextContent(); } else if (attributeName.equals("sml:value")) { attributeValue = attribute.getTextContent(); } } if (attributeLabel == null || attributeValue == null) { throw new RuntimeException("Attribute label or value cannot be null [attributeLabel = " + attributeLabel + "; attributeValue = " + attributeValue + "]"); } if (attributeLabel.equals("model")) { continue; } if (attributeLabel.equals("manufacturer")) { jobDevice.add("manufacturer", attributeValue); continue; } n++; Quantity quantity = getQuantity(attributeValue); if (quantity == null) { continue; } m++; JsonObjectBuilder jobSubClass = Json.createObjectBuilder(); JsonObjectBuilder jobCapability = Json.createObjectBuilder(); JsonObjectBuilder jobQuantity = Json.createObjectBuilder(); String quantityLabel = getQuantityLabel(attributeLabel); String capabilityLabel = deviceLabel + " " + quantityLabel; jobCapability.add("label", capabilityLabel); jobQuantity.add("label", quantity.getLabel()); if (quantity.getValue() != null) { jobQuantity.add("value", quantity.getValue()); } else if (quantity.getMinValue() != null && quantity.getMaxValue() != null) { jobQuantity.add("minValue", quantity.getMinValue()); jobQuantity.add("maxValue", quantity.getMaxValue()); } else { throw new RuntimeException( "Failed to determine quantity value [attributeValue = " + attributeValue + "]"); } jobQuantity.add("unitCode", quantity.getUnitCode()); jobQuantity.add("type", toUri(quantityLabel)); jobCapability.add("quantity", jobQuantity); jobSubClass.add("capability", jobCapability); jabSubClasses.add(jobSubClass); } jobDevice.add("subClasses", jabSubClasses); json.add(jobDevice); } Map<String, Object> properties = new HashMap<>(1); properties.put(JsonGenerator.PRETTY_PRINTING, true); JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(properties); JsonWriter jsonWriter = jsonWriterFactory.createWriter(new FileWriter(new File(jsonFileName))); jsonWriter.write(json.build()); jsonWriter.close(); System.out.println("Fraction of characteristics included: " + m + "/" + n); }
From source file:hudson.plugins.plot.XMLSeries.java
/** * Load the series from a properties file. *//* w w w . j a v a2s . c o m*/ @Override public List<PlotPoint> loadSeries(FilePath workspaceRootDir, int buildNumber, PrintStream logger) { InputStream in = null; InputSource inputSource = null; try { List<PlotPoint> ret = new ArrayList<PlotPoint>(); FilePath[] seriesFiles = null; try { seriesFiles = workspaceRootDir.list(getFile()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Exception trying to retrieve series files", e); return null; } if (ArrayUtils.isEmpty(seriesFiles)) { LOGGER.info("No plot data file found: " + getFile()); return null; } try { if (LOGGER.isLoggable(defaultLogLevel)) LOGGER.log(defaultLogLevel, "Loading plot series data from: " + getFile()); in = seriesFiles[0].read(); // load existing plot file inputSource = new InputSource(in); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Exception reading plot series data from " + seriesFiles[0], e); return null; } if (LOGGER.isLoggable(defaultLogLevel)) LOGGER.log(defaultLogLevel, "NodeType " + nodeTypeString + " : " + nodeType); if (LOGGER.isLoggable(defaultLogLevel)) LOGGER.log(defaultLogLevel, "Loaded XML Plot file: " + getFile()); XPath xpath = XPathFactory.newInstance().newXPath(); Object xmlObject = xpath.evaluate(xpathString, inputSource, nodeType); /* * If we have a nodeset, we need multiples, otherwise we just need * one value, and can do a toString() to set it. */ if (nodeType.equals(XPathConstants.NODESET)) { NodeList nl = (NodeList) xmlObject; if (LOGGER.isLoggable(defaultLogLevel)) LOGGER.log(defaultLogLevel, "Number of nodes: " + nl.getLength()); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (!new Scanner(node.getTextContent().trim()).hasNextDouble()) { return coalesceTextnodesAsLabelsStrategy(nl, buildNumber); } } return mapNodeNameAsLabelTextContentAsValueStrategy(nl, buildNumber); } else if (nodeType.equals(XPathConstants.NODE)) { addNodeToList(ret, (Node) xmlObject, buildNumber); } else { // otherwise we have a single type and can do a toString on it. if (xmlObject instanceof NodeList) { NodeList nl = (NodeList) xmlObject; if (LOGGER.isLoggable(defaultLogLevel)) LOGGER.log(defaultLogLevel, "Number of nodes: " + nl.getLength()); for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if (n != null && n.getLocalName() != null && n.getTextContent() != null) { addValueToList(ret, label, xmlObject, buildNumber); } } } else { addValueToList(ret, label, xmlObject, buildNumber); } } return ret; } catch (XPathExpressionException e) { LOGGER.log(Level.SEVERE, "XPathExpressionException for XPath '" + getXpath() + "'", e); } finally { IOUtils.closeQuietly(in); } return null; }
From source file:org.eclipse.lyo.testsuite.oslcv2.QueryTests.java
@Test public void validCompoundQueryContainsExpectedDefect() throws IOException, SAXException, ParserConfigurationException, XPathExpressionException { String respBody = runQuery(getCompoundQueryContainsExpectedDefectQuery(), OSLCConstants.CT_XML); Document doc = OSLCUtils.createXMLDocFromResponseBody(respBody); //Make sure each entry has a matching property element with a value that matches the query NodeList lst = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_cm_v2:ChangeRequest", doc, XPathConstants.NODESET); checkEqualityProperty(lst, queryProperty, queryPropertyValue, doc); checkGreaterThanProperty(lst, queryComparisonProperty, queryComparisonValue, doc); }
From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandler.java
Set<AttributeParametersXpathSupport> getAttributeParameters(Node attributeParametersNode) throws Exception { Set<AttributeParametersXpathSupport> ret = new HashSet<AttributeParametersXpathSupport>(); NodeList parameterNodes = null; if (attributeParametersNode == null) { parameterNodes = (NodeList) xpath.evaluate("er-ext:AttributeParameter", attributeParametersDocument.getDocumentElement(), XPathConstants.NODESET); } else {// w w w .j ava2 s . c o m parameterNodes = (NodeList) xpath.evaluate("er-ext:AttributeParameter", attributeParametersNode, XPathConstants.NODESET); } // XmlConverter converter = new XmlConverter(); // converter.getDocumentBuilderFactory().setNamespaceAware(true); // LOG.info(converter.toString(attributeParametersDocument)); for (int i = 0; i < parameterNodes.getLength(); i++) { Node node = parameterNodes.item(i); // From the attribute parameter element, extract the attribute xpath value // The namespace prefixes will need to be processed and added to the ER namespace context String attributeXpathValue = xpath.evaluate("er-ext:AttributeXPath", node); LOG.debug("Attribute parameter xpath value: " + attributeXpathValue); AttributeParametersXpathSupport parameter = new AttributeParametersXpathSupport(attributeXpathValue, node); String algorithmURI = xpath.evaluate("er-ext:AttributeMatchAlgorithmSimmetricsURICode", node); String botchedClassName = algorithmURI.replace("urn:org:search:ers:algorithms:", ""); String[] splitClassName = botchedClassName.split("\\."); StringBuffer reversedClassName = new StringBuffer(64); for (int ii = splitClassName.length - 2; ii >= 0; ii--) { reversedClassName.append(splitClassName[ii]).append("."); } reversedClassName.append(splitClassName[splitClassName.length - 1]); parameter.setAlgorithmClassName(reversedClassName.toString()); String isDeterm = xpath.evaluate("er-ext:AttributeIsDeterminativeIndicator", node); // LOG.info("$#$#$!!! isDeterm=" + isDeterm); parameter.setDeterminative("true".equals(isDeterm)); parameter.setThreshold(Double.parseDouble(xpath.evaluate("er-ext:AttributeThresholdValue", node))); Node sortNode = (Node) xpath.evaluate("er-ext:AttributeSortSpecification", node, XPathConstants.NODE); if (sortNode != null) { SortOrderSpecification sos = new SortOrderSpecification(); String sortOrder = xpath.evaluate("er-ext:AttributeSortOrder", sortNode); String sortOrderRankS = xpath.evaluate("er-ext:AttributeSortOrderRank", sortNode); if (sortOrder == null || sortOrderRankS == null) { throw new IllegalArgumentException( "If the AttributeSortSpecification element is specified, both sort order and rank must be specified."); } int sortOrderRank = Integer.parseInt(sortOrderRankS); sos.setSortOrder(sortOrder); sos.setSortOrderRank(sortOrderRank); parameter.setSortOrder(sos); } ret.add(parameter); } return ret; }
From source file:org.eclipse.lyo.testsuite.oslcv2.ServiceProviderXmlTests.java
@Test public void publisherElementsAreValid() throws XPathExpressionException { //Get all Publisher xml blocks NodeList publishers = (NodeList) OSLCUtils.getXPath().evaluate("//dc:publisher/*", doc, XPathConstants.NODESET); //Verify that each block contains a title and identifier, and at most one icon and label for (int i = 0; i < publishers.getLength(); i++) { NodeList publisherElements = publishers.item(i).getChildNodes(); int titleCount = 0; int identifierCount = 0; int iconCount = 0; int labelCount = 0; for (int j = 0; j < publisherElements.getLength(); j++) { Node ele = publisherElements.item(j); if (ele.getLocalName() == null) { continue; }/*from w ww .j ava 2 s .c o m*/ if (ele.getNamespaceURI().equals(OSLCConstants.DC) && ele.getLocalName().equals("title")) { titleCount++; } if (ele.getNamespaceURI().equals(OSLCConstants.DC) && ele.getLocalName().equals("identifier")) { identifierCount++; } if (ele.getNamespaceURI().equals(OSLCConstants.OSLC_V2) && ele.getLocalName().equals("label")) { labelCount++; } if (ele.getNamespaceURI().equals(OSLCConstants.OSLC_V2) && ele.getLocalName().equals("icon")) { iconCount++; } } assertTrue(titleCount == 1); assertTrue(identifierCount == 1); assertTrue(iconCount <= 1); assertTrue(labelCount <= 1); } }
From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestXmlTests.java
@Test public void changeRequestHasAtMostOneModifiedDate() throws XPathExpressionException { NodeList modifiedDates = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_cm_v2:ChangeRequest/dc:modified", doc, XPathConstants.NODESET); assertTrue(getFailureMessage(), modifiedDates.getLength() <= 1); //If there is a modified date, verify the format. if (modifiedDates.getLength() > 0) { try {/*from w w w . ja va 2 s. com*/ final String dateString = modifiedDates.item(0).getTextContent(); DatatypeConverter.parseDateTime(dateString); } catch (Exception e) { fail("Modified date not in valid XSD format"); } } }