Java Code Examples for javax.xml.xpath.XPath#evaluate()
The following examples show how to use
javax.xml.xpath.XPath#evaluate() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KmehrHelper.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
private boolean verifyXpath(String[] xpathConfigs, Document doc) throws XPathExpressionException, NumberFormatException, IntegrationModuleException { if (xpathConfigs == null) { return false; } String xpathStr = xpathConfigs[0]; int min = Integer.parseInt(xpathConfigs[1].trim()); int max = xpathConfigs.length > 2 ? Integer.parseInt(xpathConfigs[2].trim()) : Integer.MAX_VALUE; XPath xpath = XPathFactory.newInstance().newXPath(); NamespaceContext nsCtx = new MapNamespaceContext(); xpath.setNamespaceContext(nsCtx); NodeList nodes = (NodeList) xpath.evaluate(xpathStr, doc, XPathConstants.NODESET); if (nodes.getLength() < min || nodes.getLength() > max) { LOG.error("FAILED Xpath query : " + xpathStr); return false; //throw new IntegrationModuleException(I18nHelper.getLabel("error.xml.invalid")); } return true; }
Example 2
Source File: AndroidManifest.java From buck with Apache License 2.0 | 6 votes |
@NonNull private static String getStringValue(@NonNull IAbstractFile file, @NonNull String xPath) throws StreamException { XPath xpath = AndroidXPathFactory.newXPath(); InputStream is = null; try { is = file.getContents(); return xpath.evaluate(xPath, new InputSource(is)); } catch (XPathExpressionException e){ throw new RuntimeException( "Malformed XPath expression when reading the attribute from the manifest," + "exp = " + xPath, e); } finally { Closeables.closeQuietly(is); } }
Example 3
Source File: XMLSearchableAttributeContent.java From rice with Educational Community License v2.0 | 6 votes |
String getSearchContent() throws XPathExpressionException, ParserConfigurationException { if (searchContent == null) { Node cfg = getSearchingConfig(); XPath xpath = XPathHelper.newXPath(); Node n = (Node) xpath.evaluate("xmlSearchContent", cfg, XPathConstants.NODE); if (n != null) { StringBuilder sb = new StringBuilder(); NodeList list = n.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { sb.append(XmlJotter.jotNode(list.item(i))); } this.searchContent = sb.toString(); } } return searchContent; }
Example 4
Source File: Bug4991939.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
@Test public void testXPath13() throws Exception { QName qname = new QName(XMLConstants.XML_NS_URI, ""); XPathFactory xpathFactory = XPathFactory.newInstance(); Assert.assertNotNull(xpathFactory); XPath xpath = xpathFactory.newXPath(); Assert.assertNotNull(xpath); try { xpath.evaluate("1+1", (Object) null, qname); Assert.fail("failed , expected IAE not thrown"); } catch (IllegalArgumentException e) { ; // as expected } }
Example 5
Source File: SvgUtilities.java From waltz with Apache License 2.0 | 6 votes |
public static String convertVisioSvg(String key, String svgStr) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, TransformerException { DocumentBuilder builder = createNonValidatingDocumentBuilderFactory().newDocumentBuilder(); InputSource svgSource = new InputSource(new ByteArrayInputStream(svgStr.getBytes())); Document svg = builder.parse(svgSource); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xpath.evaluate("//*", svg, XPathConstants.NODESET); stream(nodes) .forEach(n -> stream(n.getChildNodes()) .filter(c -> c.getNodeName().contains("custProps")) .forEach(c -> stream(c.getChildNodes()) .filter(cp -> cp.getNodeName().contains("cp")) .map(cp -> (Element) cp) .filter(cp -> key.equals(cp.getAttribute("v:lbl"))) .map(cp -> cp.getAttribute("v:val")) .map(v -> v.replaceAll("^.*\\((.*)\\)$", "$1")) .forEach(v -> ((Element) n).setAttribute("data-"+key, v)) ) ); return printDocument(svg, false); // do NOT toPrettyString print visio }
Example 6
Source File: KmehrHelper.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
private boolean verifyXpath(String[] xpathConfigs1, String[] xpathConfigs2, Document doc) throws XPathExpressionException { if (xpathConfigs1 == null || xpathConfigs2 == null) { return false; } String xpathStr1 = xpathConfigs1[0]; String xpathStr2 = xpathConfigs2[0]; XPath xpath = XPathFactory.newInstance().newXPath(); NamespaceContext nsCtx = new MapNamespaceContext(); xpath.setNamespaceContext(nsCtx); Double count1 = (Double) xpath.evaluate(xpathStr1, doc, XPathConstants.NUMBER); Double count2 = (Double) xpath.evaluate(xpathStr2, doc, XPathConstants.NUMBER); if (!Objects.equals(count1, count2)) { LOG.error("FAILED Xpath query : " + xpathStr1 + " <==> " + xpathStr2); return false; } return true; }
Example 7
Source File: XliffUtils.java From mojito with Apache License 2.0 | 6 votes |
/** * Gets the target language of the XLIFF by looking at the first "file" * element. * * @param xliffContent xliff content from which to extract the target language * @return the target language or {@code null} if not found */ public String getTargetLanguage(String xliffContent) { String targetLanguage = null; InputSource inputSource = new InputSource(new StringReader(xliffContent)); XPath xPath = XPathFactory.newInstance().newXPath(); SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext(); simpleNamespaceContext.bindNamespaceUri("xlf", "urn:oasis:names:tc:xliff:document:1.2"); xPath.setNamespaceContext(simpleNamespaceContext); try { Node node = (Node) xPath.evaluate("/xlf:xliff/xlf:file[1]/@target-language", inputSource, XPathConstants.NODE); if(node != null) { targetLanguage = node.getTextContent(); } } catch (XPathExpressionException xpee) { logger.debug("Can't extract target language from xliff", xpee); } return targetLanguage; }
Example 8
Source File: XmlSignatureBuilder.java From freehealth-connector with GNU Affero General Public License v3.0 | 5 votes |
private static byte[] transform(boolean encapsulate, String xpathLocation, EncapsulationTransformer encapsulationTranformer, Document doc, XMLSignature sig) { if (!encapsulate) { return ConnectorXmlUtils.toByteArray((Node)sig.getElement()); } else { Node toInsert = doc.adoptNode(encapsulationTranformer.transform(sig.getElement())); Node insertBeforeNode = null; if (StringUtils.isNotBlank(xpathLocation)) { try { XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList)xPath.evaluate(xpathLocation, doc.getDocumentElement(), XPathConstants.NODESET); if (nodes.getLength() == 1) { LOG.debug("1 node found, inserting at location [" + xpathLocation + "]"); insertBeforeNode = nodes.item(0); } else { LOG.warn("XPATH error: " + nodes.getLength() + "found at location [" + xpathLocation + "],using default."); } } catch (XPathExpressionException var9) { LOG.info("Unable to determine XPath Location, using default.", var9); } } else { LOG.debug("Using default location (last child tag)"); } doc.getFirstChild().insertBefore(toInsert, insertBeforeNode); return ConnectorXmlUtils.toByteArray((Node)doc); } }
Example 9
Source File: WebserviceSAMLSPTestSetup.java From development with Apache License 2.0 | 5 votes |
private void updateElementValue(XPath path, Document doc, String pathValue, String attribute, String value) throws XPathExpressionException { Element node = (Element) path.evaluate(pathValue, doc, XPathConstants.NODE); if (node != null) { node.setAttribute(attribute, value); } }
Example 10
Source File: RuleAttributeXmlParser.java From rice with Educational Community License v2.0 | 5 votes |
public List parseRuleAttributes(Element element) throws XmlException { List ruleAttributes = new ArrayList(); try { XPath xpath = XPathHelper.newXPath(); NodeList nodeList = (NodeList)xpath.evaluate(XPATH_RULE_ATTRIBUTES, element, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node ruleAttributeNode = nodeList.item(i); ruleAttributes.add(parseRuleAttribute(ruleAttributeNode)); } for (Iterator iterator = ruleAttributes.iterator(); iterator.hasNext();) { RuleAttribute ruleAttribute = (RuleAttribute) iterator.next(); try { RuleAttribute existingAttribute = KEWServiceLocator.getRuleAttributeService().findByName(ruleAttribute.getName()); if (existingAttribute != null) { ruleAttribute.setId(existingAttribute.getId()); ruleAttribute.setVersionNumber(existingAttribute.getVersionNumber()); } KEWServiceLocator.getRuleAttributeService().save(ruleAttribute); } catch (Exception e) { LOG.error("Error saving rule attribute entered by XML", e); } } } catch (XPathExpressionException e1) { throw new XmlException("Could not find a rule attribute.", e1); } return ruleAttributes; }
Example 11
Source File: Http.java From BotLibre with Eclipse Public License 1.0 | 5 votes |
/** * Post the XML document object and return the XML data from the URL. */ public Vertex postXMLAuth(String url, String user, String password, Vertex xmlObject, String xpath, Network network) { log("POST XML Auth", Level.INFO, url); try { String data = convertToXML(xmlObject); log("POST XML", Level.FINE, data); String xml = Utils.httpAuthPOST(url, user, password, "application/xml", data); log("XML", Level.FINE, xml); InputStream stream = new ByteArrayInputStream(xml.getBytes("utf-8")); Element element = parseXML(stream); if (element == null) { return null; } XPathFactory factory = XPathFactory.newInstance(); XPath path = factory.newXPath(); Object node = path.evaluate(xpath, element, XPathConstants.NODE); if (node instanceof Element) { return convertElement((Element)node, network); } else if (node instanceof Attr) { return network.createVertex(((Attr)node).getValue()); } return null; } catch (Exception exception) { log(exception); return null; } }
Example 12
Source File: Http.java From BotLibre with Eclipse Public License 1.0 | 5 votes |
/** * Post the XML document object and return the XML data from the URL. */ public Vertex postXMLAuth(String url, String user, String password, String agent, Vertex xmlObject, String xpath, Network network) { log("POST XML Auth", Level.INFO, url); try { String data = convertToXML(xmlObject); log("POST XML", Level.FINE, data); String xml = Utils.httpAuthPOST(url, user, password, agent, "application/xml", data); log("XML", Level.FINE, xml); InputStream stream = new ByteArrayInputStream(xml.getBytes("utf-8")); Element element = parseXML(stream); if (element == null) { return null; } XPathFactory factory = XPathFactory.newInstance(); XPath path = factory.newXPath(); Object node = path.evaluate(xpath, element, XPathConstants.NODE); if (node instanceof Element) { return convertElement((Element)node, network); } else if (node instanceof Attr) { return network.createVertex(((Attr)node).getValue()); } else if (node instanceof org.w3c.dom.Text) { return network.createVertex(((org.w3c.dom.Text)node).getTextContent()); } return null; } catch (Exception exception) { log(exception); return null; } }
Example 13
Source File: CienaWaveserverAiDeviceDescriptionTest.java From onos with Apache License 2.0 | 5 votes |
@Test public void testDiscoverPortDetails() { List<PortDescription> result = new ArrayList<>(); List<PortDescription> expectResult = getExpectedPorts(); try { XPath xp = XPathFactory.newInstance().newXPath(); Node nodeListItem; Node node = doRequest("/response/discoverPortDetails.xml", "/rpc-reply/data"); NodeList nodeList = (NodeList) xp.evaluate("waveserver-ports/ports", node, XPathConstants.NODESET); int count = nodeList.getLength(); for (int i = 0; i < count; ++i) { nodeListItem = nodeList.item(i); DefaultAnnotations annotationPort = DefaultAnnotations.builder() .set(AnnotationKeys.PORT_NAME, xp.evaluate("port-id/text()", nodeListItem)) .set(AnnotationKeys.PROTOCOL, xp.evaluate("id/type/text()", nodeListItem)) .build(); String port = xp.evaluate("port-id/text()", nodeListItem); result.add(DefaultPortDescription.builder() .withPortNumber(PortNumber.portNumber( portIdConvert(port), port)) .isEnabled(portStateConvert(xp.evaluate( "state/operational-state/text()", nodeListItem))) .portSpeed(portSpeedToLong(xp.evaluate( "id/speed/text()", nodeListItem))) .type(Port.Type.PACKET) .annotations(annotationPort) .build()); } } catch (XPathExpressionException e) { e.printStackTrace(); } assertEquals(expectResult, result); }
Example 14
Source File: XPathQualifierResolver.java From rice with Educational Community License v2.0 | 5 votes |
protected void handleSimpleMap(Node baseNode, List<Map<String, String>> maps, ResolverConfig config, XPath xPath) throws XPathExpressionException { String attributeName = config.getExpressionMap().keySet().iterator().next(); String xPathExpression = config.getExpressionMap().get(attributeName); NodeList attributes = (NodeList)xPath.evaluate(xPathExpression, baseNode, XPathConstants.NODESET); for (int index = 0; index < attributes.getLength(); index++) { Element attributeElement = (Element)attributes.item(index); Map<String, String> map = new HashMap<String, String>(); String attributeValue = attributeElement.getTextContent(); if (LOG.isDebugEnabled()) { LOG.debug("Adding values to simple Map<String, String>: " + attributeName + "::" + attributeValue); } map.put(attributeName, attributeValue); maps.add(map); } }
Example 15
Source File: Http.java From BotLibre with Eclipse Public License 1.0 | 5 votes |
/** * GET the XML data from the URL. */ public Vertex requestXMLAuth(String url, String user, String password, String xpath, Network network) { log("GET XML Auth", Level.INFO, url); try { String xml = Utils.httpAuthGET(url, user, password); log("XML", Level.FINE, xml); InputStream stream = new ByteArrayInputStream(xml.getBytes("utf-8")); Element element = parseXML(stream); if (element == null) { return null; } if (xpath == null) { return convertElement(element, network); } XPathFactory factory = XPathFactory.newInstance(); XPath path = factory.newXPath(); Object node = path.evaluate(xpath, element, XPathConstants.NODE); if (node instanceof Element) { return convertElement((Element)node, network); } else if (node instanceof Attr) { return network.createVertex(((Attr)node).getValue()); } else if (node instanceof org.w3c.dom.Text) { return network.createVertex(((org.w3c.dom.Text)node).getTextContent()); } return null; } catch (Exception exception) { log(exception); return null; } }
Example 16
Source File: MockDriverHandler.java From onos with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public MockDriverHandler(Class<? extends AbstractDriverLoader> loaderClass, String behaviorSpec, DeviceId mockDeviceId, CoreService mockCoreService, DeviceService mockDeviceService) { // Had to split into declaration and initialization to make stylecheck happy // else line was considered too long // and auto format couldn't be tweak to make it correct Map<Class<? extends Behaviour>, Class<? extends Behaviour>> behaviours; behaviours = new HashMap<Class<? extends Behaviour>, Class<? extends Behaviour>>(); try { String data = Resources.toString(Resources.getResource(loaderClass, behaviorSpec), StandardCharsets.UTF_8); InputStream resp = IOUtils.toInputStream(data, StandardCharsets.UTF_8); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document document = builder.parse(resp); XPath xp = XPathFactory.newInstance().newXPath(); NodeList list = (NodeList) xp.evaluate("//behaviour", document, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i += 1) { Node node = list.item(i); NamedNodeMap attrs = node.getAttributes(); Class<? extends Behaviour> api = (Class<? extends Behaviour>) Class .forName(attrs.getNamedItem("api").getNodeValue()); Class<? extends Behaviour> impl = (Class<? extends Behaviour>) Class .forName(attrs.getNamedItem("impl").getNodeValue()); behaviours.put(api, impl); } init(behaviours, mockDeviceId, mockCoreService, mockDeviceService); } catch (Exception e) { fail(e.toString()); } }
Example 17
Source File: WebXmlParser.java From piranha with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Parse the default-context-path section. * * @param webXml the web.xml to add to. * @param xPath the XPath to use. * @param node the DOM node. */ private void parseDefaultContextPath(WebXml webXml, XPath xPath, Node node) { try { Node contextPathNode = (Node) xPath.evaluate("//default-context-path", node, NODE); if (contextPathNode != null) { String defaultContextPath = parseString(xPath, "//default-context-path/text()", node); if (defaultContextPath != null) { webXml.setDefaultContextPath(defaultContextPath); } } } catch (XPathException xpe) { LOGGER.log(WARNING, "Unable to parse <default-context-path> section", xpe); } }
Example 18
Source File: XPathWctMetsExtractor.java From webcurator with Apache License 2.0 | 4 votes |
private void populateCopyrightURL(Document doc, XPath xpath) throws XPathExpressionException { copyrightURL = (String) xpath.evaluate(copyrightURLQuery, doc, XPathConstants.STRING); }
Example 19
Source File: XPathWctMetsExtractor.java From webcurator with Apache License 2.0 | 4 votes |
private void populateProvenanceNote(Document doc, XPath xpath) throws XPathExpressionException { provenanceNote = (String) xpath.evaluate(provenanceNoteQuery, doc, XPathConstants.STRING); }
Example 20
Source File: XMLSchedulingDataProcessor.java From AsuraFramework with Apache License 2.0 | 3 votes |
protected Boolean getBoolean(XPath xpath, String elementName, Document document) throws XPathExpressionException { Node directive = (Node) xpath.evaluate(elementName, document, XPathConstants.NODE); if(directive == null || directive.getTextContent() == null) return null; String val = directive.getTextContent(); if(val.equalsIgnoreCase("true") || val.equalsIgnoreCase("yes") || val.equalsIgnoreCase("y")) return Boolean.TRUE; return Boolean.FALSE; }