/** * Returns properly configured (e.g. security features) factory * - securityProcessing == is set based on security processing property, default is true */ public static XPathFactory createXPathFactory(boolean disableSecureProcessing) throws IllegalStateException { try { XPathFactory factory = XPathFactory.newInstance(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "XPathFactory instance: {0}", factory); } factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !isXMLSecurityDisabled(disableSecureProcessing)); return factory; } catch (XPathFactoryConfigurationException ex) { LOGGER.log(Level.SEVERE, null, ex); throw new IllegalStateException( ex); } catch (AbstractMethodError er) { LOGGER.log(Level.SEVERE, null, er); throw new IllegalStateException(Messages.INVALID_JAXP_IMPLEMENTATION.format(), er); } }
public static boolean isMavenFXProject(@NonNull final Project prj) { if (isMavenProject(prj)) { try { FileObject pomXml = prj.getProjectDirectory().getFileObject("pom.xml"); //NOI18N DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(FileUtil.toFile(pomXml)); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression exprJfxrt = xpath.compile("//bootclasspath[contains(text(),'jfxrt')]"); //NOI18N XPathExpression exprFxPackager = xpath.compile("//executable[contains(text(),'javafxpackager')]"); //NOI18N XPathExpression exprPackager = xpath.compile("//executable[contains(text(),'javapackager')]"); //NOI18N boolean jfxrt = (Boolean) exprJfxrt.evaluate(doc, XPathConstants.BOOLEAN); boolean packager = (Boolean) exprPackager.evaluate(doc, XPathConstants.BOOLEAN); boolean fxPackager = (Boolean) exprFxPackager.evaluate(doc, XPathConstants.BOOLEAN); return jfxrt && (packager || fxPackager); } catch (XPathExpressionException | ParserConfigurationException | SAXException | IOException ex) { LOGGER.log(Level.INFO, "Error while parsing pom.xml.", ex); //NOI18N return false; } } return false; }
public void testAddLibraries() throws Exception { SuiteProject suite = TestBase.generateSuite(getWorkDir(), "suite"); TestBase.generateSuiteComponent(suite, "lib"); TestBase.generateSuiteComponent(suite, "testlib"); NbModuleProject clientprj = TestBase.generateSuiteComponent(suite, "client"); Library lib = LibraryFactory.createLibrary(new LibImpl("lib")); FileObject src = clientprj.getSourceDirectory(); assertTrue(ProjectClassPathModifier.addLibraries(new Library[] {lib}, src, ClassPath.COMPILE)); assertFalse(ProjectClassPathModifier.addLibraries(new Library[] {lib}, src, ClassPath.COMPILE)); Library testlib = LibraryFactory.createLibrary(new LibImpl("testlib")); FileObject testsrc = clientprj.getTestSourceDirectory("unit"); assertTrue(ProjectClassPathModifier.addLibraries(new Library[] {testlib}, testsrc, ClassPath.COMPILE)); assertFalse(ProjectClassPathModifier.addLibraries(new Library[] {testlib}, testsrc, ClassPath.COMPILE)); InputSource input = new InputSource(clientprj.getProjectDirectory().getFileObject("nbproject/project.xml").toURL().toString()); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(nbmNamespaceContext()); assertEquals("org.example.client", xpath.evaluate("//nbm:data/nbm:code-name-base", input)); // control assertEquals("org.example.lib", xpath.evaluate("//nbm:module-dependencies/*/nbm:code-name-base", input)); assertEquals("org.example.testlib", xpath.evaluate("//nbm:test-dependencies/*/*/nbm:code-name-base", input)); }
public void testAddRoots() throws Exception { NbModuleProject prj = TestBase.generateStandaloneModule(getWorkDir(), "module"); FileObject src = prj.getSourceDirectory(); FileObject jar = TestFileUtils.writeZipFile(FileUtil.toFileObject(getWorkDir()), "a.jar", "entry:contents"); URL root = FileUtil.getArchiveRoot(jar.toURL()); assertTrue(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE)); assertFalse(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE)); FileObject releaseModulesExt = prj.getProjectDirectory().getFileObject("release/modules/ext"); assertNotNull(releaseModulesExt); assertNotNull(releaseModulesExt.getFileObject("a.jar")); jar = TestFileUtils.writeZipFile(releaseModulesExt, "b.jar", "entry2:contents"); root = FileUtil.getArchiveRoot(jar.toURL()); assertTrue(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE)); assertFalse(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE)); assertEquals(2, releaseModulesExt.getChildren().length); String projectXml = prj.getProjectDirectory().getFileObject("nbproject/project.xml").toURL().toString(); InputSource input = new InputSource(projectXml); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(nbmNamespaceContext()); assertEquals(projectXml, "ext/a.jar", xpath.evaluate("//nbm:class-path-extension[1]/nbm:runtime-relative-path", input)); assertEquals(projectXml, "release/modules/ext/a.jar", xpath.evaluate("//nbm:class-path-extension[1]/nbm:binary-origin", input)); assertEquals(projectXml, "ext/b.jar", xpath.evaluate("//nbm:class-path-extension[2]/nbm:runtime-relative-path", input)); assertEquals(projectXml, "release/modules/ext/b.jar", xpath.evaluate("//nbm:class-path-extension[2]/nbm:binary-origin", input)); }
/** Extract specific POM-related values from a XML-String into a map. */ Map<String, String> mapPom(String pom) { try { var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); var document = builder.parse(new InputSource(new StringReader(pom))); var xpath = XPathFactory.newInstance().newXPath(); var name = xpath.evaluate("/project/name", document); var url = xpath.evaluate("/project/url", document); var group = xpath.evaluate("/project/groupId", document); var artifact = xpath.evaluate("/project/artifactId", document); var version = xpath.evaluate("/project/version", document); if (group.isEmpty()) { group = xpath.evaluate("/project/parent/groupId", document); } if (version.isEmpty()) { version = xpath.evaluate("/project/parent/version", document); } return Map.of( "name", name, "url", url, "group", group, "artifact", artifact, "version", version); } catch (Exception e) { debug("scan({0}) failed: {0}", pom, e); } return Map.of(); }
@Test public void testXPath_DOM_withSM() { System.out.println("Evaluate DOM Source; Security Manager is set:"); setSystemProperty(DOM_FACTORY_ID, "MyDOMFactoryImpl"); try { XPathFactory xPathFactory = XPathFactory.newInstance("http://java.sun.com/jaxp/xpath/dom", "com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl", null); xPathFactory.setFeature(ORACLE_FEATURE_SERVICE_MECHANISM, true); if ((boolean) xPathFactory.getFeature(ORACLE_FEATURE_SERVICE_MECHANISM)) { Assert.fail("should not override in secure mode"); } } catch (Exception e) { Assert.fail(e.getMessage()); } finally { clearSystemProperty(DOM_FACTORY_ID); } }
@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 } }
/** * Find the element reference for the selected element. The selected element * is an XPATH expression relation to the element reference given as a * parameter. * * @param pev the element reference from which the XPATH expression is * evaluated. * @param path the XPATH expression * @return the resulting element reference */ public final ElementValue findElementValue(ElementValue pev, String path) { XPath xpath = XPathFactory.newInstance().newXPath(); try { Element el = (Element) xpath.evaluate(path, pev.getElement(), XPathConstants.NODE); return pev.isInHerited() ? (el == null ? new ElementValue(Type.INHERITED_MISSING) : new ElementValue(el, Type.INHERITED)) : (el == null ? new ElementValue(pev, path) : new ElementValue(el, Type.OK)); } catch (XPathExpressionException ex) { return new ElementValue(pev, path); } }
/** * Default constructor */ public XPathMetadataExtracter() { super(new HashSet<String>(Arrays.asList(SUPPORTED_MIMETYPES))); try { DocumentBuilderFactory normalFactory = DocumentBuilderFactory.newInstance(); documentBuilder = normalFactory.newDocumentBuilder(); DocumentBuilderFactory dtdIgnoringFactory = DocumentBuilderFactory.newInstance(); dtdIgnoringFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); dtdIgnoringFactory.setFeature("http://xml.org/sax/features/validation", false); dtdIgnoringDocumentBuilder = dtdIgnoringFactory.newDocumentBuilder(); xpathFactory = XPathFactory.newInstance(); } catch (Throwable e) { throw new AlfrescoRuntimeException("Failed to initialize XML metadata extractor", e); } }
public boolean eval() throws BuildException { if (nullOrEmpty(fileName)) { throw new BuildException("No file set"); } File file = new File(fileName); if (!file.exists() || file.isDirectory()) { throw new BuildException( "The specified file does not exist or is a directory"); } if (nullOrEmpty(path)) { throw new BuildException("No XPath expression set"); } XPath xpath = XPathFactory.newInstance().newXPath(); InputSource inputSource = new InputSource(fileName); Boolean result = Boolean.FALSE; try { result = (Boolean) xpath.evaluate(path, inputSource, XPathConstants.BOOLEAN); } catch (XPathExpressionException e) { throw new BuildException("XPath expression fails", e); } return result.booleanValue(); }
private void setJKSLocation(String domainPath) { URL fileUrl = Thread.currentThread().getContextClassLoader() .getResource(STSConfigTemplateFileName); File file = new File(fileUrl.getFile()); if (!file.exists()) { System.out.println("MockSTSServiceTemplate.xml not exists"); return; } try { Document doc = parse(file); XPathFactory xpfactory = XPathFactory.newInstance(); XPath path = xpfactory.newXPath(); updateElementValue(path, doc, "/definitions/Policy/ExactlyOne/All/KeyStore", "location", domainPath + "/config/keystore.jks"); updateElementValue(path, doc, "/definitions/Policy/ExactlyOne/All/TrustStore", "location", domainPath + "/config/cacerts.jks"); doc2Xml(doc); } catch (Exception e) { e.printStackTrace(); } }
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); } }
/** * 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); } } }
/** * Searches XML element with XPath and returns list of nodes found * * @param xml input stream with the XML in which the element is being searched * @param expression XPath expression used in search * @return {@link NodeList} of elements matching the XPath in the XML * @throws XPathExpressionException if there is an error in the XPath expression * @throws IOException if the XML at the specified path is missing * @throws SAXException if the XML cannot be parsed * @throws ParserConfigurationException */ public static NodeList findWithXPath(InputStream xml, String expression) throws IOException, SAXException, ParserConfigurationException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xml); doc.getDocumentElement().normalize(); XPath xPath = XPathFactory.newInstance().newXPath(); try { return (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new InvalidXPathException(expression, e); } }
/** * Evaluates provided XPath expression into the {@link String} * * @param evalExpression Expression to evaluate * @param xmlSource XML source * @return Evaluation result */ public static String evaluateXPathToString(String evalExpression, String xmlSource) { try { return XPathFactory. newInstance(). newXPath(). evaluate( evalExpression, DocumentBuilderFactory. newInstance(). newDocumentBuilder(). parse(new InputSource( new StringReader( xmlSource)))); } catch (Exception e) { LOG.warning(COMMON_EVAL_ERROR_MESSAGE); } return EMPTY; }
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; } }; }
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; }
/** * @param xmlString * @return * @throws Exception */ public static String findFunction(String xmlString) throws Exception { DocumentBuilder document = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Element node = document.parse(new ByteArrayInputStream(xmlString.getBytes())).getDocumentElement(); //Xpath XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("//*[local-name()='Envelope']/*[local-name()='Body']/*"); Object result = expr.evaluate(node, XPathConstants.NODESET); NodeList nodes = (NodeList) result; if (log.isDebugEnabled()) { log.debug("nodes.item(0).getNodeName():" + nodes.item(0).getNodeName()); } if (nodes.item(0).getNodeName().contains("query")) { return "query"; } else if (nodes.item(0).getNodeName().contains("update")) { return "update"; } else { return null; } }
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); }
@DataProvider(name = "document") public Object[][] getDocument() throws Exception { DocumentBuilderFactory dBF = DocumentBuilderFactory.newInstance(); dBF.setValidating(false); dBF.setNamespaceAware(true); Document doc = dBF.newDocumentBuilder().parse( new ByteArrayInputStream(rawXML.getBytes("UTF-8"))); return new Object[][]{{XPathFactory.newInstance().newXPath(), doc}}; }
public static XPathFactory newXPathFactory(boolean disableSecurity) { XPathFactory factory = XPathFactory.newInstance(); try { factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !xmlSecurityDisabled(disableSecurity)); } catch (XPathFactoryConfigurationException e) { LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[] { factory.getClass().getName() } ); } return factory; }
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 XPath createXPath() throws XPathFactoryConfigurationException { XPathFactory xpathFactory = XPathFactory.newInstance(); Assert.assertNotNull(xpathFactory); XPath xpath = xpathFactory.newXPath(); Assert.assertNotNull(xpath); return xpath; }
boolean enableExtensionFunction(XPathFactory factory) { boolean isSupported = true; try { factory.setFeature(ENABLE_EXTENSION_FUNCTIONS, true); } catch (XPathFactoryConfigurationException ex) { isSupported = false; } return isSupported; }
/**Query the API and returns the list of expansions. Update the cache. * @param abbrev lowercase abbreviation. * @throws Exception */ private synchronized String[] queryApi(String abbrev, int retryLeft) throws Exception { if (retryLeft < MAX_RETRY) Thread.sleep(1000); URL url = new URL(String.format("%s?uid=%s&tokenid=%s&term=%s", API_URL, uid, tokenId, URLEncoder.encode(abbrev, "utf8"))); boolean cached = abbrToExpansion.containsKey(abbrev); LOG.info("{} {}", cached ? "<cached>" : "Querying", url); if (cached) return abbrToExpansion.get(abbrev); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setConnectTimeout(0); connection.setRequestProperty("Accept", "*/*"); connection .setRequestProperty("Content-Type", "multipart/form-data"); connection.setUseCaches(false); if (connection.getResponseCode() != 200) { Scanner s = new Scanner(connection.getErrorStream()) .useDelimiter("\\A"); LOG.error("Got HTTP error {}. Message is: {}", connection.getResponseCode(), s.next()); s.close(); throw new RuntimeException("Got response code:" + connection.getResponseCode()); } DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc; try { doc = builder.parse(connection.getInputStream()); } catch (IOException e) { LOG.error("Got error while querying: {}", url); throw e; } XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression resourceExpr = xpath.compile("//definition/text()"); NodeList resources = (NodeList) resourceExpr.evaluate(doc, XPathConstants.NODESET); Vector<String> resVect = new Vector<>(); for (int i=0; i<resources.getLength(); i++){ String expansion = resources.item(i).getTextContent().replace(String.valueOf((char) 160), " ").trim(); if (!resVect.contains(expansion)) resVect.add(expansion); } String[] res = resVect.toArray(new String[]{}); abbrToExpansion.put(abbrev, res); increaseFlushCounter(); return res; }
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; } }
public EasyTravelScenarioService(RestTemplate restTemplate, EasyTravelConfigurationProperties conf) { this.restTemplate = restTemplate; this.xPathFactory = XPathFactory.newInstance(); this.documentBuilderFactory = DocumentBuilderFactory.newInstance(); this.apiUrl = conf.getApiUrl(); this.availableScenarioConfigsMap = conf.getAvailableScenarios().stream().collect(Collectors.toMap(ScenarioConfigProperty::getId, sc -> sc)); this.availableScenarioNames = conf.getAvailableScenarioNames(); }
public XPath getXPath(NamespaceContext namespaceContext) { XPathFactory xPathFactory = buildXPathFactory(); configure(xPathFactory); XPath xPath = buildXPath(xPathFactory); configure(xPath, namespaceContext); return xPath; }
public XPathContentWorkerSelector() { try { documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); xpathFactory = XPathFactory.newInstance(); } catch (Throwable e) { throw new AlfrescoRuntimeException("Failed to initialize XPathContentWorkerSelector", e); } supportedMimetypes = new HashSet<String>(); supportedMimetypes.add(MimetypeMap.MIMETYPE_XML); }
public MetaDataMerger ( final String label, final boolean compressed ) throws Exception { this.doc = createDocument (); final XPathFactory xpf = XPathFactory.newInstance (); final XPath xp = xpf.newXPath (); this.isCategoryPathExpression = xp.compile ( "properties/property[@name='org.eclipse.equinox.p2.type.category']/@value" ); final ProcessingInstruction pi = this.doc.createProcessingInstruction ( "metadataRepository", "" ); pi.setData ( "version=\"1.1.0\"" ); this.doc.appendChild ( pi ); this.r = this.doc.createElement ( "repository" ); this.doc.appendChild ( this.r ); this.r.setAttribute ( "name", label ); this.r.setAttribute ( "type", "org.eclipse.equinox.internal.p2.metadata.repository.LocalMetadataRepository" ); this.r.setAttribute ( "version", "1" ); this.p = this.doc.createElement ( "properties" ); this.r.appendChild ( this.p ); addProperty ( this.p, "p2.compressed", "" + compressed ); addProperty ( this.p, "p2.timestamp", "" + System.currentTimeMillis () ); this.u = this.doc.createElement ( "units" ); this.r.appendChild ( this.u ); }
/** * 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; }
private Element getParentVersionElement(Document doc) throws MojoExecutionException { XPath xPath = XPathFactory.newInstance().newXPath(); try { NodeList nodes = ((NodeList) xPath.evaluate("/project/parent/version", doc.getDocumentElement(), XPathConstants.NODESET)); if (nodes.getLength() == 0) { return null; } return (Element) nodes.item(0); } catch (XPathExpressionException e) { throw new MojoExecutionException("Failed to evaluate xpath expression", e); } }
private static void writerToFile(String inputFile, String outputLatexStandard, String outputBib) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException, DOMException, NumberFormatException { // writing LaTeX in World Standard Path latexStandard = Paths.get(outputLatexStandard); BufferedWriter wrlatex = Files.newBufferedWriter(latexStandard, StandardCharsets.UTF_8); // writing bibtex Path bibtexStandard = Paths.get(outputBib); BufferedWriter bib = Files.newBufferedWriter(bibtexStandard, StandardCharsets.UTF_8); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(inputFile); XPath xPath = XPathFactory.newInstance().newXPath(); /* parsing JATS XML */ LaTeX latex = jatsParser(document, xPath); /* creating reference to a bib with regex */ String referenceLink = outputBib.trim().replaceAll(".bib$", ""); if (referenceLink.contains("\\") || referenceLink.contains("/")) { Pattern p = Pattern.compile("(\\w+)$"); Matcher m = p.matcher(referenceLink); if (m.find()) { referenceLink = m.group(); } } /* writing to LaTeX (standard, bib) */ latexStandardWriter(wrlatex, latex, referenceLink); bibWriter(bib, latex); }
/** * 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); }
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; }
/** * Count nodes which are given via xpath expression */ public static Double countNodes(Node node, String nodePath) throws XPathExpressionException { final XPathFactory factory = XPathFactory.newInstance(); final XPath xpath = factory.newXPath(); final XPathExpression expr = xpath.compile("count(" + nodePath + ')'); return (Double) expr.evaluate(node, XPathConstants.NUMBER); }
@Test public void execute() throws Exception { // when task.execute(); // then DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File(TEST_FILE)); XPathFactory xpfactory = XPathFactory.newInstance(); XPath path = xpfactory.newXPath(); Element node = (Element) path.evaluate("/definitions/documentation", doc, XPathConstants.NODE); assertEquals("v1.7", node.getTextContent()); }