List of usage examples for javax.xml.xpath XPathFactory newXPath
public abstract XPath newXPath();
Return a new XPath
using the underlying object model determined when the XPathFactory was instantiated.
From source file:org.mycore.common.xml.MCRXMLFunctions.java
/** * The method return a org.w3c.dom.NodeList as subpath of the doc input * NodeList selected by a path as String. * * @param doc/* w ww . j a v a 2 s . c o m*/ * the input org.w3c.dom.Nodelist * @param path * the path of doc as String * @return a subpath of doc selected by path as org.w3c.dom.NodeList */ public static NodeList getTreeByPath(NodeList doc, String path) { NodeList n = null; DocumentBuilder documentBuilder = MCRDOMUtils.getDocumentBuilderUnchecked(); try { // build path selection XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(path); // select part Document document = documentBuilder.newDocument(); if (doc.item(0).getNodeName().equals("#document")) { // LOGGER.debug("NodeList is a document."); Node child = doc.item(0).getFirstChild(); if (child != null) { Node node = (Node) doc.item(0).getFirstChild(); Node imp = document.importNode(node, true); document.appendChild(imp); } else { document.appendChild(doc.item(0)); } } n = (NodeList) expr.evaluate(document, XPathConstants.NODESET); } catch (Exception e) { e.printStackTrace(); } finally { MCRDOMUtils.releaseDocumentBuilder(documentBuilder); } return n; }
From source file:org.netbeans.jcode.rest.util.RestUtils.java
public static String getAttributeValue(Node n, String nodePath, String attrName) throws XPathExpressionException { String attrValue = null;// w w w . ja va2 s .c o m XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr3 = xpath.compile(nodePath + "/@" + attrName); Object result3 = expr3.evaluate(n, XPathConstants.NODESET); NodeList nodes3 = (NodeList) result3; for (int i = 0; i < nodes3.getLength(); i++) { attrValue = nodes3.item(i).getNodeValue(); break; } return attrValue; }
From source file:org.nuxeo.launcher.connect.ConnectBroker.java
protected List<String> getDistributionFilenames() { File distributionMPFile = new File(distributionMPDir, PACKAGES_XML); List<String> md5Filenames = new ArrayList<>(); // Try to get md5 files from packages.xml DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true);//from www .ja v a 2 s . co m try { DocumentBuilder builder = docFactory.newDocumentBuilder(); Document doc = builder.parse(distributionMPFile); XPathFactory xpFactory = XPathFactory.newInstance(); XPath xpath = xpFactory.newXPath(); XPathExpression expr = xpath.compile("//package/@md5"); NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { String md5 = nodes.item(i).getNodeValue(); if ((md5 != null) && (md5.length() > 0)) { md5Filenames.add(md5); } } } catch (Exception e) { // Parsing failed - return empty list log.error("Failed parsing " + distributionMPFile, e); return new ArrayList<>(); } return md5Filenames; }
From source file:ORG.oclc.os.SRW.SRWOpenSearchDatabase.java
@Override public void init(String dbname, String srwHome, String dbHome, String dbPropertiesFileName, Properties dbProperties, HttpServletRequest request) throws Exception { log.debug("entering SRWOpenSearchDatabase.init, dbname=" + dbname); super.initDB(dbname, srwHome, dbHome, dbPropertiesFileName, dbProperties); String urlStr = dbProperties.getProperty("SRWOpenSearchDatabase.OpenSearchDescriptionURL"); author = dbProperties.getProperty("SRWOpenSearchDatabase.author"); contact = dbProperties.getProperty("SRWOpenSearchDatabase.contact"); description = dbProperties.getProperty("SRWOpenSearchDatabase.description"); restrictions = dbProperties.getProperty("SRWOpenSearchDatabase.restrictions"); title = dbProperties.getProperty("SRWOpenSearchDatabase.title"); defaultSchemaName = dbProperties.getProperty("SRWOpenSearchDatabase.defaultSchemaName"); defaultSchemaID = dbProperties.getProperty("SRWOpenSearchDatabase.defaultSchemaID"); itemsPerPage = Integer.parseInt(dbProperties.getProperty("SRWOpenSearchDatabase.itemsPerPage", "0")); URL url = new URL(urlStr); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder sb = new StringBuilder(); String inputLine;/*from www . jav a2 s. com*/ while ((inputLine = in.readLine()) != null) sb.append(inputLine).append('\n'); in.close(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(sb.toString()))); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr; if (contact == null) { expr = xpath.compile("/OpenSearchDescription/Contact"); contact = (String) expr.evaluate(document, XPathConstants.STRING); } if (description == null) { expr = xpath.compile("/OpenSearchDescription/Description"); description = (String) expr.evaluate(document, XPathConstants.STRING); } if (restrictions == null) { expr = xpath.compile("/OpenSearchDescription/SyndicationRight"); restrictions = (String) expr.evaluate(document, XPathConstants.STRING); if (restrictions != null) restrictions = "SynticationRight=" + restrictions; expr = xpath.compile("/OpenSearchDescription/Attribution"); String attribution = (String) expr.evaluate(document, XPathConstants.STRING); if (attribution != null) if (restrictions != null) restrictions = restrictions + ", Attribution=" + attribution; else restrictions = "Attribution=" + attribution; } if (title == null) { expr = xpath.compile("/OpenSearchDescription/LongName"); title = (String) expr.evaluate(document, XPathConstants.STRING); } expr = xpath.compile("/OpenSearchDescription/Url"); NodeList nl = (NodeList) expr.evaluate(document, XPathConstants.NODESET); NamedNodeMap attrs; String template, type; if (nl.getLength() == 0) { throw new InstantiationException("No OpenSearchDescription/Url found in " + url); } for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); attrs = n.getAttributes(); n = attrs.getNamedItem("template"); template = n.getTextContent(); log.debug("template=" + template); n = attrs.getNamedItem("type"); type = n.getTextContent(); log.info("<Url type='" + type + "' template='" + template + "'/>"); if ("application/rss+xml".equals(type)) { addSchema("RSS2.0", "rss", "http://europa.eu/rapid/conf/RSS20.xsd", "RSS Items", template); } } log.debug("leaving SRWOpenSearchDatabase.init"); }
From source file:org.ojbc.web.portal.controllers.PortalController.java
public PortalController() { XPathFactory xPathFactory = XPathFactory.newInstance(); xPath = xPathFactory.newXPath(); xPath.setNamespaceContext(new Saml2NamespaceContext()); // This map is used to translate those possible values for "searchProfilesEnabled" map entries // that represent visible states ("enabled", "disabled") into booleans indicating whether they are actually enabled visibleProfileStateMap = new HashMap<String, Boolean>(); visibleProfileStateMap.put("enabled", true); visibleProfileStateMap.put("disabled", false); }
From source file:org.onebusaway.transit_data_federation.impl.realtime.SiriLikeRealtimeSource.java
@PostConstruct public void setup() throws Exception { ISO_DATE_FORMAT.setLenient(false);/*w w w .j a v a 2 s. c o m*/ ISO_DATE_SHORT_FORMAT.setLenient(false); factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); mvjExpression = xpath.compile("/Siri/VehicleMonitoringDelivery/VehicleActivity/MonitoredVehicleJourney"); tripIdExpression = xpath.compile("FramedVehicleJourneyRef/DatedVehicleJourneyRef/text()"); serviceDateExpression = xpath.compile("FramedVehicleJourneyRef/DataFrameRef/text()"); recordedAtExpression = xpath .compile("/Siri/VehicleMonitoringDelivery/VehicleActivity/RecordedAtTime/text()"); vehicleIdExpression = xpath.compile("VehicleRef/text()"); latExpression = xpath.compile("VehicleLocation/Latitude/text()"); lonExpression = xpath.compile("VehicleLocation/Longitude/text()"); if (_refreshInterval > 0) { _refreshTask = _scheduledExecutorService.scheduleAtFixedRate(new RefreshTask(), 0, _refreshInterval, TimeUnit.SECONDS); } }
From source file:org.openecomp.sdnc.uebclient.SdncUebCallback.java
private DistributionStatusEnum deploySpoolFile(DeployableArtifact artifact) { DistributionStatusEnum deployResult = DistributionStatusEnum.DEPLOY_OK; StringBuffer msgBuffer = new StringBuffer(); String namespace = config.getAsdcApiNamespace(); if ((namespace == null) || (namespace.length() == 0)) { namespace = "com:att:sdnctl:asdcapi"; }/* w w w .ja va2 s . co m*/ msgBuffer.append("<input xmlns='"); msgBuffer.append(namespace); msgBuffer.append("'>\n"); String svcName = artifact.getSvcName(); String resourceName = artifact.getResourceName(); String artifactName = artifact.getArtifactName(); if (svcName != null) { if (resourceName != null) { artifactName = svcName + "/" + resourceName + "/" + artifactName; } else { artifactName = svcName + "/" + artifactName; } } msgBuffer.append("<artifact-name>" + artifactName + "</artifact-name>\n"); msgBuffer.append("<artifact-version>" + artifact.getArtifactVersion() + "</artifact-version>\n"); try { BufferedReader rdr = new BufferedReader(new FileReader(artifact.getFile())); String curLine = rdr.readLine(); while (curLine != null) { if (!curLine.startsWith("<?")) { msgBuffer.append(curLine + "\n"); } curLine = rdr.readLine(); } rdr.close(); } catch (Exception e) { LOG.error("Could not process spool file " + artifact.getFile().getName(), e); return (DistributionStatusEnum.DEPLOY_ERROR); } msgBuffer.append("</input>\n"); byte[] msgBytes = msgBuffer.toString().getBytes(); Document results = postRestXml(artifact.getType().getRpcUrl(config.getAsdcApiBaseUrl()), msgBytes); if (results == null) { deployResult = DistributionStatusEnum.DEPLOY_ERROR; } else { XPathFactory xpf = XPathFactory.newInstance(); XPath xp = xpf.newXPath(); String asdcApiResponseCode = "500"; try { asdcApiResponseCode = xp.evaluate("//asdc-api-response-code[position()=1]/text()", results.getDocumentElement()); } catch (Exception e) { LOG.error("Caught exception retrying to evaluate xpath", e); } if (asdcApiResponseCode.contains("200")) { LOG.info("Update to SDN-C succeeded"); deployResult = DistributionStatusEnum.DEPLOY_OK; } else { LOG.info("Update to SDN-C failed (response code " + asdcApiResponseCode + ")"); if (asdcApiResponseCode.contains("409")) { deployResult = DistributionStatusEnum.ALREADY_DEPLOYED; } else { deployResult = DistributionStatusEnum.DEPLOY_ERROR; } } } return (deployResult); }
From source file:org.openhab.binding.autelis.handler.AutelisHandler.java
/** * The polling future executes this every iteration *//*w w w . j a v a 2 s.c o m*/ protected void execute() { logger.trace("Connecting to {}" + baseURL); clearState(); // we will reconstruct the document with all the responses combined for // XPATH StringBuilder sb = new StringBuilder("<response>"); // pull down the three xml documents String[] statuses = { "status", "chem", "pumps" }; for (String status : statuses) { String response = getUrl(baseURL + "/" + status + ".xml", TIMEOUT); logger.trace(baseURL + "/" + status + ".xml \n {}", response); if (response == null) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR); return; } // get the xml data between the response tags and append to our main // doc Matcher m = responsePattern.matcher(response); if (m.find()) { sb.append(m.group(1)); } } // finish our "new" XML Document sb.append("</response>"); updateStatus(ThingStatus.ONLINE); /* * This xmlDoc will now contain the three XML documents we retrieved * wrapped in response tags for easier querying in XPath. */ String xmlDoc = sb.toString(); for (Channel channel : getThing().getChannels()) { String key = channel.getUID().getId().replace('-', '/'); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); try { InputSource is = new InputSource(new StringReader(xmlDoc)); String value = xpath.evaluate("response/" + key, is); if (StringUtils.isEmpty((value))) continue; State state = toState(channel.getAcceptedItemType(), value); State oldState = stateMap.put(channel.getUID().getAsString(), state); if (!state.equals(oldState)) { logger.trace("updating channel {} with state {}", channel, state); updateState(channel.getUID(), state); } } catch (XPathExpressionException e) { logger.error("could not parse xml", e); } } }
From source file:org.openhab.binding.autelis.internal.AutelisBinding.java
/** * @{inheritDoc}/*from www . j a v a 2s . c o m*/ */ @Override protected void execute() { logger.trace("Connecting to {}" + baseURL); clearState(); String xmlDoc = fetchStateFromController(); if (xmlDoc == null) return; for (AutelisBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { Item item = provider.getItem(itemName); String config = provider.getAutelisBindingConfigString(itemName); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); try { InputSource is = new InputSource(new StringReader(xmlDoc)); String value = xpath.evaluate("response/" + config.replace('.', '/'), is); State state = toState(item.getClass(), value); State oldState = stateMap.put(itemName, state); if (!state.equals(oldState)) { logger.debug("updating item {} with state {}", itemName, state); eventPublisher.postUpdate(itemName, state); } } catch (XPathExpressionException e) { logger.warn("could not parse xml", e); } } } }
From source file:org.openhab.binding.autelis.internal.handler.AutelisHandler.java
/** * Poll the Autelis controller for updates. This will retrieve various xml documents and update channel states from * its contents.//from w w w. j a v a 2 s . c om */ private void pollAutelisController() { logger.trace("Connecting to {}", baseURL); // clear our cached stated IF it is time. clearState(false); // we will reconstruct the document with all the responses combined for XPATH StringBuilder sb = new StringBuilder("<response>"); // pull down the three xml documents String[] statuses = { "status", "chem", "pumps" }; for (String status : statuses) { String response = getUrl(baseURL + "/" + status + ".xml", TIMEOUT_SECONDS); logger.trace("{}/{}.xml \n {}", baseURL, status, response); if (response == null) { // all models and versions have the status.xml endpoint if (status.equals("status")) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR); return; } else { // not all models have the other endpoints, so we ignore errors continue; } } // get the xml data between the response tags and append to our main // doc Matcher m = responsePattern.matcher(response); if (m.find()) { sb.append(m.group(1)); } } // finish our "new" XML Document sb.append("</response>"); if (!ThingStatus.ONLINE.equals(getThing().getStatus())) { updateStatus(ThingStatus.ONLINE); } /* * This xmlDoc will now contain the three XML documents we retrieved * wrapped in response tags for easier querying in XPath. */ HashMap<String, String> pumps = new HashMap<>(); String xmlDoc = sb.toString(); for (Channel channel : getThing().getChannels()) { String key = channel.getUID().getId().replaceFirst("-", "/"); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); try { InputSource is = new InputSource(new StringReader(xmlDoc)); String value = null; /** * Work around for Pentair pumps. Rather then have child XML elements, the response rather uses commas * on the pump response to separate the different values like so: * * watts,rpm,gpm,filter,error * * Also, some pools will only report the first 3 out of the 5 values. */ Matcher matcher = PUMPS_PATTERN.matcher(key); if (matcher.matches()) { if (!pumps.containsKey(key)) { String pumpValue = xpath.evaluate("response/" + matcher.group(1), is); String[] values = pumpValue.split(","); for (int i = 0; i < PUMP_TYPES.length; i++) { // this will be something like pump/pump1-rpm String newKey = matcher.group(1) + '-' + PUMP_TYPES[i]; // some Pentair models only have the first 3 values if (i < values.length) { pumps.put(newKey, values[i]); } else { pumps.put(newKey, ""); } } } value = pumps.get(key); } else { value = xpath.evaluate("response/" + key, is); // Convert pentair salt levels to PPM. if ("chlor/salt".equals(key)) { try { value = String.valueOf(Integer.parseInt(value) * 50); } catch (NumberFormatException ignored) { logger.debug("Failed to parse pentair salt level as integer"); } } } if (StringUtils.isEmpty((value))) { continue; } State state = toState(channel.getAcceptedItemType(), value); State oldState = stateMap.put(channel.getUID().getAsString(), state); if (!state.equals(oldState)) { logger.trace("updating channel {} with state {} (old state {})", channel.getUID(), state, oldState); updateState(channel.getUID(), state); } } catch (XPathExpressionException e) { logger.error("could not parse xml", e); } } }