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.adaptris.util.text.xml.XPath.java
/** * selects a list of Nodes from the context node using the supplied xpath * * @param context the root node to query * @param xpath the xpath to apply/* w w w .j av a 2s . c o m*/ * @return NodeList of returned Nodes * @throws XPathExpressionException on error. */ public NodeList selectNodeList(Node context, String xpath) throws XPathExpressionException { return (NodeList) createXpath().evaluate(xpath, context, XPathConstants.NODESET); }
From source file:org.dataconservancy.dcs.integration.main.ManualDepositIT.java
/** * Ensure that the <code>href</code> attribute values for <collection>s are valid URLs. *///from ww w. j av a2 s. c om @Test public void testServiceDocCollectionUrls() throws IOException, XPathExpressionException { final HttpGet req = new HttpGet(serviceDocUrl); final HttpResponse resp = client.execute(req); assertEquals("Unable to retrieve atompub service document " + serviceDocUrl, 200, resp.getStatusLine().getStatusCode()); final XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new NamespaceContext() { @Override public String getNamespaceURI(String prefix) { if ("app".equals(prefix) || prefix == null || "".equals(prefix)) { return ATOM_NS; } throw new RuntimeException("Unknown xmlns prefix: '" + prefix + "'"); } @Override public String getPrefix(String nsUri) { if (ATOM_NS.equals(nsUri)) { return "app"; } throw new RuntimeException("Unknown xmlns uri '" + nsUri + "'"); } @Override public Iterator<String> getPrefixes(String s) { ArrayList<String> prefixes = new ArrayList<String>(); prefixes.add("app"); return prefixes.iterator(); } }); final String xpathExpression = "//app:collection/@href"; final NodeList collectionHrefs = (NodeList) xpath.evaluate(xpathExpression, new InputSource(resp.getEntity().getContent()), XPathConstants.NODESET); assertTrue( "No atompub collections found in service document " + serviceDocUrl + " (xpath search '" + xpathExpression + "' yielded no results.", collectionHrefs != null && collectionHrefs.getLength() > 0); for (int i = 0; i < collectionHrefs.getLength(); i++) { final String collectionUrl = collectionHrefs.item(i).getNodeValue(); assertNotNull("atompub collection url was null.", collectionUrl); assertTrue("atompub collection url was the empty string.", collectionUrl.trim().length() > 0); new URL(collectionUrl); assertTrue("Expected atompub collection url to start with " + serviceDocUrl + " (collection url was: " + collectionUrl, collectionUrl.startsWith(serviceDocUrl)); } }
From source file:jGPIO.DTO.java
/** * Tries to use lshw to detect the physical system in use. * /*from w w w .j a v a2 s. co m*/ * @return The filename of the GPIO Definitions file. */ static private String autoDetectSystemFile() { String definitions = System.getProperty("definitions.lookup"); if (definitions == null) { definitions = DEFAULT_DEFINITIONS; } File capabilitiesFile = new File(definitions); // If it doesn't exist, fall back to the default if (!capabilitiesFile.exists() && !definitions.equals(DEFAULT_DEFINITIONS)) { System.out.println("Could not find definitions lookup file at: " + definitions); System.out.println("Trying default definitions file at: " + definitions); capabilitiesFile = new File(DEFAULT_DEFINITIONS); } if (!capabilitiesFile.exists()) { System.out.println("Could not find definitions file at: " + definitions); return null; } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = null; try { dBuilder = dbFactory.newDocumentBuilder(); } catch (ParserConfigurationException e1) { e1.printStackTrace(); } // Generate the lshw output if available Process lshw; try { lshw = Runtime.getRuntime().exec("lshw -c bus -disable dmi -xml"); lshw.waitFor(); } catch (Exception e1) { System.out.println("Couldn't execute lshw to identify board"); e1.printStackTrace(); return null; } Document lshwXML = null; try { lshwXML = dBuilder.parse(lshw.getInputStream()); } catch (IOException e1) { System.out.println("IO Exception running lshw"); e1.printStackTrace(); return null; } catch (SAXException e1) { System.out.println("Could not parse lshw output"); e1.printStackTrace(); return null; } XPath xp = XPathFactory.newInstance().newXPath(); NodeList capabilities; try { capabilities = (NodeList) xp.evaluate("/list/node[@id=\"core\"]/capabilities/capability", lshwXML, XPathConstants.NODESET); } catch (XPathExpressionException e1) { System.out.println("Couldn't run Caoability lookup"); e1.printStackTrace(); return null; } Document lookupDocument = null; try { lookupDocument = dBuilder.parse(capabilitiesFile); String lookupID = null; for (int i = 0; i < capabilities.getLength(); i++) { Node c = capabilities.item(i); lookupID = c.getAttributes().getNamedItem("id").getNodeValue(); System.out.println("Looking for: " + lookupID); NodeList nl = (NodeList) xp.evaluate("/lookup/capability[@id=\"" + lookupID + "\"]", lookupDocument, XPathConstants.NODESET); if (nl.getLength() == 1) { definitionFile = nl.item(0).getAttributes().getNamedItem("file").getNodeValue(); pinDefinitions = (JSONArray) new JSONParser().parse(new FileReader(definitionFile)); return definitionFile; } } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.impetus.ankush.common.utils.NmapUtil.java
/** * @throws ParserConfigurationException//from w ww . j a va 2 s. c o m * @throws SAXException * @throws IOException * @throws XPathExpressionException */ private static Map<String, String> getHostIPMapping(String filePath) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { // loading the XML document from a file DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance(); builderfactory.setNamespaceAware(true); DocumentBuilder builder = builderfactory.newDocumentBuilder(); File file = new File(filePath); Document xmlDocument = builder.parse(file); XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance(); XPath xPath = factory.newXPath(); // getting the name of the book having an isbn number == ABCD7327923 XPathExpression hostXpath = xPath.compile("//host"); XPathExpression ipXpath = xPath.compile("address[@addrtype='ipv4']/@addr"); XPathExpression hostNameXpath = xPath.compile("hostnames/hostname[@type='user']/@name"); NodeList nodeListHost = (NodeList) hostXpath.evaluate(xmlDocument, XPathConstants.NODESET); Map<String, String> hostIpMapping = new HashMap<String, String>(); for (int index = 0; index < nodeListHost.getLength(); index++) { String ip = (String) ipXpath.evaluate(nodeListHost.item(index), XPathConstants.STRING); String host = (String) hostNameXpath.evaluate(nodeListHost.item(index), XPathConstants.STRING); hostIpMapping.put(host, ip); } // deleting the temporary xml file. FileUtils.deleteQuietly(file); return hostIpMapping; }
From source file:com.esri.gpt.server.openls.provider.services.geocode.GeocodeProvider.java
/** * Reads Address Information from request * @param reqParams//from w ww . ja va 2 s .c om * @param ndReq * @param xpath * @throws XPathExpressionException */ public void parseRequest(GeocodeParams reqParams, Node ndReq, XPath xpath) throws XPathExpressionException { NodeList ndAddresses = (NodeList) xpath.evaluate("xls:Address", ndReq, XPathConstants.NODESET); if (ndAddresses != null) { for (int i = 0; i < ndAddresses.getLength(); i++) { Node address = ndAddresses.item(i); if (address != null) { Address addr = new Address(); Node ndStrAddr = (Node) xpath.evaluate("xls:StreetAddress", address, XPathConstants.NODE); if (ndStrAddr != null) { Node ndStr = (Node) xpath.evaluate("xls:Street", ndStrAddr, XPathConstants.NODE); if (ndStr != null) { addr.setStreet(ndStr.getTextContent()); } } Node ndPostalCode = (Node) xpath.evaluate("xls:PostalCode", address, XPathConstants.NODE); if (ndPostalCode != null) { addr.setPostalCode(ndPostalCode.getTextContent()); } NodeList ndPlaces = (NodeList) xpath.evaluate("xls:Place", address, XPathConstants.NODESET); if (ndPlaces != null) { for (int j = 0; j < ndPlaces.getLength(); j++) { Node ndPlace = ndPlaces.item(j); String type = Val .chkStr((String) xpath.evaluate("@type", ndPlace, XPathConstants.STRING)); addr.setPlaceType(type); if (type.equalsIgnoreCase("Municipality")) { addr.setMunicipality(ndPlace.getTextContent()); } else if (type.equalsIgnoreCase("CountrySubdivision")) { addr.setCountrySubdivision(ndPlace.getTextContent()); } else if (type.equalsIgnoreCase("BuildingNumber")) { addr.setBuildingNumber(ndPlace.getTextContent()); } else if (type.equalsIgnoreCase("Intersection")) { addr.setIntersection(ndPlace.getTextContent()); } else if (type.equalsIgnoreCase("StreetVec")) { addr.setStreetVec(ndPlace.getTextContent()); } } } reqParams.getAddresses().add(addr); } } } }
From source file:com.comcast.magicwand.spells.web.iexplore.IePhoenixDriver.java
/** * {@inheritDoc}/*from ww w . j a v a 2 s .co m*/ */ public boolean verify(PhoenixDriverIngredients i) { boolean rv = false; Map<String, Object> configs = i.getDriverConfigs(); LOGGER.debug("[version_property, arch_property] = [{}, {}]", (String) configs.get(IE_DRIVER_VERSION_KEY), (String) configs.get(IE_DRIVER_ARCH_KEY)); IePlatformSpecifics ips = this.createIePlatformSpecifics((String) configs.get(IE_DRIVER_VERSION_KEY), (String) configs.get(IE_DRIVER_ARCH_KEY)); if (!ips.isValid()) { LOGGER.error("The IePlatformSpecifics retrieved are not valid."); return false; } try { XPath xpath = XPathFactory.newInstance().newXPath(); String pwd = System.getProperty("user.dir"); String version = ips.getVersion(); String arch = ips.getArch(); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(IE_XML_DRIVER_LISTING_URL); NodeList nodes = (NodeList) xpath.evaluate(IE_XML_DRIVER_LISTING_XPATH, doc, XPathConstants.NODESET); String highestVersion = null; String needle = version + "/IEDriverServer_" + arch + "_"; for (int idx = 0; idx < nodes.getLength(); idx++) { Node n = nodes.item(idx); String text = n.getTextContent(); if (text.startsWith(needle)) { text = text.substring(needle.length(), text.length()); if (IePhoenixDriver.versionGreater(highestVersion, text)) { highestVersion = text; } } } if (null != highestVersion) { highestVersion = FilenameUtils.removeExtension(highestVersion); URL url = new URL(String.format(IE_HTTP_DRIVER_PATH_FORMAT, version, arch, highestVersion)); String zipName = String.format(IE_ZIP_FILE_FORMAT, arch, highestVersion); File ieSaveDir = new File(Paths.get(pwd, "target", "drivers", "iexplore", version).toString()); LOGGER.debug("Will read from \"{}\"", url); File zipFile = new File( Paths.get(pwd, "target", "drivers", "iexplore", version, zipName).toString()); FileUtils.copyURLToFile(url, zipFile); extract(zipFile, ieSaveDir.getAbsolutePath()); File exe = Paths.get(pwd, "target", "drivers", "iexplore", version, IE_EXE_FILE_NAME).toFile(); if (exe.exists()) { exe.setExecutable(true); systemSetProperty("webdriver.ie.driver", exe.getAbsolutePath()); this.webDriver = this.createDriver(i.getDriverCapabilities()); rv = true; } else { LOGGER.error("Extracted zip archive did nto contain \"{}\".", IE_EXE_FILE_NAME); } } else { LOGGER.error("Unable to find any IE Drivers from [{}]", IE_XML_DRIVER_LISTING_XPATH); } } catch (ParserConfigurationException | SAXException | XPathExpressionException err) { throw new RuntimeException(err); } catch (IOException ioe) { LOGGER.error("IO failure: {}", ioe); } return rv; }
From source file:com.wso2telco.identity.application.authentication.endpoint.util.TenantDataManager.java
private static void refreshActiveTenantDomainsList() { try {/*from www.j av a2s . c om*/ String url = "https://" + getPropertyValue(HOST) + ":" + getPropertyValue(PORT) + "/services/TenantMgtAdminService/retrieveTenants"; String xmlString = getServiceResponse(url); if (xmlString != null && !"".equals(xmlString)) { XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); InputSource inputSource = new InputSource(new StringReader(xmlString)); String xPathExpression = "/*[local-name() = '" + RETRIEVE_TENANTS_RESPONSE + "']/*[local-name() = '" + RETURN + "']"; NodeList nodeList = (NodeList) xpath.evaluate(xPathExpression, inputSource, XPathConstants.NODESET); tenantDomainList = new ArrayList<String>(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; NodeList tenantData = element.getChildNodes(); boolean activeChecked = false; boolean domainChecked = false; boolean isActive = false; String tenantDomain = null; for (int j = 0; j < tenantData.getLength(); j++) { Node dataItem = tenantData.item(j); String localName = dataItem.getLocalName(); if (ACTIVE.equals(localName)) { activeChecked = true; if ("true".equals(dataItem.getTextContent())) { isActive = true; } } if (TENANT_DOMAIN.equals(localName)) { domainChecked = true; tenantDomain = dataItem.getTextContent(); } if (activeChecked && domainChecked) { if (isActive) { tenantDomainList.add(tenantDomain); } break; } } } } Collections.sort(tenantDomainList); } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Retrieving Active Tenant Domains Failed. Ignore this if there are no tenants : ", e); } } }
From source file:jp.go.nict.langrid.bpel.ProcessAnalyzer.java
/** * /*from w w w .j av a 2 s. c om*/ * */ public static BPEL analyzeBPEL(byte[] body) throws SAXException, URISyntaxException, XPathExpressionException { Document doc; try { doc = builder.parse(new ByteArrayInputStream(body)); } catch (IOException e) { throw new RuntimeException(e); } Node root = doc.getDocumentElement(); NamespaceContextImpl nsc = new NamespaceContextImpl(); addNamespaceMappings(nsc, root.getAttributes()); String rootNs = root.getNamespaceURI(); nsc.addMapping("_", rootNs); XPath xpath = DocumentUtil.getDefaultXPath(); xpath.setNamespaceContext(nsc); String processName = NodeUtil.getAttribute(root, "name"); BPEL bpel = new BPEL(); bpel.setBody(body); if (rootNs.equals(bpel4ws_1_1_ns)) { bpel.setBpelVersion(BPELVersion.BPEL4WS_1_1); } else if (rootNs.equals(wsbpel_2_0_ns)) { bpel.setBpelVersion(BPELVersion.WSBPEL_2_0); } else { bpel.setBpelVersion(BPELVersion.UNKNOWN); } bpel.setTargetNamespace(new URI(xpath.evaluate("/_:process/@targetNamespace", root))); bpel.setProcessName(processName); bpel.setFilename(processName + BPEL_EXTENSION); ArrayList<PartnerLink> links = new ArrayList<PartnerLink>(); NodeList list = (NodeList) xpath.evaluate("/_:process/_:partnerLinks/_:partnerLink", root, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); PartnerLink pl = new PartnerLink(nsc, node); links.add(pl); } bpel.setPartnerLinks(links); return bpel; }
From source file:com.espertech.esper.event.xml.BaseXMLEventType.java
/** * Set the preconfigured event properties resolved by XPath expression. * @param explicitXPathProperties are preconfigured event properties * @param additionalSchemaProperties the explicit properties *//*from w ww . j av a2 s.co m*/ protected void initialize(Collection<ConfigurationEventTypeXMLDOM.XPathPropertyDesc> explicitXPathProperties, List<ExplicitPropertyDescriptor> additionalSchemaProperties) { // make sure we override those explicitly provided with those derived from a metadataz Map<String, ExplicitPropertyDescriptor> namedProperties = new LinkedHashMap<String, ExplicitPropertyDescriptor>(); for (ExplicitPropertyDescriptor desc : additionalSchemaProperties) { namedProperties.put(desc.getDescriptor().getPropertyName(), desc); } String xpathExpression = null; try { for (ConfigurationEventTypeXMLDOM.XPathPropertyDesc property : explicitXPathProperties) { XPath xPath = xPathFactory.newXPath(); if (namespaceContext != null) { xPath.setNamespaceContext(namespaceContext); } xpathExpression = property.getXpath(); if (log.isInfoEnabled()) { log.info("Compiling XPath expression for property '" + property.getName() + "' as '" + xpathExpression + "'"); } XPathExpression expression = xPath.compile(xpathExpression); FragmentFactoryXPathPredefinedGetter fragmentFactory = null; boolean isFragment = false; if (property.getOptionaleventTypeName() != null) { fragmentFactory = new FragmentFactoryXPathPredefinedGetter(this.getEventAdapterService(), property.getOptionaleventTypeName(), property.getName()); isFragment = true; } boolean isArray = false; if (property.getType().equals(XPathConstants.NODESET)) { isArray = true; } EventPropertyGetter getter = new XPathPropertyGetter(property.getName(), xpathExpression, expression, property.getType(), property.getOptionalCastToType(), fragmentFactory); Class returnType = SchemaUtil.toReturnType(property.getType(), property.getOptionalCastToType()); EventPropertyDescriptor desc = new EventPropertyDescriptor(property.getName(), returnType, null, false, false, isArray, false, isFragment); ExplicitPropertyDescriptor explicit = new ExplicitPropertyDescriptor(desc, getter, isArray, property.getOptionaleventTypeName()); namedProperties.put(desc.getPropertyName(), explicit); } } catch (XPathExpressionException ex) { throw new EPException( "XPath expression could not be compiled for expression '" + xpathExpression + '\'', ex); } super.initialize(new ArrayList<ExplicitPropertyDescriptor>(namedProperties.values())); // evaluate start and end timestamp properties if any startTimestampPropertyName = configurationEventTypeXMLDOM.getStartTimestampPropertyName(); endTimestampPropertyName = configurationEventTypeXMLDOM.getEndTimestampPropertyName(); EventTypeUtility.validateTimestampProperties(this, startTimestampPropertyName, endTimestampPropertyName); }