Java Code Examples for javax.xml.xpath.XPathExpression

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project jangaroo-tools, under directory /asdoc-scraping/src/main/java/net/jangaroo/tools/asdocscreenscraper/.

Source file: ASDocScreenScraper.java

  24 
vote

private String getClassDoc() throws XPathExpressionException {
  XPath xpath=xPathFactory.newXPath();
  XPathExpression classDoc=xpath.compile("//*[@id='content']//*[name()='div'][@class='MainContent']");
  Node classDocNode=(Node)classDoc.evaluate(document,XPathConstants.NODE);
  if (classDocNode != null) {
    NodeList classDocNodes=classDocNode.getChildNodes();
    return getASDoc(classDocNodes,null);
  }
  return "";
}
 

Example 2

From project blog_1, under directory /miniprojects/generic-pojo-mappers/src/main/java/net/jakubholy/blog/genericmappers/xml/.

Source file: XmlElements.java

  23 
vote

private <T>T getNodesMatchingXPath(String xpathExpression,QName expectedResult,Class<T> resultType){
  try {
    XPathExpression nodesXPath=makeXPathExpression(xpathExpression);
    @SuppressWarnings("unchecked") T result=(T)nodesXPath.evaluate(parsedXmlDocument,expectedResult);
    return result;
  }
 catch (  XPathExpressionException e) {
    throw new RuntimeException("Invalid xpath '" + xpathExpression + "': "+ e.getMessage(),e);
  }
}
 

Example 3

From project cascading, under directory /src/xml/cascading/operation/xml/.

Source file: XPathFilter.java

  23 
vote

@Override public boolean isRemove(FlowProcess flowProcess,FilterCall<Pair<DocumentBuilder,Tuple>> filterCall){
  String argument=(String)filterCall.getArguments().getString(0);
  Document document=parseDocument(filterCall.getContext().getLhs(),argument);
  XPathExpression expression=getExpressions().get(0);
  try {
    boolean value=(Boolean)expression.evaluate(document,XPathConstants.BOOLEAN);
    LOG.debug("xpath: {} matches: {}",paths[0],value);
    return value == removeMatch;
  }
 catch (  XPathExpressionException exception) {
    throw new OperationException("could not evaluate xpath expression: " + paths[0],exception);
  }
}
 

Example 4

From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/xml/.

Source file: XMLUtils.java

  23 
vote

public static String getXPathValue(IFile file,String xPath) throws Exception {
  DocumentBuilderFactory docFactory=DocumentBuilderFactory.newInstance();
  docFactory.setNamespaceAware(false);
  docFactory.setValidating(false);
  DocumentBuilder builder=docFactory.newDocumentBuilder();
  XPathFactory factory=XPathFactory.newInstance();
  XPath xpath=factory.newXPath();
  final XPathExpression exp=xpath.compile(xPath);
  Document doc=builder.parse(new InputSource(file.getContents()));
  final NodeList nodeList=(NodeList)exp.evaluate(doc,XPathConstants.NODESET);
  return XMLUtils.getNodeValue(nodeList);
}
 

Example 5

From project edna-rcp, under directory /org.edna.plugingenerator/src/org/edna/plugingenerator/generator/.

Source file: WizardHelpers.java

  23 
vote

static public String getReferencedObject(String id,IFile umlFile) throws Exception {
  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
  DocumentBuilder db=dbf.newDocumentBuilder();
  Document doc=db.parse(umlFile.getContents());
  doc.getDocumentElement().normalize();
  XPath xpath=XPathFactory.newInstance().newXPath();
  XPathExpression expr=xpath.compile("//*[@id='" + id + "']");
  NodeList nodelist=(NodeList)expr.evaluate(doc,XPathConstants.NODESET);
  if (nodelist.getLength() < 1) {
    throw new IllegalArgumentException(String.format("The item with id %s cannot be found in file %s",id,umlFile));
  }
  return nodelist.item(0).getAttributes().getNamedItem("name").getNodeValue();
}
 

Example 6

From project heritrix3, under directory /engine/src/main/java/org/archive/crawler/migrate/.

Source file: MigrateH1to3Tool.java

  23 
vote

/** 
 * Given a Document, return a Map of all non-blank simple text  nodes, keyed by the pseudo-XPath to their parent element. 
 * @param h1order Document to extract Map
 * @return Map<String,String> Xpath-like-String -> non-blank text content
 * @throws XPathExpressionException
 */
public static Map<String,String> flattenH1Order(Document h1order) throws XPathExpressionException {
  Map<String,String> flattened=new LinkedHashMap<String,String>();
  XPathExpression xpath=XPathFactory.newInstance().newXPath().compile("//text()");
  NodeList nodes=(NodeList)xpath.evaluate(h1order,XPathConstants.NODESET);
  for (int i=0; i < nodes.getLength(); i++) {
    Node node=nodes.item(i);
    if (StringUtils.isNotBlank(node.getTextContent())) {
      String pseudoXPath=getPseudoXpath(node.getParentNode());
      pseudoXPath=pseudoXPath.replaceFirst("/crawl-order","/");
      flattened.put(pseudoXPath,node.getTextContent());
    }
  }
  return flattened;
}
 

Example 7

From project arquillian-container-jbossas, under directory /jbossas-managed-4.2/src/main/java/org/jboss/arquillian/container/jbossas/managed_4_2/.

Source file: ManagementViewParser.java

  22 
vote

private static List<String> extractServletNames(String descriptor) throws Exception {
  Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(descriptor.getBytes()));
  XPathExpression xPathExpression=XPathFactory.newInstance().newXPath().compile("/web-app/servlet/servlet-name");
  NodeList nodes=(NodeList)xPathExpression.evaluate(doc,XPathConstants.NODESET);
  List<String> servletNames=new ArrayList<String>();
  for (int i=0; i < nodes.getLength(); i++) {
    Node node=nodes.item(i);
    servletNames.add(node.getTextContent());
  }
  return servletNames;
}
 

Example 8

From project arquillian-core, under directory /config/impl-base/src/test/java/org/jboss/arquillian/config/descriptor/impl/.

Source file: AssertXPath.java

  22 
vote

/** 
 * Assert that the specified XPath Expression resolves to the specified values. <br/><br/> Assertions:<br/> "ExpectedValue count should match found Node count" <br/>  "XPath content should match expected value" <br/>
 * @param xml The XML to assert against
 * @param expression XPath expression to extract
 * @param expectedValue The Expected values found by expression
 * @throws Exception XML/XPath related parse exceptions
 */
public static void assertXPath(String xml,String expression,Object... expectedValue) throws Exception {
  Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));
  XPathExpression xPathExpression=XPathFactory.newInstance().newXPath().compile(expression);
  NodeList nodes=(NodeList)xPathExpression.evaluate(doc,XPathConstants.NODESET);
  Assert.assertEquals("ExpectedValue count should match found Node count",expectedValue.length,nodes.getLength());
  for (int i=0; i < nodes.getLength(); i++) {
    Node node=nodes.item(i);
    Assert.assertEquals("XPath content should match expected value",String.valueOf(expectedValue[i]),node.getTextContent());
  }
}
 

Example 9

From project arquillian_deprecated, under directory /containers/jbossas-remote-5/src/main/java/org/jboss/arquillian/container/jbossas/remote_5_0/.

Source file: ManagementViewParser.java

  22 
vote

private static List<String> extractServletNames(String descriptor) throws Exception {
  Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(descriptor.getBytes()));
  XPathExpression xPathExpression=XPathFactory.newInstance().newXPath().compile("/web-app/servlet/servlet-name");
  NodeList nodes=(NodeList)xPathExpression.evaluate(doc,XPathConstants.NODESET);
  List<String> servletNames=new ArrayList<String>();
  for (int i=0; i < nodes.getLength(); i++) {
    Node node=nodes.item(i);
    servletNames.add(node.getTextContent());
  }
  return servletNames;
}
 

Example 10

From project jASM_16, under directory /src/main/java/de/codesourcery/jasm16/ide/.

Source file: ProjectConfiguration.java

  22 
vote

private void parseXML(Document doc) throws XPathExpressionException {
  final XPathFactory factory=XPathFactory.newInstance();
  final XPath xpath=factory.newXPath();
  final XPathExpression nameExpr=xpath.compile("/project/name");
  final XPathExpression outputFolderExpr=xpath.compile("/project/outputFolder");
  final XPathExpression executableNameExpr=xpath.compile("/project/executableName");
  final XPathExpression srcFoldersExpr=xpath.compile("/project/sourceFolders/sourceFolder");
  this.outputFolder=getValue(outputFolderExpr,doc);
  this.projectName=getValue(nameExpr,doc);
  this.executableName=getValue(executableNameExpr,doc);
  this.sourceFolders.clear();
  this.sourceFolders.addAll(getValues(srcFoldersExpr,doc));
}
 

Example 11

From project jCAE, under directory /amibe/src-test/org/jcae/mesh/.

Source file: MesherTest.java

  22 
vote

private long getMesherRuntimeMillis(Document doc){
  XPath xpath=XPathFactory.newInstance().newXPath();
  try {
    XPathExpression xpathTimestamp=xpath.compile("//millis/text()");
    NodeList events=(NodeList)xpath.evaluate("//message/text()[contains(string(), 'Meshing face')]/ancestor::record",doc,XPathConstants.NODESET);
    long t1=Long.parseLong(xpathTimestamp.evaluate(events.item(0)));
    long t2=Long.parseLong(xpathTimestamp.evaluate(events.item(events.getLength() - 1).getNextSibling()));
    return t2 - t1;
  }
 catch (  XPathExpressionException ex) {
    throw new RuntimeException(ex.getCause());
  }
}
 

Example 12

From project juzu, under directory /doc/tutorial/examples/src/main/java/examples/tutorial/weather3/.

Source file: WeatherService.java

  22 
vote

public String getTemperature(String location,String grade){
  try {
    XPath xpath=XPathFactory.newInstance().newXPath();
    XPathExpression expr=xpath.compile("//temp_" + grade + "/@data");
    String url="http://www.google.com/ig/api?weather=" + location;
    InputSource src=new InputSource(url);
    src.setEncoding("ISO-8859-1");
    return expr.evaluate(src);
  }
 catch (  XPathExpressionException e) {
    return "unavailable";
  }
}
 

Example 13

From project MEditor, under directory /editor-common/editor-common-server/src/main/java/cz/mzk/editor/server/fedora/.

Source file: FedoraAccessImpl.java

  22 
vote

/** 
 * Datastream in list of datastreams.
 * @param datastreams the datastreams
 * @param dsId the ds id
 * @return true, if successful
 * @throws XPathExpressionException the x path expression exception
 */
private boolean datastreamInListOfDatastreams(Document datastreams,String dsId) throws XPathExpressionException {
  XPathFactory factory=XPathFactory.newInstance();
  XPath xpath=factory.newXPath();
  XPathExpression expr=xpath.compile("/objectDatastreams/datastream[@dsid='" + dsId + "']");
  Node oneNode=(Node)expr.evaluate(datastreams,XPathConstants.NODE);
  return (oneNode != null);
}
 

Example 14

From project openclaws, under directory /cat/WEB-INF/src/edu/rit/its/claws/cat/.

Source file: ClawsDocument.java

  22 
vote

/** 
 * Returns the Node matching the given xpath
 * @throws XPathExpressionException
 */
public static Node xpathNode(String path,Document doc) throws XPathExpressionException {
  XPathExpression xpe;
  xpe=xpath.compile(path);
  Node n=(Node)xpe.evaluate(doc,XPathConstants.NODE);
  return n;
}
 

Example 15

From project openengsb-framework, under directory /itests/src/test/java/org/openengsb/itests/exam/.

Source file: WSPortIT.java

  22 
vote

private String transformResponseToMessage(DOMSource response) throws Exception {
  Document document=(Document)response.getNode();
  XPath xpath=XPathFactory.newInstance().newXPath();
  XPathExpression expression=xpath.compile("//return/text()");
  String result=(String)expression.evaluate(document,XPathConstants.STRING);
  return result;
}
 

Example 16

From project OpenTripPlanner, under directory /opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/ned/.

Source file: NEDDownloader.java

  22 
vote

private XPathExpression makeXPathExpression(String xpathStr) throws XPathExpressionException {
  XPathFactory factory=XPathFactory.newInstance();
  XPath xpath=factory.newXPath();
  xpath.setNamespaceContext(new EDCNamespaceContext());
  XPathExpression expr=xpath.compile(xpathStr);
  return expr;
}
 

Example 17

From project recommenders, under directory /plugins/org.eclipse.recommenders.rdk/src/org/eclipse/recommenders/rdk/utils/.

Source file: Artifacts.java

  22 
vote

private static Optional<String> find(final String string,final Document doc) throws XPathExpressionException {
  final XPath xpath=XPathFactory.newInstance().newXPath();
  final XPathExpression expr=xpath.compile(string);
  final Node node=(Node)expr.evaluate(doc,XPathConstants.NODE);
  if (node == null) {
    return Optional.absent();
  }
 else {
    return Optional.of(node.getTextContent());
  }
}
 

Example 18

From project rest-fixture, under directory /RestFixture/src/main/java/smartrics/rest/fitnesse/fixture/support/.

Source file: Tools.java

  22 
vote

private static XPathExpression toExpression(String xpathExpression){
  try {
    XPathFactory xpathFactory=XPathFactory.newInstance();
    XPath xpath=xpathFactory.newXPath();
    XPathExpression expr=xpath.compile(xpathExpression);
    return expr;
  }
 catch (  XPathExpressionException e) {
    throw new IllegalArgumentException("xPath expression can not be compiled: " + xpathExpression,e);
  }
}
 

Example 19

From project RestFixture, under directory /src/main/java/smartrics/rest/fitnesse/fixture/support/.

Source file: Tools.java

  22 
vote

public static XPathExpression toExpression(Map<String,String> ns,String xpathExpression){
  try {
    XPathFactory xpathFactory=XPathFactory.newInstance();
    XPath xpath=xpathFactory.newXPath();
    if (ns.size() > 0) {
      xpath.setNamespaceContext(toNsContext(ns));
    }
    XPathExpression expr=xpath.compile(xpathExpression);
    return expr;
  }
 catch (  XPathExpressionException e) {
    throw new IllegalArgumentException("xPath expression can not be compiled: " + xpathExpression,e);
  }
}
 

Example 20

From project roolie, under directory /src/org/roolie/util/component/.

Source file: XmlUtil.java

  22 
vote

protected XPathExpression getXPathExpression(String sExpression) throws XPathExpressionException {
  XPathExpression expression=xPathExpressions.get(sExpression);
  if (null == expression) {
    XPath xPath=xPathFactory.newXPath();
    expression=xPath.compile(sExpression);
    xPathExpressions.put(sExpression,expression);
  }
  return expression;
}
 

Example 21

From project s-ramp, under directory /s-ramp-repository/src/main/java/org/overlord/sramp/repository/derived/.

Source file: WsdlDeriver.java

  22 
vote

/** 
 * Process the entire wsdl for all derived content.
 * @param derivedArtifacts
 * @param artifact
 * @param definitions
 * @param xpath
 * @throws XPathExpressionException
 */
public static void processDefinitions(IndexedArtifactCollection derivedArtifacts,BaseArtifactType artifact,Element definitions,XPath xpath) throws XPathExpressionException {
  XPathExpression expr=xpath.compile("./wsdl:types/xsd:schema");
  NodeList schemas=(NodeList)expr.evaluate(definitions,XPathConstants.NODESET);
  for (int idx=0; idx < schemas.getLength(); idx++) {
    Element schema=(Element)schemas.item(idx);
    XsdDeriver.processSchema(derivedArtifacts,artifact,schema,xpath);
  }
  processMessages(derivedArtifacts,artifact,definitions,xpath);
  processPortTypes(derivedArtifacts,artifact,definitions,xpath);
}
 

Example 22

From project SOCIETIES-SCE-Services, under directory /3rdPartyServices/EnterpriseServices/CollaborationTools/CollabTools-Server/src/main/java/org/societies/enterprise/collabtools/Interpretation/.

Source file: AlchemyAPISimple.java

  22 
vote

private String getNodeValue(XPathFactory factory,Document doc,String xpathStr) throws XPathExpressionException {
  XPath xpath=factory.newXPath();
  XPathExpression expr=xpath.compile(xpathStr);
  Object result=expr.evaluate(doc,XPathConstants.NODESET);
  NodeList results=(NodeList)result;
  if (results.getLength() > 0 && null != results.item(0))   return results.item(0).getNodeValue();
  return null;
}
 

Example 23

From project spring-flex, under directory /spring-flex-core/src/main/java/org/springframework/flex/config/.

Source file: FlexConfigurationManager.java

  22 
vote

private XPathExpression getXPathExpression(String expression){
  try {
    XPathExpression compiledExpression=exprCache.get(expression);
    if (compiledExpression == null) {
      compiledExpression=xpath.compile(expression);
      exprCache.put(expression,compiledExpression);
    }
    return compiledExpression;
  }
 catch (  XPathExpressionException ex) {
    throw wrapException(ex);
  }
}
 

Example 24

From project tycho, under directory /tycho-its/src/test/java/org/eclipse/tycho/test/TYCHO192sourceBundles/.

Source file: Tycho192SourceBundleTest.java

  22 
vote

private void checkP2ContentXml(File p2Content) throws Exception {
  assertTrue(p2Content.isFile());
  Document p2ContentDOM=docBuilder.parse(p2Content);
  XPathExpression sourceBundleUnitExpression=xpath.compile("/units/unit[@id = 'helloworld.source']");
  Element sourceBundleUnitNode=(Element)sourceBundleUnitExpression.evaluate(p2ContentDOM.getDocumentElement(),XPathConstants.NODE);
  assertNotNull("unit with id 'helloworld.source' not found",sourceBundleUnitNode);
  assertHasMavenClassifierProperty(sourceBundleUnitNode);
}
 

Example 25

From project zen-project, under directory /zen-base/src/main/java/com/nominanuda/xml/.

Source file: XmlHelper.java

  22 
vote

/** 
 * @param nodeOrNodeList
 * @param xpathExpr
 * @param nsBindings in the form "n1","http://a.b.c/n1", "prefix2", "http://a.b.c/whatever"
 * @return
 * @throws XPathExpressionException 
 */
private Object xPath(Object nodeOrNodeList,String xpathExpr,QName resultType,String... nsBindings) throws IllegalArgumentException {
  try {
    XPath xpath=XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new MyNamespaceContext(nsBindings));
    XPathExpression expr=xpath.compile(xpathExpr);
    Object result=expr.evaluate(nodeOrNodeList,resultType);
    return result;
  }
 catch (  XPathExpressionException e) {
    return null;
  }
}
 

Example 26

From project addis, under directory /application/src/main/java/org/drugis/addis/util/.

Source file: ConvertDiabetesDatasetUtil.java

  21 
vote

private void renameStudies() throws IOException {
  for (  Study study : d_domain.getStudies()) {
    PubMedIdList pubmed=(PubMedIdList)study.getCharacteristic(BasicStudyCharacteristic.PUBMED);
    try {
      Document doc=getPubMedXML(pubmed);
      XPathFactory factory=XPathFactory.newInstance();
      XPath xpath=factory.newXPath();
      XPathExpression yearExpr=xpath.compile("/PubmedArticleSet/PubmedArticle[1]/MedlineCitation[1]/DateCreated[1]/Year[1]");
      Object yearResults=yearExpr.evaluate(doc,XPathConstants.NODESET);
      String year=((NodeList)yearResults).item(0).getTextContent();
      XPathExpression authorExpr=xpath.compile("/PubmedArticleSet/PubmedArticle[1]/MedlineCitation[1]/Article[1]/AuthorList[1]/Author/LastName");
      Object authorResults=authorExpr.evaluate(doc,XPathConstants.NODESET);
      NodeList authorNodes=(NodeList)authorResults;
      List<String> authors=new ArrayList<String>();
      for (int i=0; i < authorNodes.getLength(); i++) {
        authors.add(authorNodes.item(i).getTextContent());
      }
      String title="";
      if (authors.size() > 2) {
        title=authors.get(0) + " et al, " + year;
      }
 else {
        title=StringUtils.join(authors,", ") + ", " + year;
      }
      study.setName(title);
    }
 catch (    Exception e) {
      continue;
    }
  }
}
 

Example 27

From project cdk, under directory /xinclude/src/main/java/org/apache/cocoon/pipeline/component/xpointer/.

Source file: XPointerPart.java

  21 
vote

public boolean process(XPointerContext xpointerContext) throws SAXException, IOException {
  Document document=xpointerContext.getDocument();
  XPath xpath=XPF.newXPath();
  xpath.setNamespaceContext(xpointerContext);
  XPathExpression xpathExpression;
  try {
    xpathExpression=xpath.compile(expression);
  }
 catch (  XPathExpressionException e) {
    throw new SAXException("XPointer: expression \"" + expression + "\" is not a valid XPath expression",e);
  }
  try {
    NodeList nodeList=(NodeList)xpathExpression.evaluate(document,XPathConstants.NODESET);
    if (nodeList.getLength() > 0) {
      SAXConsumer consumer=xpointerContext.getXmlConsumer();
      LocatorImpl locator=new LocatorImpl();
      locator.setSystemId(xpointerContext.getSource().toString());
      consumer.setDocumentLocator(locator);
      for (int i=0; i < nodeList.getLength(); i++) {
        DOMUtils.stream(nodeList.item(i),consumer);
      }
      return true;
    }
 else {
      if (xpointerContext.getLogger().isDebugEnabled()) {
        xpointerContext.getLogger().debug("XPointer: expression \"" + expression + "\" gave no results.");
      }
      return false;
    }
  }
 catch (  XPathExpressionException e) {
    throw new SAXException("XPointer: impossible to select DOM fragment using expression \"" + expression + "\", see nested exception",e);
  }
}
 

Example 28

From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/framework/data/.

Source file: XmlSplitter.java

  21 
vote

/** 
 * Split a given org.w3c.dom.Node using a given XPath expression.
 * @param node The node to split.
 * @param expression The expression to use to split Node.
 * @return a List of org.w3c.dom.Node objects
 * @throws CiliaException When there is an error building the Xml parser or when there is a problem parsing the Node
 */
public static List split(Node node,String expression) throws CiliaException {
  List returnedDataSet=new ArrayList();
  XPath xpath=XPathFactory.newInstance().newXPath();
  XPathExpression expr=null;
  try {
    expr=xpath.compile(expression);
  }
 catch (  XPathExpressionException e) {
    e.printStackTrace();
    throw new CiliaException("Expression : " + expression + " is not valid in XmlSplitter"+ e.getMessage());
  }
  Object result=null;
  try {
    result=expr.evaluate(node,XPathConstants.NODESET);
  }
 catch (  XPathExpressionException e) {
    e.printStackTrace();
    throw new CiliaException("Expression : " + expression + " throws an exception"+ e.getMessage());
  }
  NodeList nodes=(NodeList)result;
  for (int i=0; i < nodes.getLength(); i++) {
    Node nn=nodes.item(i);
    returnedDataSet.add(nn);
  }
  if (nodes.getLength() == 0) {
    returnedDataSet.add(node);
  }
  return returnedDataSet;
}
 

Example 29

From project components, under directory /common/common/src/main/java/org/switchyard/component/common/selector/.

Source file: OperationSelector.java

  21 
vote

private QName xpathMatch(String expression,Document content) throws Exception {
  XPathFactory factory=XPathFactory.newInstance();
  XPath xpath=factory.newXPath();
  NodeList result=null;
  try {
    XPathExpression expr=xpath.compile(expression);
    result=NodeList.class.cast(expr.evaluate(content,XPathConstants.NODESET));
  }
 catch (  Exception e) {
    throw new Exception("Couldn't evaluate XPath expression '" + expression + "'",e);
  }
  if (result.getLength() == 1) {
    return QName.valueOf(result.item(0).getTextContent());
  }
 else   if (result.getLength() == 0) {
    throw new Exception("No node has been matched with the XPath expression '" + expression + "' in the payload. It couldn't determine the operation.");
  }
 else {
    throw new Exception("Multiple nodes have been matched with the XPath expression '" + expression + "' in the payload. It couldn't determine the operation.");
  }
}
 

Example 30

From project descriptors, under directory /test-util/src/main/java/org/jboss/shrinkwrap/descriptor/test/util/.

Source file: XmlAssert.java

  21 
vote

private static NodeList extractMatchingNodes(final Document doc,String xpathExpression){
  final XPathExpression xPathExpression;
  try {
    xPathExpression=XPathFactory.newInstance().newXPath().compile(xpathExpression);
  }
 catch (  final XPathExpressionException xee) {
    throw new RuntimeException(xee);
  }
  final NodeList nodes;
  try {
    nodes=(NodeList)xPathExpression.evaluate(doc,XPathConstants.NODESET);
  }
 catch (  final XPathExpressionException xee) {
    throw new RuntimeException(xee);
  }
  return nodes;
}
 

Example 31

From project drools-chance, under directory /drools-shapes/drools-shapes-examples/conyard-example/src/test/java/.

Source file: FactTest.java

  21 
vote

@Test public void testXMLNamespaces(){
  StringWriter writer;
  writer=new StringWriter();
  try {
    marshaller.marshal(painting,writer);
  }
 catch (  JAXBException e) {
    fail(e.getMessage());
  }
  try {
    Document dox=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(writer.toString().getBytes()));
    XPathFactory xPathFactory=XPathFactory.newInstance();
    XPath xPath=xPathFactory.newXPath();
    XPathExpression xPathExpression=xPath.compile("//namespace::*");
    NodeList nodeList=(NodeList)xPathExpression.evaluate(dox,XPathConstants.NODESET);
    for (int j=0; j < nodeList.getLength(); j++) {
      Node n=nodeList.item(j);
      if (n.getNodeName().equals("xmlns")) {
        assertEquals("http://owl.drools.org/conyard",n.getNodeValue());
      }
 else       if (n.getNodeName().equals("xmlns:xml")) {
        assertEquals("http://www.w3.org/XML/1998/namespace",n.getNodeValue());
      }
 else       if (n.getNodeName().equals("xmlns:xsi")) {
        assertEquals("http://www.w3.org/2001/XMLSchema-instance",n.getNodeValue());
      }
 else {
        fail("Unexpected namespace " + n.getNodeName() + " :: "+ n.getNodeValue());
      }
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
    fail(e.getMessage());
  }
}
 

Example 32

From project gda-common, under directory /uk.ac.gda.common/src/uk/ac/gda/util/schema/.

Source file: SchemaReader.java

  21 
vote

public List<String> getParents(String name) throws Exception {
  final String expression="*//xsd:element";
  final XPath xpath=factory.newXPath();
  xpath.setNamespaceContext(getXSDContext());
  final XPathExpression expr=xpath.compile(expression);
  final Object result=expr.evaluate(doc,XPathConstants.NODESET);
  if (result == null)   return null;
  final NodeList nodes=(NodeList)result;
  if (nodes.getLength() < 1)   return null;
  final List<String> items=new ArrayList<String>(nodes.getLength());
  for (int i=0; i < nodes.getLength(); i++) {
    final Node node=nodes.item(i);
    if (node.getAttributes().getNamedItem("name") != null && name.equals(node.getAttributes().getNamedItem("name").getNodeValue())) {
      try {
        final Node par=node.getParentNode().getParentNode().getParentNode();
        if (par.getAttributes().getNamedItem("name") == null)         continue;
        items.add(par.getAttributes().getNamedItem("name").getNodeValue());
      }
 catch (      Exception ne) {
        continue;
      }
    }
  }
  return items;
}
 

Example 33

From project interoperability-framework, under directory /interfaces/web/wsdl-client/src/main/java/eu/impact_project/wsclient/.

Source file: HtmlServiceProvider.java

  21 
vote

private NodeList applyXPath(Document doc,String xpathExpression,String namespace){
  XPathFactory factory=XPathFactory.newInstance();
  XPath xpath=factory.newXPath();
  if (namespace != NO_NAMESPACE)   xpath.setNamespaceContext(new WSDLNamespaceContext());
  XPathExpression expr;
  Object result=null;
  try {
    expr=xpath.compile(xpathExpression);
    result=expr.evaluate(doc,XPathConstants.NODESET);
  }
 catch (  XPathExpressionException e) {
    e.printStackTrace();
  }
  return (NodeList)result;
}
 

Example 34

From project jOOX, under directory /jOOX/src/main/java/org/joox/.

Source file: Impl.java

  21 
vote

@Override public final Impl xpath(String expression,Object... variables){
  List<Element> result=new ArrayList<Element>();
  try {
    XPathFactory factory=XPathFactory.newInstance();
    XPath xpath=factory.newXPath();
    Util.xalanExtensionAware(xpath);
    if (variables != null && variables.length != 0) {
      xpath.setXPathVariableResolver(new VariableResolver(expression,variables));
    }
    if (!namespaces.isEmpty() || expression.contains(":")) {
      xpath.setNamespaceContext(new ChainedContext(xpath.getNamespaceContext()));
    }
    XPathExpression exp=xpath.compile(expression);
    for (    Element element : get()) {
      for (      Element match : iterable((NodeList)exp.evaluate(element,XPathConstants.NODESET))) {
        result.add(match);
      }
    }
  }
 catch (  XPathExpressionException e) {
    throw new RuntimeException(e);
  }
  return new Impl(document,namespaces).addUniqueElements(result);
}
 

Example 35

From project lyo.testsuite, under directory /org.eclipse.lyo.testsuite.server/src/main/java/org/eclipse/lyo/testsuite/oslcv2/asset/.

Source file: UsageCaseXmlTests.java

  21 
vote

private Node getBestAsset(Document document) throws XPathExpressionException {
  String getAssets="/rdf:RDF/oslc_asset:Asset";
  XPath xPath=OSLCUtils.getXPath();
  XPathExpression assetsExpr=xPath.compile(getAssets);
  NodeList assets=(NodeList)assetsExpr.evaluate(document,XPathConstants.NODESET);
  Node bestAsset=null;
  String highestVersion="";
  for (int i=0; i < assets.getLength(); i++) {
    NodeList nodeKids=assets.item(i).getChildNodes();
    for (int j=0; j < nodeKids.getLength(); j++) {
      Node node=nodeKids.item(j);
      if (node.getNodeName().equals("oslc_asset:version")) {
        String version=node.getTextContent();
        if (version.compareTo(highestVersion) > 0) {
          highestVersion=version;
          bestAsset=assets.item(i);
        }
        break;
      }
    }
  }
  return bestAsset;
}
 

Example 36

From project maven-android-plugin, under directory /src/main/java/com/jayway/maven/plugins/android/standalonemojos/.

Source file: RunMojo.java

  21 
vote

/** 
 * Gets the first "Launcher" Activity by running an XPath query on <code>AndroidManifest.xml</code>.
 * @return A {@link LauncherInfo}
 * @throws MojoExecutionException
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 * @throws XPathExpressionException
 * @throws ActivityNotFoundException
 */
private LauncherInfo getLauncherActivity() throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, MojoFailureException {
  Document document;
  DocumentBuilder documentBuilder;
  DocumentBuilderFactory documentBuilderFactory;
  Object result;
  XPath xPath;
  XPathExpression xPathExpression;
  XPathFactory xPathFactory;
  documentBuilderFactory=DocumentBuilderFactory.newInstance();
  documentBuilder=documentBuilderFactory.newDocumentBuilder();
  document=documentBuilder.parse(androidManifestFile);
  xPathFactory=XPathFactory.newInstance();
  xPath=xPathFactory.newXPath();
  xPathExpression=xPath.compile("//manifest/application/activity/intent-filter[action[@name=\"android.intent.action.MAIN\"] " + "and category[@name=\"android.intent.category.LAUNCHER\"]]/..");
  result=xPathExpression.evaluate(document,XPathConstants.NODESET);
  if (result instanceof NodeList) {
    NodeList activities;
    activities=(NodeList)result;
    if (activities.getLength() > 0) {
      LauncherInfo launcherInfo;
      launcherInfo=new LauncherInfo();
      launcherInfo.activity=activities.item(0).getAttributes().getNamedItem("android:name").getNodeValue();
      launcherInfo.packageName=document.getDocumentElement().getAttribute("package").toString();
      return launcherInfo;
    }
 else {
      throw new MojoFailureException("Could not find a launcher activity in manifest");
    }
  }
 else {
    throw new MojoFailureException("Could not find any activity in manifest");
  }
}
 

Example 37

From project nuxeo-distribution, under directory /nuxeo-launcher/src/main/java/org/nuxeo/launcher/connect/.

Source file: ConnectBroker.java

  21 
vote

protected List<String> getDistributionFilenames(){
  File distributionMPFile=new File(distributionMPDir,PACKAGES_XML);
  List<String> md5Filenames=new ArrayList<String>();
  DocumentBuilderFactory docFactory=DocumentBuilderFactory.newInstance();
  docFactory.setNamespaceAware(true);
  try {
    DocumentBuilder builder=docFactory.newDocumentBuilder();
    Document doc=builder.parse(distributionMPFile);
    XPathFactory xpFactory=XPathFactory.newInstance();
    XPath xpath=xpFactory.newXPath();
    XPathExpression expr=xpath.compile("//package/@md5");
    NodeList nodes=(NodeList)expr.evaluate(doc,XPathConstants.NODESET);
    for (int i=0; i < nodes.getLength(); i++) {
      String md5=nodes.item(i).getNodeValue();
      if ((md5 != null) && (md5.length() > 0)) {
        md5Filenames.add(md5);
      }
    }
  }
 catch (  Exception e) {
    log.error("Failed parsing " + distributionMPFile,e);
    return new ArrayList<String>();
  }
  return md5Filenames;
}
 

Example 38

From project rest-driver, under directory /rest-server-driver/src/main/java/com/github/restdriver/serverdriver/.

Source file: Xml.java

  21 
vote

/** 
 * Extracts an XPath value from an XML element and returns the result as a string.
 * @param expression The XPath expression to use for extraction
 * @param element The element to use the XPath expression on
 * @return The result of evaluating the XPath expression on the element
 */
public static String extractXPathValue(String expression,Element element){
  XPath xPath=XPathFactory.newInstance().newXPath();
  XPathExpression compiledXPath;
  try {
    compiledXPath=xPath.compile(expression);
  }
 catch (  XPathExpressionException e) {
    throw new RuntimeException("Failed to compile XPath '" + expression + "'",e);
  }
  try {
    return compiledXPath.evaluate(element,XPathConstants.STRING).toString();
  }
 catch (  XPathExpressionException e) {
    throw new RuntimeException("Failed to evaluate XPath '" + expression + "'",e);
  }
}
 

Example 39

From project SanDisk-HQME-SDK, under directory /projects/HqmeService/project/src/com/hqme/cm/core/.

Source file: Policy.java

  21 
vote

public int getRelativePriority(){
  for (  Entry<String,RuleCollection> rc : mRuleCollections.entrySet()) {
    boolean usedInDownloadElement=false;
    String ruleName=rc.getValue().getName();
    String expression="//Rule[@name=\"" + ruleName + "\"]";
    String qt=Pattern.quote(expression);
    if (mDownload.matches(".*" + qt + ".*"))     usedInDownloadElement=true;
    String expression2="/Policy/Rule[@name=\"" + ruleName + "\"]";
    qt=Pattern.quote(expression2);
    if (mDownload.matches(".*" + qt + ".*"))     usedInDownloadElement=true;
    if (usedInDownloadElement) {
      XPathFactory factory=XPathFactory.newInstance();
      XPath xpath=factory.newXPath();
      XPathExpression expression1=null;
      String propertyExpressionString="/Policy/Rule[@name=\"" + ruleName + "\"][Property[@key=\"RULE_PRIORITY\"]]";
      try {
        expression1=xpath.compile(propertyExpressionString);
        InputSource is2=new InputSource(new StringReader(this.toString()));
        NodeList ruleNodes=(NodeList)expression1.evaluate(is2,XPathConstants.NODESET);
        if (ruleNodes.getLength() > 0) {
          for (          Rule rule : rc.getValue().getRules()) {
            if ("RULE_PRIORITY".equals(rule.getName())) {
              return Integer.parseInt(rule.getValue());
            }
          }
        }
      }
 catch (      XPathExpressionException e) {
        e.printStackTrace();
      }
    }
  }
  return -1;
}
 

Example 40

From project scoutdoc, under directory /main/src/scoutdoc/main/fetch/.

Source file: RssUtility.java

  21 
vote

public static List<Page> parseRss(String url,IPageFilter filter){
  List<Page> result=new ArrayList<Page>();
  DocumentBuilderFactory docFactory=DocumentBuilderFactory.newInstance();
  docFactory.setNamespaceAware(true);
  try {
    DocumentBuilder builder=docFactory.newDocumentBuilder();
    Document doc=builder.parse(url);
    XPathFactory factory=XPathFactory.newInstance();
    XPath xpath=factory.newXPath();
    XPathExpression expr=xpath.compile("//item/link");
    NodeList nodes=(NodeList)expr.evaluate(doc,XPathConstants.NODESET);
    for (int i=0; i < nodes.getLength(); i++) {
      Page page=convertToPage(nodes.item(i).getTextContent(),filter);
      if (page != null) {
        result.add(page);
      }
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return Collections.unmodifiableList(result);
}
 

Example 41

From project server-main, under directory /src/main/java/org/powertac/server/.

Source file: CompetitionSetupService.java

  21 
vote

/** 
 * Sets up the simulator, with config overrides provided in a file containing a sequence of PluginConfig instances. Errors are logged if one or more PluginConfig instances cannot be used in the current server setup.
 */
public boolean preGame(URL bootFile){
  log.info("preGame(File) - start");
  preGame();
  Competition bootstrapCompetition=null;
  XPathFactory factory=XPathFactory.newInstance();
  XPath xPath=factory.newXPath();
  try {
    XPathExpression exp=xPath.compile("/powertac-bootstrap-data/config/competition");
    NodeList nodes=(NodeList)exp.evaluate(new InputSource(bootFile.openStream()),XPathConstants.NODESET);
    String xml=nodeToString(nodes.item(0));
    bootstrapCompetition=(Competition)messageConverter.fromXML(xml);
  }
 catch (  XPathExpressionException xee) {
    log.error("preGame: Error reading boot dataset: " + xee.toString());
    System.out.println("preGame: Error reading boot dataset: " + xee.toString());
    return false;
  }
catch (  IOException ioe) {
    log.error("preGame: Error opening file " + bootFile + ": "+ ioe.toString());
    System.out.println("preGame: Error opening file " + bootFile + ": "+ ioe.toString());
    return false;
  }
  Competition.currentCompetition().update(bootstrapCompetition);
  return true;
}
 

Example 42

From project SIARD-Val, under directory /SIARD-Val/src/main/java/ch/kostceco/tools/siardval/validation/module/impl/.

Source file: ValidationJsurplusFilesModuleImpl.java

  21 
vote

private boolean validateSchema(File schema,XPath xPath,Document doc) throws XPathExpressionException {
  boolean valid=true;
  XPathExpression expression=xPath.compile("//siard:schema[siard:folder='" + schema.getName() + "']/siard:folder/text()");
  Node node=(Node)expression.evaluate(doc,XPathConstants.NODE);
  if (node == null) {
    valid=false;
    File content=new File(schema.getParent());
    if (schema.isFile()) {
      getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_J) + getTextResourceService().getText(MESSAGE_DASHES) + content.getName()+ " "+ getTextResourceService().getText(MESSAGE_MODULE_J_INVALID_FILE)+ " "+ schema.getName()+ ".");
    }
 else     if (schema.isDirectory()) {
      getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_J) + getTextResourceService().getText(MESSAGE_DASHES) + content.getName()+ " "+ getTextResourceService().getText(MESSAGE_MODULE_J_INVALID_FOLDER)+ " "+ schema.getName()+ ".");
    }
 else {
      getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_J) + getTextResourceService().getText(MESSAGE_DASHES) + content.getName()+ " "+ getTextResourceService().getText(MESSAGE_MODULE_J_INVALID_ENTRY)+ " "+ schema.getName()+ ".");
    }
  }
  if (valid) {
    File[] tables=schema.listFiles();
    for (    File table : tables) {
      valid=valid && validateTable(table,xPath,doc);
    }
  }
  return valid;
}
 

Example 43

From project Sparkweave, under directory /spark-handler/src/main/java/at/sti2/spark/handler/.

Source file: ImpactoriumHandler.java

  21 
vote

public String extractInfoObjectIdentifier(String infoObjectResponse){
  String reportId=null;
  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
  try {
    DocumentBuilder db=dbf.newDocumentBuilder();
    Document doc=db.parse(new ByteArrayInputStream(infoObjectResponse.getBytes("UTF-8")));
    XPathFactory factory=XPathFactory.newInstance();
    XPath xpath=factory.newXPath();
    XPathExpression expr=xpath.compile("//info-object");
    Object result=expr.evaluate(doc,XPathConstants.NODESET);
    NodeList nodes=(NodeList)result;
    NamedNodeMap attributesMap=nodes.item(0).getAttributes();
    Node idAttribute=attributesMap.getNamedItem("id");
    reportId=idAttribute.getNodeValue();
  }
 catch (  ParserConfigurationException e) {
    e.printStackTrace();
  }
catch (  SAXException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
catch (  XPathExpressionException e) {
    e.printStackTrace();
  }
  return reportId;
}
 

Example 44

From project starflow, under directory /src/main/java/com/googlecode/starflow/engine/core/expression/xpath/.

Source file: XPathBuilder.java

  21 
vote

/** 
 * Evaluates the expression as the given result type
 */
protected String evaluateAs(String xml){
  XPathExpression xpathExpression=pool.poll();
  if (xpathExpression == null) {
    logger.trace("Creating new XPathExpression as none was available from pool");
    try {
      xpathExpression=createXPathExpression();
    }
 catch (    XPathExpressionException e) {
      e.printStackTrace();
      throw new InvalidXPathExpression(getText(),e);
    }
catch (    Exception e) {
      throw new InvalidXPathExpression("Cannot create xpath expression",e);
    }
  }
 else {
    logger.trace("Acquired XPathExpression from pool");
  }
  try {
    return doInEvaluateAs(xpathExpression,xml);
  }
  finally {
    pool.add(xpathExpression);
    logger.trace("Released XPathExpression back to pool");
  }
}
 

Example 45

From project streetlights, under directory /streetlights-client-android/simple-xml-2.6.3/test/src/org/simpleframework/xml/core/.

Source file: XPathTest.java

  21 
vote

public void testXPath() throws Exception {
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  DocumentBuilder builder=factory.newDocumentBuilder();
  byte[] source=SOURCE.getBytes("UTF-8");
  InputStream stream=new ByteArrayInputStream(source);
  Document doc=builder.parse(stream);
  XPathFactory xpathFactory=XPathFactory.newInstance();
  XPath xpath=xpathFactory.newXPath();
  XPathExpression expr=xpath.compile("inventory/book[1]/@year");
  Object result=expr.evaluate(doc,XPathConstants.NODESET);
  NodeList nodes=(NodeList)result;
  for (int i=0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getNodeValue());
  }
}
 

Example 46

From project eclim, under directory /org.eclim.core/java/org/eclim/plugin/core/util/.

Source file: XmlUtils.java

  19 
vote

/** 
 * Create an XPathExpression from the supplied xpath string.
 * @param xpath The xpath string.
 * @return An XPathExpression.
 */
public static XPathExpression createXPathExpression(String xpath) throws Exception {
  if (XPATH == null) {
    XPATH=XPathFactory.newInstance().newXPath();
  }
  return XPATH.compile(xpath);
}
 

Example 47

From project jboss-jstl-api_spec, under directory /src/main/java/org/apache/taglibs/standard/tag/common/xml/.

Source file: JSTLXPathImpl.java

  19 
vote

/** 
 * <p>Compile an XPath expression for later evaluation.</p> <p>If <code>expression</code> contains any  {@link javax.xml.xpath.XPathFunction}s, they must be available via the  {@link XPathFunctionResolver}. An  {@link XPathExpressionException} will be thrown if the <code>XPathFunction</code>cannot be resovled with the <code>XPathFunctionResolver</code>.</p> <p>If <code>expression</code> is <code>null</code>, a <code>NullPointerException</code> is thrown.</p>
 * @param expression The XPath expression.
 * @return Compiled XPath expression.
 * @throws XPathExpressionException If <code>expression</code> cannot be compiled.
 * @throws NullPointerException If <code>expression</code> is <code>null</code>.
 */
public XPathExpression compile(String expression) throws XPathExpressionException {
  if (expression == null) {
    String fmsg=XSLMessages.createXPATHMessage(XPATHErrorResources.ER_ARG_CANNOT_BE_NULL,new Object[]{"XPath expression"});
    throw new NullPointerException(fmsg);
  }
  return null;
}
 

Example 48

From project pdfmark, under directory /src/org/crossref/pdfmark/.

Source file: XPathHelpers.java

  19 
vote

public static String evalConcat(Node n,String delimiter,XPathExpression... exprs) throws XPathExpressionException {
  ArrayList<String> results=new ArrayList<String>();
  for (  XPathExpression expr : exprs) {
    results.add(orEmptyStr(expr,n));
  }
  while (results.remove(""))   ;
  String retn="";
  for (  String s : results) {
    retn+=s;
    if (results.indexOf(s) != results.size() - 1) {
      retn+=delimiter;
    }
  }
  return retn;
}
 

Example 49

From project skmclauncher, under directory /src/main/java/com/sk89q/mclauncher/util/.

Source file: XMLUtil.java

  19 
vote

/** 
 * Get a string from an XPath expression.
 * @param node node
 * @param expr XPath expression
 * @return string, or null if empty or not defined
 * @throws XPathExpressionException 
 */
public static String getStringOrNull(Node node,XPathExpression expr) throws XPathExpressionException {
  String s=getString(node,expr);
  if (s.trim().length() == 0) {
    return null;
  }
  return s;
}
 

Example 50

From project spring-migration-analyzer, under directory /contributions/src/main/java/org/springframework/migrationanalyzer/contributions/xml/.

Source file: StandardXmlArtifactAnalyzer.java

  19 
vote

private XPathExpression getXPathExpression(String expressionString) throws XPathExpressionException {
  XPathFactory newInstance=XPathFactory.newInstance();
  XPath xpath=newInstance.newXPath();
  if (this.namespaceContext != null) {
    xpath.setNamespaceContext(this.namespaceContext);
  }
  return xpath.compile(expressionString);
}
 

Example 51

From project spring-test-mvc, under directory /src/main/java/org/springframework/test/web/support/.

Source file: XpathExpectationsHelper.java

  19 
vote

private XPathExpression compileXpathExpression(String expression,Map<String,String> namespaces) throws XPathExpressionException {
  SimpleNamespaceContext namespaceContext=new SimpleNamespaceContext();
  namespaceContext.setBindings((namespaces != null) ? namespaces : Collections.<String,String>emptyMap());
  XPath xpath=XPathFactory.newInstance().newXPath();
  xpath.setNamespaceContext(namespaceContext);
  return xpath.compile(expression);
}