/** * selectXMLNode * * @param xpath * @return Node */ public Node selectXMLNode(String xpath) { for (Document doc : this.docs) { try { Node node = (Node) this.xpath.evaluate(xpath, doc, XPathConstants.NODE); if (null != node) { return node; } } catch (XPathExpressionException e) { if (this.logger.isLogEnabled()) { this.logger.warn("Select nodes[" + xpath + "] from doc[" + doc + "] FAILs.", e); } } } return null; }
/** * Returns the version * * @return String */ public static String getVersion() { String jarImplementation = VISNode.class.getPackage().getImplementationVersion(); if (jarImplementation != null) { return jarImplementation; } String file = VISNode.class.getResource(".").getFile(); String pack = VISNode.class.getPackage().getName().replace(".", "/") + '/'; File pomXml = new File(file.replace("target/classes/" + pack, "pom.xml")); if (pomXml.exists()) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new FileReader(pomXml))); XPath xPath = XPathFactory.newInstance().newXPath(); return (String) xPath.evaluate("/project/version", document, XPathConstants.STRING); } catch (IOException | ParserConfigurationException | XPathExpressionException | SAXException e) { } } return "Unknown version"; }
public NodeInfoList find(UiElement context) throws Exception { Element domNode = getDomNode((UiElement<?, ?>) context); NodeInfoList list = new NodeInfoList(); getDocument().appendChild(domNode); NodeList nodes = (NodeList) xPathExpression.evaluate(domNode, XPathConstants.NODESET); int nodesLength = nodes.getLength(); for (int i = 0; i < nodesLength; i++) { if (nodes.item(i).getNodeType() == Node.ELEMENT_NODE && !FROM_DOM_MAP.get(nodes.item(i)).getClassName().equals("hierarchy")) { list.addToList(FROM_DOM_MAP.get(nodes.item(i)).node); } } try { getDocument().removeChild(domNode); } catch (DOMException e) { document = null; } return list; }
private void handleRequireModules(AddOnVersion addOnVersion, XPath xpath, Document config) throws XPathExpressionException { NodeList nodeList = (NodeList) xpath.evaluate("/module/require_modules/require_module", config, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { Node item = nodeList.item(i); Node version = item.getAttributes().getNamedItem("version"); String requiredModule = item.getTextContent().trim(); String requiredVersion = version == null ? null : version.getTextContent().trim(); // sometimes modules are inadvertently uploaded without substituting maven variables in config.xml and we end // up with a required module version like ${reportingVersion} if (requiredVersion != null && requiredVersion.startsWith("${")) { requiredVersion = null; } addOnVersion.addRequiredModule(requiredModule, requiredVersion); } }
public Element unwrapSoapMessage(Element soapElement) { XPath xpath = XPathFactory.newInstance().newXPath(); NamespaceContextImpl context = new NamespaceContextImpl(); context.startPrefixMapping("soapenv", "http://schemas.xmlsoap.org/soap/envelope/"); context.startPrefixMapping("samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); context.startPrefixMapping("saml", "urn:oasis:names:tc:SAML:2.0:assertion"); context.startPrefixMapping("ds", "http://www.w3.org/2000/09/xmldsig#"); xpath.setNamespaceContext(context); try { final String expression = "/soapenv:Envelope/soapenv:Body/samlp:Response"; Element element = (Element) xpath.evaluate(expression, soapElement, XPathConstants.NODE); if (element == null) { String errorMessage = format("Document{0}{1}{0}does not have element {2} inside it.", NEW_LINE, writeToString(soapElement), expression); LOG.error(errorMessage); throw new IllegalArgumentException(errorMessage); } return element; } catch (XPathExpressionException e) { throw propagate(e); } }
/** * Check the given document against the list of XPath statements provided. * * @param doc the XML document * @return Returns a content worker that was matched or <tt>null</tt> */ private W processDocument(Document doc) { for (Map.Entry<String, W> entry : workersByXPath.entrySet()) { try { String xpath = entry.getKey(); W worker = entry.getValue(); // Execute the statement Object ret = xpathFactory.newXPath().evaluate(xpath, doc, XPathConstants.NODE); if (ret != null) { // We found one return worker; } } catch (XPathExpressionException e) { // We accept this and move on } } // Nothing found return null; }
/** * Get values matching passed XPath expression * @param node * @param expression XPath expression * @return matching values * @throws Exception */ private static String[] getByXpath( Node node, String expression ) throws Exception { XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); XPathExpression xPathExpression = xPath.compile(expression); NodeList nlist = (NodeList) xPathExpression.evaluate(node, XPathConstants.NODESET); int nodeListSize = nlist.getLength(); List<String> values = new ArrayList<String>(nodeListSize); for (int index = 0; index < nlist.getLength(); index++) { Node aNode = nlist.item(index); values.add(aNode.getTextContent()); } return values.toArray(new String[values.size()]); }
protected static void countColumns(XPath xPath, Table table, Node tableHead) throws XPathExpressionException, DOMException, NumberFormatException { if (tableHead != null) { Node firstRow = (Node) xPath.compile("*[1]").evaluate(tableHead, XPathConstants.NODE); NodeList childFirstRows = firstRow.getChildNodes(); int columnNumber = 0; for (int w = 0; w < childFirstRows.getLength(); w++) { Node childFirstRow = childFirstRows.item(w); if (childFirstRow.getNodeValue() == null && (childFirstRow.getNodeName() == "th" || childFirstRow.getNodeName() == "td")) { int number = 1; if (childFirstRow.getAttributes().getNamedItem("colspan") != null) { number = Integer.parseInt(childFirstRow.getAttributes().getNamedItem("colspan").getNodeValue()); } columnNumber = columnNumber + number; } } table.setColumnNumber(columnNumber); } }
@Override public void parse(Consumer<MnoInfo> consumer) throws Exception { File fXmlFile = config.toFile(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); XPathExpression xpathMno = XPathFactory.newInstance().newXPath().compile("//*[local-name()='mno']"); XPathExpression xpathMasksMno = XPathFactory.newInstance().newXPath().compile("//*[local-name()='mask']"); NodeList mnoNodes = (NodeList) xpathMno.evaluate(doc, XPathConstants.NODESET); for (int i=0; i<mnoNodes.getLength(); i++) { Node node = mnoNodes.item(i); NamedNodeMap attributes = node.getAttributes(); String country = getValue(attributes.getNamedItem("country")); String title = getValue(attributes.getNamedItem("title")); String area = getValue(attributes.getNamedItem("area")); Set<Mask> masks = new HashSet<>(); NodeList maskNodes = (NodeList) xpathMasksMno.evaluate(doc, XPathConstants.NODESET); for (int j=0; j<maskNodes.getLength(); j++) { masks.add(Mask.parse(getValue(maskNodes.item(j)))); } consumer.accept(new MnoInfo(title, area, country, masks)); } }
/** * Performs all file existence checks contained in the validation profile. If the validation has failed (some of the files specified * in the validation profile do not exist), {@link MissingFile} exception is thrown. * * @param sipPath path to the SIP * @param validationProfileDoc document with the validation profile * @param validationProfileId id of the validation profile * @throws XPathExpressionException if there is an error in the XPath expression */ private void performFileExistenceChecks(String sipPath, Document validationProfileDoc, String validationProfileId) throws XPathExpressionException { XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.compile("/profile/rule/fileExistenceCheck") .evaluate(validationProfileDoc, XPathConstants.NODESET); for (int i = 0; i< nodes.getLength(); i++) { Element element = (Element) nodes.item(i); String relativePath = element.getElementsByTagName("filePath").item(0).getTextContent(); String absolutePath = sipPath + relativePath; if (!ValidationChecker.fileExists(absolutePath)) { log.info("Validation of SIP with profile " + validationProfileId + " failed. File at \"" + relativePath + "\" is missing."); throw new MissingFile(relativePath, validationProfileId); } } }
/** * Performs all validation schema checks contained in the validation profile. If the validation has failed (some of the XMLs * specified in the validation profile do not match their respective validation schemas) {@link SchemaValidationError} is thrown. * * @param sipPath path to the SIP * @param validationProfileDoc document with the validation profile * @param validationProfileId id of the validation profile * @throws IOException if some of the XMLs address from the validation profile does not exist * @throws XPathExpressionException if there is an error in the XPath expression * @throws SAXException if the XSD schema is invalid */ private void performValidationSchemaChecks(String sipPath, Document validationProfileDoc, String validationProfileId) throws XPathExpressionException, IOException, SAXException { XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.compile("/profile/rule/validationSchemaCheck") .evaluate(validationProfileDoc, XPathConstants.NODESET); for (int i = 0; i< nodes.getLength(); i++) { Element element = (Element) nodes.item(i); String filePath = element.getElementsByTagName("filePath").item(0).getTextContent(); String schema = element.getElementsByTagName("schema").item(0).getTextContent(); String absoluteFilePath = sipPath + filePath; try { ValidationChecker.validateWithXMLSchema(new FileInputStream(absoluteFilePath), new InputStream[] { new ByteArrayInputStream(schema.getBytes(StandardCharsets.UTF_8.name()))}); } catch (GeneralException e) { log.info("Validation of SIP with profile " + validationProfileId + " failed. File at \"" + filePath + "\" is not " + "valid against its corresponding schema."); throw new SchemaValidationError(filePath, schema, e.getMessage()); } } }
@Test public void testXPath11() throws Exception { try { Document d = null; XPathFactory xpathFactory = XPathFactory.newInstance(); Assert.assertNotNull(xpathFactory); XPath xpath = xpathFactory.newXPath(); Assert.assertNotNull(xpath); String quantity = (String) xpath.evaluate("/widgets/widget[@name='a']/@quantity", d, XPathConstants.STRING); Assert.fail("XPathExpressionException not thrown"); } catch (XPathExpressionException e) { // Expected exception as context node is null } }
public static Iterator<Node> getNodeList(String exp, Element dom) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expUserTask = xpath.compile(exp); final NodeList nodeList = (NodeList) expUserTask.evaluate(dom, XPathConstants.NODESET); return new Iterator<Node>() { private int index = 0; @Override public Node next() { return nodeList.item(index++); } @Override public boolean hasNext() { return (nodeList.getLength() - index) > 0; } }; }
@SuppressWarnings("nls") @Override public void execute(TemporaryFileHandle staging, InstitutionInfo instInfo, ConverterParams params) throws XPathExpressionException { SubTemporaryFile folder = new SubTemporaryFile(staging, "workflow"); List<String> entries = xmlHelper.getXmlFileList(folder); for( String entry : entries ) { PropBagEx workflow = xmlHelper.readToPropBagEx(folder, entry); NodeList zeroDays = (NodeList) allNodes.evaluate(workflow.getRootElement(), XPathConstants.NODESET); for( int i = 0; i < zeroDays.getLength(); i++ ) { PropBagEx bag = new PropBagEx(zeroDays.item(i), true); bag.setNode("priority", Priority.NORMAL.intValue()); if( bag.isNodeTrue("escalate") && bag.getIntNode("escalationdays") == 0 ) { bag.setNode("escalate", "false"); } } xmlHelper.writeFromPropBagEx(folder, entry, workflow); } }
private int getMaxRId(ByteArrayOutputStream xmlStream) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(xmlStream.toByteArray())); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("Relationships/*"); NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { String id = nodeList.item(i).getAttributes().getNamedItem("Id").getTextContent(); int idNum = Integer.parseInt(id.substring("rId".length())); this.maxRId = idNum > this.maxRId ? idNum : this.maxRId; } return this.maxRId; }
@Test public void testSignThenRedactAndThenVerify() throws Exception { RedactableXMLSignature sig = RedactableXMLSignature.getInstance(algorithm); sig.initSign(keyPair); sig.setDocument(new FileInputStream("testdata/vehicles.xml")); sig.addSignSelector("#xpointer(id('a1'))", true); sig.addSignSelector("#xpointer(id('a2'))", true); sig.addSignSelector("#xpointer(id('a3'))", true); Document document = sig.sign(); sig.initRedact(keyPair.getPublic()); sig.setDocument(document); sig.addRedactSelector("#xpointer(id('a3'))"); sig.redact(); validateXSD(document); sig.initVerify(keyPair.getPublic()); sig.setDocument(document); assertTrue(sig.verify()); // ensure that a3 is actually removed XPath xPath = XPathFactory.newInstance().newXPath(); assertNull(xPath.evaluate("//*[@id='a3']", document, XPathConstants.NODE)); assertNull(xPath.evaluate("//*[@URI=\"#xpointer(id('a3'))\"]", document, XPathConstants.NODE)); }
private Element unwrapSoapMessage(Element soapElement, SamlElementType samlElementType) { XPath xpath = XPathFactory.newInstance().newXPath(); NamespaceContextImpl context = new NamespaceContextImpl(); context.startPrefixMapping("soapenv", "http://schemas.xmlsoap.org/soap/envelope/"); context.startPrefixMapping("samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); context.startPrefixMapping("saml", "urn:oasis:names:tc:SAML:2.0:assertion"); context.startPrefixMapping("ds", "http://www.w3.org/2000/09/xmldsig#"); xpath.setNamespaceContext(context); try { String expression = "//samlp:" + samlElementType.getElementName(); Element element = (Element) xpath.evaluate(expression, soapElement, XPathConstants.NODE); if (element == null) { String errorMessage = format("Document{0}{1}{0}does not have element {2} inside it.", NEW_LINE, XmlUtils.writeToString(soapElement), expression); LOG.error(errorMessage); throw new SoapUnwrappingException(errorMessage); } return element; } catch (XPathExpressionException e) { throw propagate(e); } }
private static Iterable<String> getAttrNames(InputStream is, XPathExpression expr) { Set<String> names = Sets.newHashSet(); if (expr != null) { try { Document doc = parseStream(is); if (doc != null) { NodeList nodelist = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodelist.getLength(); i++) { String name = nodelist.item(i).getNodeValue(); names.add(name); } } } catch (XPathExpressionException ex) { LOG.log(Level.WARNING, null, ex); } } return names; }
@Override protected VerzoekParser<AfnemerindicatieVerzoek> geefDienstSpecifiekeParser(final Node node) { try { final String plaatsenExpressie = SLASH + BRP_NAMESPACE_PREFIX + SoortBericht.LVG_SYN_REGISTREER_AFNEMERINDICATIE.getIdentifier() + SLASH + BRP_NAMESPACE_PREFIX + PLAATSING_AFNEMERINDICATIE; final String verwijderenExpressie = SLASH + BRP_NAMESPACE_PREFIX + SoortBericht.LVG_SYN_REGISTREER_AFNEMERINDICATIE.getIdentifier() + SLASH + BRP_NAMESPACE_PREFIX + VERWIJDERING_AFNEMERINDICATIE; final Node plaatsingNode = (Node) xpath.evaluate(plaatsenExpressie, node, XPathConstants.NODE); final Node verwijderingNode = (Node) xpath.evaluate(verwijderenExpressie, node, XPathConstants.NODE); for (Map.Entry<String, VerzoekParser<AfnemerindicatieVerzoek>> entry : DIENST_BERICHT_PARSER_MAP.entrySet()) { if ((plaatsingNode != null && entry.getKey().contains(plaatsingNode.getLocalName())) || (verwijderingNode != null && entry.getKey() .contains(verwijderingNode.getLocalName()))) { return entry.getValue(); } } } catch (final XPathExpressionException e) { throw new UnsupportedOperationException("XPath kon niet worden geëvalueerd.", e); } throw new BrpServiceRuntimeException("Geen geschikte parser voor dit verzoek."); }
public Framework(final String name, final File bsFile) { super(name, null); try { final File pathf = bsFile.getCanonicalFile().getParentFile().getParentFile().getParentFile(); path = pathf.getParentFile().getParentFile().getCanonicalPath(); } catch (IOException x) { throw new RuntimeException(x); } binaries = findBinaries(path, name); pkg = ClassGenerator.JOBJC_PACKAGE + "." + name.toLowerCase(); try { rootNode = (Node)XPATH.evaluate("signatures", new InputSource(bsFile.getAbsolutePath()), XPathConstants.NODE); } catch (final XPathExpressionException e) { throw new RuntimeException(e); } protocols = new ArrayList<Protocol>(); categories = new ArrayList<Category>(); }
/**@param{Object} Address- The physical address of a location * This method returns Geocode coordinates of the Address object.Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, * Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739).Please give all the physical Address values * for a precise coordinate. setting none of the values will give a null value for the Latitude and Longitude. */ public static GeoCode getCoordinates(Address address) throws Exception { GeoCode geo= new GeoCode(); String physicalAddress = (address.getAddress1() == null ? "" : address.getAddress1() + ",") + (address.getAddress2() == null ? "" : address.getAddress2() + ",") + (address.getCityName() == null ? "" : address.getCityName() + ",") + (address.getState() == null ? "" : address.getState() + "-") + (address.getZip() == null ? "" : address.getZip() + ",") + (address.getCountry() == null ? "" : address.getCountry()); String api = GMAPADDRESS + URLEncoder.encode(physicalAddress, "UTF-8") + SENSOR; URL url = new URL(api); HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection(); httpConnection.connect(); int responseCode = httpConnection.getResponseCode(); if(responseCode == 200) { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(httpConnection.getInputStream()); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile(STATUS); String status = (String)expr.evaluate(document, XPathConstants.STRING); if(status.equals("OK")) { expr = xpath.compile(LATITUDE); String latitude = (String)expr.evaluate(document, XPathConstants.STRING); expr = xpath.compile(LONGITUDE); String longitude = (String)expr.evaluate(document, XPathConstants.STRING); geo.setLatitude(latitude); geo.setLongitude(longitude); } } else { throw new Exception("Fail to Convert to Geocode"); } return geo; }
private List<ElementValue> findElementValues(ElementValue pev, String path) { List<ElementValue> result = new ArrayList<>(); XPath xpath = XPathFactory.newInstance().newXPath(); try { NodeList list = (NodeList) xpath.evaluate(path, pev.getElement(), XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { result.add(new ElementValue((Element) list.item(i), Type.OK)); } } catch (XPathExpressionException ex) { } return result; }
public InputStream upsetTheNorm(String xPath, boolean remove) { try { document = dbf.newDocumentBuilder().parse(new File(pathname)); XPath xpath = xpf.newXPath(); XPathExpression expression = xpath.compile(xPath); NodeList searchedNodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET); if (searchedNodes == null) { System.out.println("bad path: " + xPath); } else { for (int i = 0; i < searchedNodes.getLength(); i++) { Node searched = searchedNodes.item(i); Node owningElement = (searched instanceof ElementImpl) ? searched : ((AttrImpl) searched).getOwnerElement(); Node containingParent = owningElement.getParentNode(); if (remove) { containingParent.removeChild(owningElement); } else { containingParent.appendChild(owningElement.cloneNode(true)); } } } Transformer t = tf.newTransformer(); ByteArrayOutputStream os = new ByteArrayOutputStream(); Result result = new StreamResult(os); t.transform(new DOMSource(document), result); return new ByteArrayInputStream(os.toByteArray()); } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException | TransformerException ex) { throw new RuntimeException(ex); } }
private void removeWhitespace(Document document) throws XPathExpressionException { document.normalize(); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); } }
private void doPopulateUnapproved(Map<String, ModuleInfo> moduleRATInfo, Element rootElement, XPath path) throws XPathExpressionException { NodeList evaluate = (NodeList) path.evaluate("descendant::resource[license-approval/@name=\"false\"]", rootElement, XPathConstants.NODESET); for (int i = 0; i < evaluate.getLength(); i++) { String resources = relativize(evaluate.item(i).getAttributes().getNamedItem("name").getTextContent()); String moduleName = getModuleName(resources); if (!moduleRATInfo.containsKey(moduleName)) { moduleRATInfo.get(NOT_CLUSTER).addUnapproved(resources); } else { moduleRATInfo.get(moduleName).addUnapproved(resources); } } }
private void doPopulateApproved(Map<String, ModuleInfo> moduleRATInfo, Element rootElement, XPath path) throws XPathExpressionException { NodeList evaluate = (NodeList) path.evaluate("descendant::resource[license-approval/@name=\"true\"]", rootElement, XPathConstants.NODESET); for (int i = 0; i < evaluate.getLength(); i++) { String resources = relativize(evaluate.item(i).getAttributes().getNamedItem("name").getTextContent()); String moduleName = getModuleName(resources); if (!moduleRATInfo.containsKey(moduleName)) { moduleRATInfo.get(NOT_CLUSTER).addApproved(resources); } else { moduleRATInfo.get(moduleName).addApproved(resources); } } }
private static void loadExcludesFile(final String testExcludesFile, final Set<String> testExcludeSet) throws XPathExpressionException { final XPath xpath = XPathFactory.newInstance().newXPath(); final NodeList testIds = (NodeList) xpath.evaluate("/excludeList/test/@id", new InputSource(testExcludesFile), XPathConstants.NODESET); for (int i = testIds.getLength() - 1; i >= 0; i--) { testExcludeSet.add(testIds.item(i).getNodeValue()); } }
public static List runXPathQuery(File parsedFile, String xpathExpr) throws Exception{ List result = new ArrayList(); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(getNamespaceContext()); InputSource inputSource = new InputSource(new FileInputStream(parsedFile)); NodeList nodes = (NodeList) xpath.evaluate(xpathExpr, inputSource, XPathConstants.NODESET); if((nodes != null) && (nodes.getLength() > 0)){ for(int i=0; i<nodes.getLength();i++){ org.w3c.dom.Node node = nodes.item(i); result.add(node.getNodeValue()); } } return result; }
private Element getAttributeQuery(Document document) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); NamespaceContextImpl context = new NamespaceContextImpl(); context.startPrefixMapping("soapenv", "http://schemas.xmlsoap.org/soap/envelope/"); context.startPrefixMapping("samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); xpath.setNamespaceContext(context); return (Element) xpath.evaluate("//samlp:Response", document, XPathConstants.NODE); }
/** * Test converting nested elements. */ public void testNestedElements2() throws XPathExpressionException { String json = "{\"menu\": {\"id\": \"file\",\"value\": \"File\",\"popup\": {\"menuitem\": [{\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},{\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},{\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}"; String xml = this.converter.convert(json); Document xmlConverted = SOAPHelper.xmlStrToDoc(xml); XPath xPath = XPathFactory.newInstance().newXPath(); assertEquals("file", xPath.compile("/menu/id").evaluate(xmlConverted)); assertEquals("File", xPath.compile("/menu/value").evaluate(xmlConverted)); NodeList nodeList = (NodeList) xPath.compile("/menu/popup/menuitem").evaluate(xmlConverted, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { for (int j = 0; j < nodeList.item(i).getChildNodes().getLength(); j += 2) { String nodeName1 = nodeList.item(i).getChildNodes().item(j).getLocalName(); String nodeValue1 = nodeList.item(i).getChildNodes().item(j).getTextContent(); String nodeName2 = nodeList.item(i).getChildNodes().item(j + 1).getLocalName(); String nodeValue2 = nodeList.item(i).getChildNodes().item(j + 1).getTextContent(); if (!((nodeValue1.equals("New") && nodeValue2.equals("CreateNewDoc()")) || (nodeValue2.equals("New") && nodeValue1.equals("CreateNewDoc()"))) && !((nodeValue1.equals("Open") && nodeValue2.equals("OpenDoc()")) || (nodeValue2.equals("Open") && nodeValue1.equals("OpenDoc()"))) && !((nodeValue1.equals("Close") && nodeValue2.equals("CloseDoc()")) || (nodeValue2.equals("Close") && nodeValue1.equals("CloseDoc()")))) { fail(); } } } }
private Element findElement(ElementValue pev, String path) { XPath xpath = XPathFactory.newInstance().newXPath(); try { return (Element) xpath.evaluate(path, pev.getElement(), XPathConstants.NODE); } catch (XPathExpressionException ex) { return null; } }
@Override public NodeList asNodeList() { try { return (NodeList) this.xPathExpression.evaluate(this.baseNode, XPathConstants.NODESET); } catch (XPathException ex) { throw new FluentXmlProcessingException(ex); } }
@Test public void testXPath10() throws Exception { try { XPath xpath = xpathFactory.newXPath(); Assert.assertNotNull(xpath); xpath.evaluate(".", d, XPathConstants.STRING); Assert.fail("XPathExpressionException not thrown"); } catch (XPathExpressionException e) { // Expected exception as context node is null } }
private boolean isCategoryUnit ( final Element unit ) throws Exception { final Object value = this.isCategoryPathExpression.evaluate ( unit, XPathConstants.STRING ); if ( value == null ) { return false; } return Boolean.parseBoolean ( (String)value ); }
/** * Any @string reference in a <provider> value in AndroidManifest.xml will break on * build, thus preventing the application from installing. This is from a bug/error * in AOSP where public resources cannot be part of an authorities attribute within * a <provider> tag. * * This finds any reference and replaces it with the literal value found in the * res/values/strings.xml file. * * @param file File for AndroidManifest.xml * @throws AndrolibException */ public static void fixingPublicAttrsInProviderAttributes(File file) throws AndrolibException { if (file.exists()) { try { Document doc = loadDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xPath.compile("/manifest/application/provider"); Object result = expression.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); NamedNodeMap attrs = node.getAttributes(); if (attrs != null) { Node provider = attrs.getNamedItem("android:authorities"); if (provider != null) { String reference = provider.getNodeValue(); String replacement = pullValueFromStrings(file.getParentFile(), reference); if (replacement != null) { provider.setNodeValue(replacement); saveDocument(file, doc); } } } } } catch (SAXException | ParserConfigurationException | IOException | XPathExpressionException | TransformerException ignored) { } } }
/** * Finds key in strings.xml file and returns text value * * @param directory Root directory of apk * @param key String reference (ie @string/foo) * @return String|null * @throws AndrolibException */ public static String pullValueFromStrings(File directory, String key) throws AndrolibException { if (! key.contains("@")) { return null; } File file = new File(directory, "/res/values/strings.xml"); key = key.replace("@string/", ""); if (file.exists()) { try { Document doc = loadDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xPath.compile("/resources/string[@name=" + '"' + key + "\"]/text()"); Object result = expression.evaluate(doc, XPathConstants.STRING); if (result != null) { return (String) result; } } catch (SAXException | ParserConfigurationException | IOException | XPathExpressionException ignored) { } } return null; }
protected static void cellParsing(XPath xPath, Table table, Node tableHead, String rowType) throws XPathExpressionException, NumberFormatException, DOMException { if (tableHead != null) { NodeList trHeadNodes = (NodeList) xPath.compile("tr").evaluate(tableHead, XPathConstants.NODESET); for (int y = 0; y < trHeadNodes.getLength(); y++) { Row row = new Row(); row.setType(rowType); table.getRow().add(row); NodeList cellNodes = (NodeList) xPath.compile("th|td").evaluate(trHeadNodes.item(y), XPathConstants.NODESET); for (int w = 0; w < cellNodes.getLength(); w++) { Cell cell = new Cell(); row.getCell().add(cell); Node cellNode = cellNodes.item(w); if (cellNode != null && cellNode.getAttributes() != null) { if (cellNode.getAttributes().getNamedItem("colspan") != null) { cell.setColspan(Integer.parseInt(cellNode.getAttributes().getNamedItem("colspan").getNodeValue())); } else { cell.setColspan(1); } if (cellNode.getAttributes().getNamedItem("rowspan") != null) { cell.setRowspan(Integer.parseInt(cellNode.getAttributes().getNamedItem("rowspan").getNodeValue())); } else { cell.setRowspan(1); } ParContent parContent = new ParContent(); parContent.setType("tableCell"); cell.getParContent().add(parContent); Body.parsingParContent(cellNode, parContent); } } } } }
private NodeList getNodeListForDocAndExpression(String objectString, String expression) throws Exception { DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder(); InputSource source = new InputSource(new StringReader(objectString)); Document doc = builder.parse(source); XPath xpath = xPathFactory.newXPath(); return (NodeList) xpath.compile(expression).evaluate(doc, XPathConstants.NODESET); }
/** * Returns the node in the given document at the specified XPath. * * @param node * The document to be checked. * @param xpathString * The xpath to look at. * @return The node at the given xpath. * @throws XPathExpressionException */ public static Node getNodeByXPath(Node node, String xpathString) throws XPathExpressionException { final XPathFactory factory = XPathFactory.newInstance(); final XPath xpath = factory.newXPath(); xpath.setNamespaceContext(new XmlNamespaceResolver( getOwningDocument(node))); final XPathExpression expr = xpath.compile(xpathString); return (Node) expr.evaluate(node, XPathConstants.NODE); }