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.easyrec.service.core.impl.ProfileServiceImpl.java
/** * Used// w w w .ja v a 2s . c o m * @param tenantId * @param itemId * @param itemType * @param deleteXPath * @throws Exception * */ @Override public boolean deleteProfileField(Integer tenantId, String itemId, String itemType, String deleteXPath) throws Exception { XPathFactory xpf = XPathFactory.newInstance(); // load and parse the profile DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader(getProfile(tenantId, itemId, itemType)))); // check if the element exists XPath xp = xpf.newXPath(); NodeList nodeList = (NodeList) xp.evaluate(deleteXPath, doc, XPathConstants.NODESET); if (nodeList.getLength() == 0) throw new FieldNotFoundException("Field does not exist in this profile!"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); } StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); trans.transform(new DOMSource(doc), result); writer.close(); String xml = writer.toString(); logger.debug(xml); storeProfile(tenantId, itemId, itemType, xml); return true; }
From source file:org.easyrec.service.domain.profile.impl.ProfileServiceImpl.java
public void insertOrUpdateMultiDimension(Integer tenantId, Integer itemId, String itemTypeId, String dimensionXPath, List<String> values) { XPathFactory xpf = XPathFactory.newInstance(); try {//from ww w. j a v a2 s .c o m // load and parse the profile DocumentBuilder db = validationParsers.get(tenantId).get(itemTypeId); Document doc = db.parse(new InputSource(new StringReader(getProfile(tenantId, itemId, itemTypeId)))); // check if the element exists Node node = null; Node parent = null; XPath xp = xpf.newXPath(); for (Iterator<String> it = values.iterator(); it.hasNext();) { String value = it.next(); // look if value already exists node = (Node) xp.evaluate(dimensionXPath + "[text()='" + value + "']", doc, XPathConstants.NODE); // if value exists, value can be discarded if (node != null) { // optimization: if a node was found, store the parent; later no new XPath evaluation is necessary parent = node.getParentNode(); it.remove(); } } if (values.isEmpty()) return; // nothing left to do String parentPath = dimensionXPath.substring(0, dimensionXPath.lastIndexOf("/")); // find path to parent if (parent == null) { String tmpPath = parentPath; while (parent == null) { tmpPath = parentPath.substring(0, tmpPath.lastIndexOf("/")); parent = (Node) xp.evaluate(tmpPath, doc, XPathConstants.NODE); } parent = insertElement(doc, parent, parentPath.substring(tmpPath.length()), null); } String tag = dimensionXPath.substring(parentPath.length() + 1); for (String value : values) { Element el = doc.createElement(tag); el.setTextContent(value); parent.appendChild(el); } StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); trans.transform(new DOMSource(doc), result); writer.close(); String xml = writer.toString(); logger.debug(xml); storeProfile(tenantId, itemId, itemTypeId, xml, true); } catch (Exception e) { logger.error("Error inserting Multi Dimension: " + e.getMessage()); e.printStackTrace(); } }
From source file:org.easyrec.service.domain.profile.impl.ProfileServiceImpl.java
public void insertOrUpdateSimpleDimension(Integer tenantId, Integer itemId, String itemTypeId, String dimensionXPath, String value) { XPathFactory xpf = XPathFactory.newInstance(); try {/* w ww . j a va 2 s . c o m*/ // load and parse the profile DocumentBuilder db = validationParsers.get(tenantId).get(itemTypeId); Document doc = db.parse(new InputSource(new StringReader(getProfile(tenantId, itemId, itemTypeId)))); // check if the element exists XPath xp = xpf.newXPath(); Node node = (Node) xp.evaluate(dimensionXPath, doc, XPathConstants.NODE); // if the element exists, just update the value if (node != null) { // if value doesn't change, there is no need to alter the profile and write it to database if (value.equals(node.getTextContent())) return; node.setTextContent(value); } else { // if the element cannot be found, insert it at the position given in the dimensionXPath // follow the XPath from bottom to top until you find the first existing path element String tmpPath = dimensionXPath; while (node == null) { tmpPath = dimensionXPath.substring(0, tmpPath.lastIndexOf("/")); node = (Node) xp.evaluate(tmpPath, doc, XPathConstants.NODE); } // found the correct node to insert or ended at Document root, hence insert insertElement(doc, node, dimensionXPath.substring(tmpPath.length()/*, dimensionXPath.length()*/), value); } StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); trans.transform(new DOMSource(doc), result); writer.close(); String xml = writer.toString(); logger.debug(xml); storeProfile(tenantId, itemId, itemTypeId, xml, true); } catch (Exception e) { logger.error("Error inserting Simple Dimension: " + e.getMessage()); e.printStackTrace(); } }
From source file:org.eclipse.mdht.dita.ui.util.DitaUtil.java
private static String getFileNameFromMap(String ditaMapPath) { StringBuffer fileName = new StringBuffer(); try {// ww w . ja v a 2 s . c om FileInputStream ditaMapStream; ditaMapStream = new FileInputStream(ditaMapPath); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(false); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/validation", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder builder; Document doc = null; XPathExpression expr = null; builder = factory.newDocumentBuilder(); doc = builder.parse(new InputSource(ditaMapStream)); XPathFactory xFactory = XPathFactory.newInstance(); XPath xpath = xFactory.newXPath(); expr = xpath.compile("//bookmap/bookmeta/prodinfo/prodname"); Node prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE); if (prodNameNode != null) { fileName.append(prodNameNode.getTextContent()); expr = xpath.compile("//bookmap/bookmeta/prodinfo/vrmlist"); Element vrmlistNode = (Element) expr.evaluate(doc, XPathConstants.NODE); if (vrmlistNode != null) { NodeList versions = vrmlistNode.getElementsByTagName("vrm"); if (versions.getLength() > 0) { NamedNodeMap versionAttributes = versions.item(0).getAttributes(); Attr releaseAttr = (Attr) versionAttributes.getNamedItem("release"); if (releaseAttr != null) { fileName.append(String.format("_%s", releaseAttr.getValue())); } Attr versionAttr = (Attr) versionAttributes.getNamedItem("version"); if (versionAttr != null) { fileName.append(String.format("_%s", versionAttr.getValue())); } } } } else { expr = xpath.compile("/bookmap"); prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE); if (prodNameNode != null) { Node node = prodNameNode.getAttributes().getNamedItem("id"); if (node != null) { fileName.append(node.getTextContent()); } } else { expr = xpath.compile("/map"); prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE); if (prodNameNode != null) { Node node = prodNameNode.getAttributes().getNamedItem("title"); if (node != null) { fileName.append(node.getTextContent()); } } } } } catch (Exception e) { e.printStackTrace(); System.out.println(); } return fileName.toString(); }
From source file:org.eclipse.swordfish.p2.internal.deploy.server.MetadataProcessor.java
/** * Create an XPath query from a string /*from w ww . j a v a 2 s.co m*/ * @param expression - the XPath string to be compiled * @return a compiled XPath expression * @throws XPathExpressionException */ private final XPathExpression createQuery(String expression) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(expression); return expr; }
From source file:org.finra.jtaf.ewd.impl.DefaultExtWebDriver.java
@Override public String evaluateXpath(String xpath) throws Exception { XPathFactory xpathFac = XPathFactory.newInstance(); XPath theXpath = xpathFac.newXPath(); String html = getHtmlSource(); html = html.replaceAll(">\\s+<", "><"); InputStream input = new ByteArrayInputStream(html.getBytes()); XMLReader reader = new Parser(); reader.setFeature(Parser.namespacesFeature, false); Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMResult result = new DOMResult(); transformer.transform(new SAXSource(reader, new InputSource(input)), result); Node htmlNode = result.getNode(); // This code gets a Node from the // result./* www .j a va 2 s. c om*/ return (String) theXpath.evaluate(xpath, htmlNode, XPathConstants.STRING); }
From source file:org.finra.jtaf.ewd.widget.element.Element.java
/** * Get the list of nodes which satisfy the xpath expression passed in * //from w ww. j a v a 2 s . c o m * @param xpath * the input xpath expression * @return the nodeset of matching elements * @throws Exception */ private NodeList getNodeListUsingJavaXPath(String xpath) throws Exception { XPathFactory xpathFac = XPathFactory.newInstance(); XPath theXpath = xpathFac.newXPath(); String html = getGUIDriver().getHtmlSource(); html = html.replaceAll(">\\s+<", "><"); InputStream input = new ByteArrayInputStream(html.getBytes()); XMLReader reader = new Parser(); reader.setFeature(Parser.namespacesFeature, false); Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMResult result = new DOMResult(); transformer.transform(new SAXSource(reader, new InputSource(input)), result); Node htmlNode = result.getNode(); // This code gets a Node from the // result. NodeList nodes = (NodeList) theXpath.evaluate(xpath, htmlNode, XPathConstants.NODESET); return nodes; }
From source file:org.forgerock.maven.plugins.LinkTester.java
@Override() public void execute() throws MojoExecutionException, MojoFailureException { if (outputFile != null) { if (!outputFile.isAbsolute()) { outputFile = new File(project.getBasedir(), outputFile.getPath()); }/*w w w .ja v a2s . c o m*/ if (outputFile.exists()) { debug("Deleting existing outputFile: " + outputFile); outputFile.delete(); } try { outputFile.createNewFile(); fileWriter = new FileWriter(outputFile); } catch (IOException ioe) { error("Error while creating output file", ioe); } } initializeSkipUrlPatterns(); //Initialize XML parsers and XPath expressions DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setExpandEntityReferences(false); dbf.setXIncludeAware(xIncludeAware); if (validating) { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Schema schema = sf.newSchema(new URL(DOCBOOK_XSD)); dbf.setSchema(schema); } catch (MalformedURLException murle) { error("Invalid URL provided as schema source", murle); } catch (SAXException saxe) { error("Parsing error occurred while constructing schema for validation", saxe); } } DocumentBuilder db; try { db = dbf.newDocumentBuilder(); db.setErrorHandler(new LoggingErrorHandler(this)); } catch (ParserConfigurationException pce) { throw new MojoExecutionException("Unable to create new DocumentBuilder", pce); } XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); xpath.setNamespaceContext(new XmlNamespaceContext()); XPathExpression expr; try { expr = xpath.compile("//@xml:id"); } catch (XPathExpressionException xpee) { throw new MojoExecutionException("Unable to compile Xpath expression", xpee); } if (docSources != null) { for (DocSource docSource : docSources) { processDocSource(docSource, db, expr); } } try { if (!skipOlinks) { //we can only check olinks after going through all the documents, otherwise we would see false //positives, because of the not yet processed files for (Map.Entry<String, Collection<String>> entry : (Set<Map.Entry<String, Collection<String>>>) olinks .entrySet()) { for (String val : entry.getValue()) { checkOlink(entry.getKey(), val); } } } if (!failedUrls.isEmpty()) { error("The following files had invalid URLs:\n" + failedUrls.toString()); } if (!timedOutUrls.isEmpty()) { warn("The following files had unavailable URLs (connection or read timed out):\n" + timedOutUrls.toString()); } if (failedUrls.isEmpty() && timedOutUrls.isEmpty() && !failure) { //there are no failed URLs and the parser didn't encounter any errors either info("DocBook links successfully tested, no errors reported."); } } finally { flushReport(); } if (failOnError) { if (failure || !failedUrls.isEmpty()) { throw new MojoFailureException("One or more error occurred during plugin execution"); } } }
From source file:org.glite.lb.NotifParser.java
/** * a method for handling xpath queries/* w w w .ja va 2 s .com*/ * * @param xpathString xpath expression * @return the result nodelist */ private NodeList evaluateXPath(String xpathString) { try { XPathFactory xfactory = XPathFactory.newInstance(); XPath xpath = xfactory.newXPath(); XPathExpression expr = xpath.compile(xpathString); return (NodeList) expr.evaluate(doc, XPathConstants.NODESET); } catch (XPathExpressionException ex) { ex.printStackTrace(); return null; } }
From source file:org.gluu.oxtrust.ldap.service.Shibboleth2ConfService.java
public String getIdpMetadataFilePath() { if (applicationConfiguration.getShibboleth2IdpRootDir() == null) { throw new InvalidConfigurationException( "Failed to find IDP metadata file due to undefined IDP root folder"); }//from w ww. ja v a 2 s .c o m String idpConfFolder = applicationConfiguration.getShibboleth2IdpRootDir() + File.separator + SHIB2_IDP_CONF_FOLDER + File.separator; File relyingPartyFile = new File(idpConfFolder + SHIB2_IDP_RELYING_PARTY); if (!relyingPartyFile.exists()) { log.error("Failed to find IDP metadata file name because relaying party file '{0}' doesn't exist", relyingPartyFile.getAbsolutePath()); return null; } InputStream is = null; InputStreamReader isr = null; Document xmlDocument = null; try { is = FileUtils.openInputStream(relyingPartyFile); isr = new InputStreamReader(is, "UTF-8"); try { xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(isr)); } catch (Exception ex) { log.error("Failed to parse relying party file '{0}'", ex, relyingPartyFile.getAbsolutePath()); } } catch (IOException ex) { log.error("Failed to read relying party file '{0}'", ex, relyingPartyFile.getAbsolutePath()); } finally { IOUtils.closeQuietly(isr); IOUtils.closeQuietly(is); } if (xmlDocument == null) { return null; } XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); String filePath = null; try { filePath = xPath.compile( "/RelyingPartyGroup/MetadataProvider[@id='ShibbolethMetadata']/MetadataProvider[@id='IdPMD']/MetadataResource/@file") .evaluate(xmlDocument); } catch (XPathExpressionException ex) { log.error("Failed to find IDP metadata file in relaying party file '{0}'", ex, relyingPartyFile.getAbsolutePath()); } if (filePath == null) { log.error("Failed to find IDP metadata file in relaying party file '{0}'", relyingPartyFile.getAbsolutePath()); } return filePath; }