List of usage examples for javax.xml.xpath XPathFactory newInstance
public static XPathFactory newInstance()
Get a new XPathFactory instance using the default object model, #DEFAULT_OBJECT_MODEL_URI , the W3C DOM.
This method is functionally equivalent to:
newInstance(DEFAULT_OBJECT_MODEL_URI)
Since the implementation for the W3C DOM is always available, this method will never fail.
From source file:com.vitembp.services.imaging.OverlayDefinition.java
/** * Initializes a new instance of the OverlayDefinition class. * @param toBuildFrom /*from www.j av a 2 s.co m*/ */ private OverlayDefinition(String toBuildFrom) throws IOException { // load the definition from XML using xpath methods // first parse the document Document def; try { def = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new ByteArrayInputStream(toBuildFrom.getBytes(Charsets.UTF_8))); } catch (ParserConfigurationException | SAXException | IOException ex) { throw new IOException("Could not parse XML input.", ex); } // prevents issues caused by parser returning multiple text elements for // a single text area def.getDocumentElement().normalize(); // get the overlay type XPath xPath = XPathFactory.newInstance().newXPath(); try { Node type = (Node) xPath.evaluate("/overlay/type", def, XPathConstants.NODE); this.overlayType = OverlayType.valueOf(type.getTextContent()); } catch (XPathExpressionException | IllegalArgumentException ex) { throw new IOException("Exception parsing type.", ex); } // get element definitions try { NodeList elements = (NodeList) xPath.evaluate("/overlay/elements/element", def, XPathConstants.NODESET); this.elementDefinitions = new ArrayList<>(); for (int i = 0; i < elements.getLength(); i++) { this.elementDefinitions.add(new ElementDefinition(elements.item(i))); } } catch (XPathExpressionException | IllegalArgumentException ex) { throw new IOException("Exception parsing elements.", ex); } }
From source file:com.nortal.jroad.util.SOAPUtil.java
/** * Evaluates an {@link XPath} expression and returns a <i>single</i> matching node. * * @param context The context in which to run the expression. * @param expression A valid {@link XPath} expression. * @return {@link Node}, if one is found, <code>null</code> otherwise. * @throws XPathException If the provided expression is invalid or multiple nodes match. *///from w w w. j av a2s. c o m public static Node getNodeByXPath(Object context, String expression) throws XPathException { return (Node) XPathFactory.newInstance().newXPath().evaluate(expression, context, XPathConstants.NODE); }
From source file:org.syncope.console.commons.XMLRolesReader.java
/** * Get all roles allowed for specific page and actio requested. * * @param pageId/*from w w w. jav a 2 s . c o m*/ * @param actionId * @return roles list comma separated */ public String getAllAllowedRoles(final String pageId, final String actionId) { if (doc == null) { init(); } if (doc == null) { return ""; } final StringBuilder roles = new StringBuilder(); try { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile( "//page[@id='" + pageId + "']/" + "action[@id='" + actionId + "']/" + "entitlement/text()"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { if (i > 0) { roles.append(","); } roles.append(nodes.item(i).getNodeValue()); } } catch (XPathExpressionException e) { LOG.error("While parsing authorizations file", e); } LOG.debug("Authorizations found: {}", roles); return roles.toString(); }
From source file:net.adamcin.commons.testing.sling.SlingPostResponse.java
public static SlingPostResponse createFromInputStream(InputStream stream, String encoding) throws IOException { InputSource source = new InputSource(new BufferedInputStream(stream)); source.setEncoding(encoding == null ? "UTF-8" : encoding); SlingPostResponse postResponse = new SlingPostResponse(); XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); try {//from w w w.j a va 2s. co m DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(source); postResponse .setStatus((String) xpath.compile(XPATH_ID_STATUS).evaluate(document, XPathConstants.STRING)); postResponse .setMessage((String) xpath.compile(XPATH_ID_MESSAGE).evaluate(document, XPathConstants.STRING)); postResponse.setLocation( (String) xpath.compile(XPATH_ID_LOCATION).evaluate(document, XPathConstants.STRING)); postResponse.setParentLocation( (String) xpath.compile(XPATH_ID_PARENT_LOCATION).evaluate(document, XPathConstants.STRING)); postResponse.setPath((String) xpath.compile(XPATH_ID_PATH).evaluate(document, XPathConstants.STRING)); postResponse .setReferer((String) xpath.compile(XPATH_ID_REFERER).evaluate(document, XPathConstants.STRING)); List<Change> changes = new ArrayList<Change>(); NodeList changeLogNodes = (NodeList) xpath.compile(XPATH_ID_CHANGE_LOG).evaluate(document, XPathConstants.NODESET); if (changeLogNodes != null) { for (int i = 0; i < changeLogNodes.getLength(); i++) { String rawChange = changeLogNodes.item(i).getTextContent(); rawChange = rawChange.substring(0, rawChange.length() - 2); String[] rawChangeParts = rawChange.split("\\(", 2); if (rawChangeParts.length != 2) { continue; } String changeType = rawChangeParts[0]; String[] rawArguments = rawChangeParts[1].split(", "); List<String> arguments = new ArrayList<String>(); for (String rawArgument : rawArguments) { arguments.add(rawArgument.substring(1, rawArgument.length() - 1)); } Change change = new Change(changeType, arguments.toArray(new String[arguments.size()])); changes.add(change); } } postResponse.setChangeLog(changes); } catch (XPathExpressionException e) { LOGGER.error("Failed to evaluate xpath statement.", e); throw new IOException("Failed to evaluate xpath statement.", e); } catch (ParserConfigurationException e) { LOGGER.error("Failed to create DocumentBuilder.", e); throw new IOException("Failed to create DocumentBuilder.", e); } catch (SAXException e) { LOGGER.error("Failed to create Document.", e); throw new IOException("Failed to create Document.", e); } LOGGER.info("Returning post response"); return postResponse; }
From source file:com.esri.geoportal.commons.csw.client.impl.ProfilesLoader.java
/** * Loads profiles./*from w ww . j a v a2 s .c o m*/ * @return profiles * @throws IOException if loading profiles from configuration fails * @throws ParserConfigurationException if unable to obtain XML parser * @throws SAXException if unable to parse XML document * @throws XPathExpressionException if invalid XPath expression */ public Profiles load() throws IOException, ParserConfigurationException, SAXException, XPathExpressionException { LOG.info(String.format("Loading CSW profiles")); Profiles profiles = new Profiles(); try (InputStream profilesXml = Thread.currentThread().getContextClassLoader() .getResourceAsStream(CONFIG_FILE_PATH);) { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document profilesDom = builder.parse(new InputSource(profilesXml)); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); NodeList profilesNodeList = (NodeList) xpath.evaluate("/CSWProfiles/Profile", profilesDom, XPathConstants.NODESET); for (int pidx = 0; pidx < profilesNodeList.getLength(); pidx++) { Node profileNode = profilesNodeList.item(pidx); String id = StringUtils .trimToEmpty((String) xpath.evaluate("ID", profileNode, XPathConstants.STRING)); String name = StringUtils .trimToEmpty((String) xpath.evaluate("Name", profileNode, XPathConstants.STRING)); String namespace = StringUtils .trimToEmpty((String) xpath.evaluate("CswNamespace", profileNode, XPathConstants.STRING)); String description = StringUtils .trimToEmpty((String) xpath.evaluate("Description", profileNode, XPathConstants.STRING)); String getRecordsReqXslt = StringUtils.trimToEmpty((String) xpath .evaluate("GetRecords/XSLTransformations/Request", profileNode, XPathConstants.STRING)); String getRecordsRspXslt = StringUtils.trimToEmpty((String) xpath .evaluate("GetRecords/XSLTransformations/Response", profileNode, XPathConstants.STRING)); String getRecordByIdReqKVP = StringUtils.trimToEmpty( (String) xpath.evaluate("GetRecordByID/RequestKVPs", profileNode, XPathConstants.STRING)); String getRecordByIdRspXslt = StringUtils.trimToEmpty((String) xpath .evaluate("GetRecordByID/XSLTransformations/Response", profileNode, XPathConstants.STRING)); Profile prof = new Profile(); prof.setId(id); prof.setName(name); prof.setDescription(description); prof.setGetRecordsReqXslt(getRecordsReqXslt); prof.setGetRecordsRspXslt(getRecordsRspXslt); prof.setKvp(getRecordByIdReqKVP); prof.setGetRecordByIdRspXslt(getRecordByIdRspXslt); profiles.add(prof); } } LOG.info(String.format("CSW profiles loaded.")); return profiles; }
From source file:org.alloy.metal.xml.merge.ImportProcessor.java
public ImportProcessor(ResourceLoader loader) { this.loader = loader; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try {//from w w w.j ava2s. c o m builder = dbf.newDocumentBuilder(); XPathFactory factory = XPathFactory.newInstance(); xPath = factory.newXPath(); } catch (ParserConfigurationException e) { LOG.error("Unable to create document builder", e); throw new RuntimeException(e); } }
From source file:eu.smartfp7.terrier.sensor.ParserUtility.java
public static EdgeNodeSnapShot parse(InputStream is) throws Exception { DocumentBuilderFactory xmlfact = DocumentBuilderFactory.newInstance(); xmlfact.setNamespaceAware(true);//from w w w .j av a 2 s . c o m Document document = xmlfact.newDocumentBuilder().parse(is); NamespaceContext ctx = new NamespaceContext() { @Override public Iterator getPrefixes(String namespaceURI) { // TODO Auto-generated method stub return null; } @Override public String getPrefix(String namespaceURI) { // TODO Auto-generated method stub return null; } @Override public String getNamespaceURI(String prefix) { String uri = null; /* * xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:smart="http://www.ait.gr/ait_web_site/faculty/apne/schema.xml#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:contact="http://www.w3.org/2000/10/swap/pim/contact#" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:time="http://www.w3.org/2006/time#" xml:base="http://www.ait.gr/ait_web_site/faculty/apne/report.xml" * */ if (prefix.equals("rdf")) { uri = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; } if (prefix.equals("smart")) { uri = "http://www.ait.gr/ait_web_site/faculty/apne/schema.xml#"; } if (prefix.equals("dc")) { uri = "http://purl.org/dc/elements/1.1/#"; } if (prefix.equals("geo")) { uri = "http://www.w3.org/2003/01/geo/wgs84_pos#"; } if (prefix.equals("time")) { uri = "http://www.w3.org/2006/time#"; } return uri; } }; // find the node data XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(ctx); String id = (String) xpath.compile("//smart:Node/@rdf:ID").evaluate(document, XPathConstants.STRING); String lat = (String) xpath.compile("//smart:Node/geo:lat/text()").evaluate(document, XPathConstants.STRING); String lon = (String) xpath.compile("//smart:Node/geo:long/text()").evaluate(document, XPathConstants.STRING); String fullName = (String) xpath.compile("//smart:Node/dc:fullName/text()").evaluate(document, XPathConstants.STRING); Node node = new Node(new Double(lat), new Double(lon), id, fullName); String time = (String) xpath.compile("//smart:Report/time:inXSDDateTime/text()").evaluate(document, XPathConstants.STRING); String reportId = (String) xpath.compile("//smart:Report/@rdf:ID").evaluate(document, XPathConstants.STRING); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); Calendar c = Calendar.getInstance(); ; c.setTime(df.parse(time)); String density = (String) xpath.compile("//smart:Crowd/smart:density/text()").evaluate(document, XPathConstants.STRING); String cameraGain = (String) xpath.compile("//smart:Crowd/smart:cameraGain/text()").evaluate(document, XPathConstants.STRING); NodeList list = (NodeList) xpath.compile("//smart:Crowd/smart:colour").evaluate(document, XPathConstants.NODESET); double[] colors = new double[list.getLength()]; for (int i = 0; i < list.getLength(); i++) { org.w3c.dom.Node colorNode = list.item(i); String v = colorNode.getFirstChild().getTextContent(); colors[i] = new Double(v); } CrowdReport crowdReport = new CrowdReport(reportId, new Double(density), new Double(cameraGain), colors); EdgeNodeSnapShot snapShot = new EdgeNodeSnapShot(node, id, c, crowdReport); return snapShot; }
From source file:Main.java
public static XPath getXPathInstance() { XPathFactory factory = XPathFactory.newInstance(); return factory.newXPath(); }
From source file:com.freedomotic.helpers.HttpHelper.java
public HttpHelper() { try {/*from ww w. j a v a 2 s . c o m*/ DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); documentBuilder = builderFactory.newDocumentBuilder(); } catch (ParserConfigurationException ex) { LOG.error(ex.getMessage()); } XPathFactory xpathFactory = XPathFactory.newInstance(); xPath = xpathFactory.newXPath(); setConnectionTimeout(DEFAULT_TIMEOUT); }
From source file:org.opencastproject.remotetest.util.JobUtils.java
/** * Parses the job instance represented by <code>xml</code> and extracts the job identifier. * /*from w ww. jav a 2 s . c o m*/ * @param xml * the job instance * @return the job identifier * @throws Exception * if parsing fails */ public static String getJobId(String xml) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(IOUtils.toInputStream(xml, "UTF-8")); return ((Element) XPathFactory.newInstance().newXPath().compile("/*").evaluate(doc, XPathConstants.NODE)) .getAttribute("id"); }