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:org.opencastproject.remotetest.server.CaptureAdminRestEndpointTest.java
@Test public void testGetAgents() throws Exception { String endpoint = "/capture-admin/agents"; HttpGet get = new HttpGet(BASE_URL + endpoint + ".xml"); String xmlResponse = EntityUtils.toString(httpClient.execute(get).getEntity()); Main.returnClient(httpClient);//from ww w .jav a 2 s . c o m // parse the xml and extract the running clients names DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(IOUtils.toInputStream(xmlResponse, "UTF-8")); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList agents = (NodeList) xPath.compile("//*[local-name() = 'agent']").evaluate(doc, XPathConstants.NODESET); // validate the REST endpoint for each agent state is functional for (int i = 0; i < agents.getLength(); i++) { try { httpClient = Main.getClient(); String agentName = (String) xPath.evaluate("*[local-name() = 'name']/text()", agents.item(i), XPathConstants.STRING); HttpGet agentGet = new HttpGet(BASE_URL + endpoint + "/" + agentName + ".xml"); int agentResponse = httpClient.execute(agentGet).getStatusLine().getStatusCode(); assertEquals(HttpStatus.SC_OK, agentResponse); } finally { Main.returnClient(httpClient); } } }
From source file:com.fortysevendeg.lab.WeatherTask.java
/** * Performs work in the background invoking the weather remote service and parses the xml results into temp values * @param strings the place params to search form * @return the temperature in celsius//from ww w . ja v a2 s . c om */ @Override protected final Integer doInBackground(String... strings) { int temp = ERROR; try { String xml = fetchWeatherData(strings[0]); if (xml != null) { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(context.getString(R.string.xpath_weather_service_temperature)); Object result = expr.evaluate(new InputSource(new StringReader(xml)), XPathConstants.NODESET); NodeList nodes = (NodeList) result; if (nodes.getLength() > 0) { temp = Integer.valueOf(nodes.item(0).getAttributes().getNamedItem("data").getNodeValue()); } } } catch (XPathExpressionException e) { Log.wtf(WeatherTask.class.toString(), e); } catch (IOException e) { Log.wtf(WeatherTask.class.toString(), e); } return temp; }
From source file:org.ow2.chameleon.fuchsia.push.base.subscriber.tool.HubDiscovery.java
public String hasTopic(Document doc) { String topic;/*from w ww .j ava 2 s .c o m*/ XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); XPathExpression xPathExpression; try { xPathExpression = xPath.compile("/feed/link[@rel='self']/@href"); topic = xPathExpression.evaluate(doc); if ((topic == null) || (topic.length() == 0)) { xPathExpression = xPath.compile("//link[@rel='self']/@href"); topic = xPathExpression.evaluate(doc); } if (topic.length() == 0) { return null; } return topic; } catch (XPathExpressionException e) { LOGGER.error("Invalid XpathExpression", e); return null; } }
From source file:gov.nih.nci.cabig.open2caaers.binding.ParticipantODMMessageBinding.java
@Override public void writeResponse(Exchange exchange, HttpServletResponse response) throws IOException { // get the status code from the mapping and set it here String body = exchange.getOut().getBody(String.class); if (StringUtils.isBlank(body)) { // if body is null do the default processing and return super.writeResponse(exchange, response); return;/* w ww .j a v a 2 s . c o m*/ } XPath xPath = XPathFactory.newInstance().newXPath(); String errorMessage = ""; try { errorMessage = xPath.evaluate("/Response/@ErrorClientResponseMessage", new InputSource(new StringReader(body))); } catch (XPathExpressionException e) { log.debug(e); } String reasonCode = ""; try { reasonCode = xPath.evaluate("/Response/@ReasonCode", new InputSource(new StringReader(body))); } catch (XPathExpressionException e) { log.debug(e); } if (reasonCode.equals("soap:Client")) { // signifies XML validation failed reasonCode = "WS_GEN_007"; String referenceNumber = String.valueOf(exchange.getProperty(ExchangePreProcessor.CORRELATION_ID)); response.setStatus(codeMap.get(reasonCode)); response.getWriter() .write("<Response ReferenceNumber=\"" + referenceNumber + "\" IsTransactionSuccessful=\"0\" ReasonCode=\"" + reasonCode + "\" ErrorClientResponseMessage=\"" + "Schema validation failed as required by caAERS Participant Service: " + errorMessage + "\"/>"); } else { exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, codeMap.get(reasonCode)); super.writeResponse(exchange, response); } }
From source file:ch.dbs.actions.bestellung.EZBJOP.java
/** * This class uses the official EZB/ZDB API from * http://services.dnb.de/fize-service/gvr/full.xml. *///from ww w .j a v a2 s . c o m public EZBForm read(final String content) { final EZBForm ezbform = new EZBForm(); try { if (content != null) { final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); final DocumentBuilder builder = domFactory.newDocumentBuilder(); final Document doc = builder.parse(new InputSource(new StringReader(content))); final XPathFactory factory = XPathFactory.newInstance(); final XPath xpath = factory.newXPath(); // references electronic data // final XPathExpression exprRefE = xpath.compile("//ElectronicData/References/Reference"); // final NodeList resultListRefE = (NodeList) exprRefE.evaluate(doc, XPathConstants.NODESET); // // for (int i = 0; i < resultListRefE.getLength(); i++) { // final Node firstResultNode = resultListRefE.item(i); // final Element result = (Element) firstResultNode; // // final EZBReference ref = new EZBReference(); // // // EZB URLs // final String url = getValue(result.getElementsByTagName("URL")); // ref.setUrl(url); // // // Label for URLs // final String label = getValue(result.getElementsByTagName("Label")); // ref.setLabel(label); // // ezbform.getReferencesonline().add(ref); // } // electronic data final XPathExpression exprE = xpath.compile("//ElectronicData/ResultList/Result"); final NodeList resultListE = (NodeList) exprE.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < resultListE.getLength(); i++) { final Node firstResultNode = resultListE.item(i); final Element result = (Element) firstResultNode; final EZBDataOnline online = new EZBDataOnline(); // state online.setState(Integer.valueOf(result.getAttribute("state"))); // 0 free accessible if (online.getState() == JOPState.FREE.getValue()) { online.setAmpel("green"); online.setComment("availresult.free"); // 1 partially free accesible } else if (online.getState() == JOPState.FREE_PARTIALLY.getValue()) { online.setAmpel("green"); online.setComment("availresult.partially_free"); // 2 licensed ; 3 partially licensed } else if (online.getState() == JOPState.LICENSED.getValue() || online.getState() == JOPState.LICENSED_PARTIALLY.getValue()) { online.setAmpel("yellow"); online.setComment("availresult.abonniert"); // journal not online for periode } else if (online.getState() == JOPState.OUTSIDE_PERIOD.getValue()) { online.setAmpel("red"); online.setComment("availresult.timeperiode"); // not indexed } else if (online.getState() == JOPState.NO_HITS.getValue()) { online.setAmpel("red"); online.setComment("availresult.nohits"); } else { online.setAmpel("red"); online.setComment("availresult.not_licensed"); } // title String title = getValue(result.getElementsByTagName("Title")); if (title != null) { title = Jsoup.clean(title, Whitelist.none()); online.setTitle(Jsoup.parse(title).text()); } online.setUrl(getValue(result.getElementsByTagName("AccessURL"))); online.setLevel(getValue(result.getElementsByTagName("AccessLevel"))); online.setReadme(getValue(result.getElementsByTagName("ReadmeURL"))); // National licenses etc. online.setAdditional(getValue(result.getElementsByTagName("Additional"))); ezbform.getOnline().add(online); } // Title not found if (resultListE.getLength() == 0) { final EZBDataOnline online = new EZBDataOnline(); online.setAmpel("red"); online.setComment("availresult.nohits"); online.setState(JOPState.NO_HITS.getValue()); ezbform.getOnline().add(online); } // references print data final XPathExpression exprRefP = xpath.compile("//PrintData/References/Reference"); final NodeList resultListRefP = (NodeList) exprRefP.evaluate(doc, XPathConstants.NODESET); final EZBReference ref = new EZBReference(); for (int i = 0; i < resultListRefP.getLength(); i++) { final Node firstResultNode = resultListRefP.item(i); final Element result = (Element) firstResultNode; // EZB URLs ref.setUrl(getValue(result.getElementsByTagName("URL"))); // Label for URLs // final String label = getValue(result.getElementsByTagName("Label")); ref.setLabel("availresult.link_title_print"); ezbform.getReferencesprint().add(ref); } // print data final XPathExpression exprP = xpath.compile("//PrintData/ResultList/Result"); final NodeList resultListP = (NodeList) exprP.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < resultListP.getLength(); i++) { final Node firstResultNode = resultListP.item(i); final Element result = (Element) firstResultNode; final EZBDataPrint print = new EZBDataPrint(); // state print.setState(Integer.valueOf(result.getAttribute("state"))); // title String title = getValue(result.getElementsByTagName("Title")); if (title != null) { title = Jsoup.clean(title, Whitelist.none()); print.setTitle(Jsoup.parse(title).text()); } print.setLocation(getValue(result.getElementsByTagName("Location"))); print.setCallnr(getValue(result.getElementsByTagName("Signature"))); print.setCoverage(getValue(result.getElementsByTagName("Period"))); // set previous extracted URL and label print.setInfo(ref); // in stock ; partially in stock if (print.getState() == JOPState.LICENSED.getValue() || print.getState() == JOPState.LICENSED_PARTIALLY.getValue()) { print.setAmpel("yellow"); print.setComment("availresult.print"); // only return if existing in Print ezbform.getPrint().add(print); } } } } catch (final XPathExpressionException e) { LOG.error(e.toString()); } catch (final SAXParseException e) { LOG.error(e.toString()); } catch (final SAXException e) { LOG.error(e.toString()); } catch (final IOException e) { LOG.error(e.toString()); } catch (final ParserConfigurationException e) { LOG.error(e.toString()); } catch (final Exception e) { LOG.error(e.toString()); } return ezbform; }
From source file:com.rest4j.generator.DocGeneratorTest.java
@Test public void testPreprocess() throws Exception { Document xml = getDocument("doc-generator-graph.xml"); gen.preprocess(xml);/* w w w . ja va 2 s . c o m*/ XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); xpath.setNamespaceContext(new Generator.APINamespaceContext()); assertEquals("patch A,patch B,B,patch C,C", modelsToString(xpath.compile("//api:endpoint[api:service/@method='patch']/api:body/api:model") .evaluate(xml, XPathConstants.NODESET))); assertEquals("C", modelsToString(xpath.compile("//api:endpoint[api:service/@method='patch']/api:response/api:model") .evaluate(xml, XPathConstants.NODESET))); assertEquals("B,C", modelsToString(xpath.compile("//api:endpoint[api:route='get']/api:response/api:model") .evaluate(xml, XPathConstants.NODESET))); assertEquals("B,C", modelsToString(xpath.compile("//api:endpoint[api:route='get']/api:response/api:model") .evaluate(xml, XPathConstants.NODESET))); assertEquals("", modelsToString(xpath.compile("//api:endpoint[api:route='binary']/api:response/api:model") .evaluate(xml, XPathConstants.NODESET))); }
From source file:org.jboss.spring.factory.NamedXmlBeanFactory.java
private void initializeNames(Resource resource) { try {//from w w w . jav a 2 s .co m XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setNamespaceContext(new NamespaceContext() { @Override public String getNamespaceURI(String prefix) { return "http://www.springframework.org/schema/beans"; } @Override public String getPrefix(String namespaceURI) { return "beans"; } @Override public Iterator getPrefixes(String namespaceURI) { return Collections.singleton("beans").iterator(); } }); String expression = "/beans:beans/beans:description"; InputSource inputSource = new InputSource(resource.getInputStream()); String description = xPath.evaluate(expression, inputSource); if (description != null) { Matcher bfm = Pattern.compile(Constants.BEAN_FACTORY_ELEMENT).matcher(description); if (bfm.find()) { this.name = bfm.group(1); } Matcher pbfm = Pattern.compile(Constants.PARENT_BEAN_FACTORY_ELEMENT).matcher(description); if (pbfm.find()) { String parentName = pbfm.group(1); try { this.setParentBeanFactory((BeanFactory) Util.lookup(parentName, BeanFactory.class)); } catch (Exception e) { throw new BeanDefinitionStoreException( "Failure during parent bean factory JNDI lookup: " + parentName, e); } } Matcher inst = Pattern.compile(Constants.INSTANTIATION_ELEMENT).matcher(description); if (inst.find()) { instantiate = Boolean.parseBoolean(inst.group(1)); } } if (this.name == null || "".equals(StringUtils.trimAllWhitespace(this.name))) { this.name = this.defaultName; } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.brewtab.ircbot.applets.WundergroundApplet.java
public WundergroundApplet(SQLProperties properties, String apikey) { this.properties = properties; this.apikey = apikey; try {/*from w ww.j a v a2 s. c om*/ documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } xpath = XPathFactory.newInstance().newXPath(); options = new Options(); options.addOption("c", "metric", false, "use metric units"); options.addOption("f", "imperial", false, "use imperial units (default)"); options.addOption("n", "no-save", false, "do not save the query as default"); parser = new PosixParser(); }
From source file:ch.entwine.weblounge.common.impl.util.xml.XPathHelper.java
/** * Returns the query result or <code>null</code>. * <p>// w ww. j a va 2s .c om * <b>Note:</b> This signature creates a new <code>XPath</code> processor on * every call, which is probably fine for testing but not favorable when it * comes to production use, since creating an <code>XPath</code> processor is * resource intensive. * * @param node * the context node * @param xpathExpression * the xpath expression * @param defaultValue * the default value * * @return the selected string or <code>defaultValue</code> if the query * didn't yield a result */ public static String valueOf(Node node, String xpathExpression, String defaultValue) { XPath xpath = XPathFactory.newInstance().newXPath(); return valueOf(node, xpathExpression, defaultValue, xpath); }
From source file:com.mnxfst.testing.server.cfg.PTestServerConfigurationParser.java
/** * Initializes the instance//from w ww . j av a 2 s . co m */ public PTestServerConfigurationParser() { XPath xpath = XPathFactory.newInstance().newXPath(); try { xpathExpressionHostname = xpath.compile(XPATH_HOSTNAME); xpathExpressionPort = xpath.compile(XPATH_PORT); xpathExpressionSocketPoolSize = xpath.compile(XPATH_SOCKET_POOL_SIZE); xpathExpressionAllHandlerSettings = xpath.compile(XPATH_ALL_HANDLER_SETTINGS); xpathExpressionHandlerClass = xpath.compile(XPATH_HANDLER_CLASS); xpathExpressionHandlerPath = xpath.compile(XPATH_HANDLER_PATH); } catch (XPathExpressionException e) { throw new RuntimeException( "Failed to create xpath expressions from preconfigured pattern. Error: " + e.getMessage()); } }