Java Code Examples for javax.xml.xpath.XPathFactory

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 adt-maven-plugin, under directory /src/test/java/com/yelbota/plugins/adt/model/.

Source file: ApplicationDescriptorModelTest.java

  18 
vote

private void testDom(Document doc,ApplicationDescriptorModel c) throws XPathExpressionException {
  XPathFactory factory=XPathFactory.newInstance();
  XPath xpath=factory.newXPath();
  Assert.assertEquals(xpath.compile("//versionLabel/text()").evaluate(doc),c.getVersionLabel(),"versionLabel should be " + c.getVersionLabel());
  Assert.assertEquals(xpath.compile("//versionNumber/text()").evaluate(doc),c.getVersionNumber(),"versionNumber should be " + c.getVersionNumber());
  Assert.assertEquals(xpath.compile("//initialWindow/content/text()").evaluate(doc),c.getContent(),"content should be " + c.getContent());
  testDomExtensions(doc,c);
}
 

Example 2

From project as3-commons-jasblocks, under directory /src/main/java/org/as3commons/asblocks/impl/.

Source file: SWCResourceRoot.java

  18 
vote

private List<ASQName> readCatalog(InputStream in) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
  Document doc=loadDoc(in);
  XPathFactory fact=XPathFactory.newInstance();
  XPath xpath=fact.newXPath();
  NodeList list=(NodeList)xpath.evaluate("/swc/libraries/library/script/def",doc,XPathConstants.NODESET);
  List<ASQName> result=new ArrayList<ASQName>();
  for (int i=0; i < list.getLength(); i++) {
    Element def=(Element)list.item(i);
    String defined=def.getAttribute("id");
    result.add(toQName(defined));
  }
  return result;
}
 

Example 3

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

Source file: XPathOperation.java

  18 
vote

/** 
 * Method getXPath returns the XPath of this XPathOperation object.
 * @return the XPath (type XPath) of this XPathOperation object.
 */
public XPath getXPath(){
  if (xPath != null)   return xPath;
  XPathFactory factory=XPathFactory.newInstance();
  xPath=factory.newXPath();
  if (namespaces != null) {
    MutableNamespaceContext namespaceContext=new MutableNamespaceContext();
    for (    String[] namespace : namespaces) {
      if (LOG.isDebugEnabled())       LOG.debug("adding namespace: {}:{}",namespace[0],namespace[1]);
      namespaceContext.addNamespace(namespace[0],namespace[1]);
    }
    xPath.setNamespaceContext(namespaceContext);
  }
  return xPath;
}
 

Example 4

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

Source file: XMLUtils.java

  18 
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 EasySOA, under directory /easysoa-proxy/easysoa-proxy-core/easysoa-proxy-core-api/src/main/java/org/easysoa/proxy/core/api/records/assertions/.

Source file: AbstractAssertion.java

  18 
vote

/** 
 * Search and returns the value corresponding to the specified field in a XML document
 * @param referenceField The field name
 * @param doc The XML document where the field will be searched
 * @return The field value
 */
public String findXMLFieldValue(String referenceField,Document doc) throws Exception {
  XPathFactory xpathFactory=XPathFactory.newInstance();
  XPath xpath=xpathFactory.newXPath();
  String expression="//" + referenceField + "/descendant::*";
  Node node=(Node)xpath.evaluate(expression,doc,XPathConstants.NODE);
  return nodeToString(node);
}
 

Example 6

From project fedora-client, under directory /fedora-client-core/src/main/java/com/yourmediashelf/fedora/client/response/.

Source file: FedoraResponseImpl.java

  18 
vote

protected XPath getXPath(){
  XPathFactory factory=XPathFactory.newInstance();
  XPath xpath=factory.newXPath();
  xpath.setNamespaceContext(nsCtx);
  return xpath;
}
 

Example 7

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

Source file: ProjectConfiguration.java

  18 
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 8

From project jboss-modules, under directory /src/test/java/org/jboss/modules/.

Source file: JAXPModuleTest.java

  18 
vote

public void checkXPath(Class<?> clazz,boolean fake) throws Exception {
  XPath parser=invokeMethod(clazz.newInstance(),"xpath");
  XPathFactory factory=invokeMethod(clazz.newInstance(),"xpathFactory");
  Assert.assertEquals(__XPathFactory.class.getName(),factory.getClass().getName());
  if (fake) {
    Assert.assertEquals(FakeXPath.class.getName(),parser.getClass().getName());
  }
 else {
    Assert.assertSame(XPathFactory.newInstance().newXPath().getClass(),parser.getClass());
  }
}
 

Example 9

From project litle-sdk-for-java, under directory /lib/jaxb/samples/updateablePartialBind/src/.

Source file: UpdateablePartialBinding.java

  18 
vote

static List<Node> xpath(Document document,String xpathExpression){
  XPathFactory xpf=XPathFactory.newInstance();
  XPath xpath=xpf.newXPath();
  try {
    List<Node> result=new ArrayList<Node>();
    NodeList nl=(NodeList)xpath.evaluate(xpathExpression,document,XPathConstants.NODESET);
    for (int i=0; i < nl.getLength(); i++)     result.add(nl.item(i));
    return result;
  }
 catch (  XPathExpressionException e) {
    e.printStackTrace();
    return Collections.emptyList();
  }
}
 

Example 10

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

Source file: OSLCUtils.java

  18 
vote

public static XPath getXPath(){
  XPathFactory factory=XPathFactory.newInstance();
  XPath xpath=factory.newXPath();
  xpath.setNamespaceContext(new OSLCNamespaceContext());
  return xpath;
}
 

Example 11

From project m2e-connectors, under directory /jaxb2-m2e-connector/org.bitstrings.eclipse.m2e.connectors.jaxb2.tests/src/org/bitstrings/eclipse/m2e/connectors/jaxb2/codehaus/.

Source file: Jaxb2SchemagenTest.java

  18 
vote

public void testSchemagenIncludes1() throws Exception {
  IProject project=schemagenCommon("includes-1");
  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
  dbf.setNamespaceAware(false);
  Document doc=dbf.newDocumentBuilder().parse(project.getFile("target/generated-resources/schemagen/schema1.xsd").getLocation().toFile());
  XPathFactory xpathFactory=XPathFactory.newInstance();
  XPath xpath=xpathFactory.newXPath();
  NodeList nodeList=((NodeList)xpath.evaluate("/schema//complexType[@name='bean2']",doc,XPathConstants.NODESET));
  assertEquals(nodeList.getLength(),1);
  nodeList=((NodeList)xpath.evaluate("/schema//complexType[@name='bean']",doc,XPathConstants.NODESET));
  assertEquals(nodeList.getLength(),0);
}
 

Example 12

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

Source file: FedoraAccessImpl.java

  18 
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 13

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

Source file: NEDDownloader.java

  18 
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 14

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

Source file: Tools.java

  18 
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 15

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

Source file: Tools.java

  18 
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 16

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

Source file: StandardXmlArtifactAnalyzer.java

  18 
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 17

From project thymeleaf, under directory /src/test/java/org/thymeleaf/.

Source file: AbstractDocumentProcessingTest.java

  18 
vote

@Override protected void setUp() throws Exception {
  super.setUp();
  this.templateEngine=new TemplateEngine();
  TemplateResolver templateResolver=new ClassLoaderTemplateResolver();
  templateResolver.setSuffix(".html");
  this.templateEngine.setTemplateResolver(templateResolver);
  this.templateEngine.initialize();
  this.context=new Context();
  XPathFactory xPathFactory=XPathFactory.newInstance();
  this.xPath=xPathFactory.newXPath();
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  this.docBuilder=factory.newDocumentBuilder();
  this.docBuilder.setEntityResolver(new EntityResolver(templateEngine.getConfiguration()));
}
 

Example 18

From project Weave, under directory /WeaveServices/src/weave/config/.

Source file: SQLConfigXML.java

  18 
vote

public SQLConfigXML() throws ParserConfigurationException, SAXException, IOException {
  fileName=null;
  lastModifiedTime=0L;
  doc=XMLUtils.getXMLFromString("<sqlConfig/>");
  XPathFactory factory=XPathFactory.newInstance();
  xpath=factory.newXPath();
}
 

Example 19

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

Source file: ConvertDiabetesDatasetUtil.java

  17 
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 20

From project build-info, under directory /build-info-extractor-maven3/src/main/java/org/jfrog/build/extractor/maven/.

Source file: BuildInfoRecorder.java

  17 
vote

private boolean isTestsFailed(List<File> surefireReports){
  XPathFactory factory=XPathFactory.newInstance();
  XPath path=factory.newXPath();
  for (  File report : surefireReports) {
    FileInputStream stream=null;
    try {
      stream=new FileInputStream(report);
      Object evaluate=path.evaluate("/testsuite/@failures",new InputSource(stream),XPathConstants.STRING);
      if (evaluate != null && StringUtils.isNotBlank(evaluate.toString()) && StringUtils.isNumeric(evaluate.toString())) {
        int testsFailed=Integer.parseInt(evaluate.toString());
        return testsFailed != 0;
      }
    }
 catch (    FileNotFoundException e) {
      logger.error("File '" + report.getAbsolutePath() + "' does not exist.");
    }
catch (    XPathExpressionException e) {
      logger.error("Expression /testsuite/@failures is invalid.");
    }
 finally {
      Closeables.closeQuietly(stream);
    }
  }
  return false;
}
 

Example 21

From project cloudbees-api-client, under directory /cloudbees-api-client/src/main/java/com/cloudbees/utils/.

Source file: AppConfigParser.java

  17 
vote

public void load(ApplicationConfiguration applicationConfiguration,Document doc,String[] environments,String[] implicitEnvironments){
  XPathFactory factory=XPathFactory.newInstance();
  XPath xpath=factory.newXPath();
  try {
    Element e=doc.getDocumentElement();
    applyToAppConfig(applicationConfiguration,xpath,e);
    applicationConfiguration.setDefaultEnvironment(e.getAttribute("default"));
    if (environments == null || environments.length == 0) {
      environments=getEnvironmentList(applicationConfiguration.getDefaultEnvironment(),implicitEnvironments);
    }
 else {
      environments=getEnvironmentList(join(environments,","),implicitEnvironments);
    }
    NodeList nodes=(NodeList)xpath.evaluate("environment",e,XPathConstants.NODESET);
    Map<String,Node> envNodes=new HashMap<String,Node>();
    for (int i=0; i < nodes.getLength(); i++) {
      Node n=nodes.item(i);
      String envName=getAttribute(n,"name",null);
      if (envName == null)       throw new IllegalArgumentException("missing required attribute (name) on environment element");
      envNodes.put(envName,n);
    }
    if (environments != null) {
      for (      String env : environments) {
        Node n=envNodes.get(env);
        if (n != null) {
          applyToAppConfig(applicationConfiguration,xpath,n);
          applicationConfiguration.getAppliedEnvironments().add(env);
        }
      }
    }
  }
 catch (  XPathExpressionException e) {
    e.printStackTrace();
  }
}
 

Example 22

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

Source file: OperationSelector.java

  17 
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 23

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

Source file: FactTest.java

  17 
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 24

From project gxa, under directory /atlas-index-api/src/main/java/uk/ac/ebi/gxa/index/.

Source file: SolrContainerFactory.java

  17 
vote

private List<String> getCorePaths() throws IOException {
  List<String> result=new ArrayList<String>();
  try {
    javax.xml.parsers.DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc=builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(getTemplatePath() + "/solr.xml"));
    XPathFactory xpathFactory=XPathFactory.newInstance();
    XPath xpath=xpathFactory.newXPath();
    NodeList cores=(NodeList)xpath.evaluate("//cores/core",doc,XPathConstants.NODESET);
    for (int i=0; i < cores.getLength(); ++i) {
      Node node=cores.item(i);
      String path=node.getAttributes().getNamedItem("instanceDir").getTextContent();
      result.add(path);
    }
  }
 catch (  ParserConfigurationException e) {
    log.error(e.getMessage(),e);
  }
catch (  SAXException e) {
    log.error(e.getMessage(),e);
  }
catch (  XPathExpressionException e) {
    log.error(e.getMessage(),e);
  }
  return result;
}
 

Example 25

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

Source file: HtmlServiceProvider.java

  17 
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 26

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

Source file: Impl.java

  17 
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 27

From project Kairos, under directory /src/java/org/apache/nutch/kairos/crf/.

Source file: AnnotationTool.java

  17 
vote

/** 
 * Extract the HTML segments from a DOM document
 * @param doc
 * @return the HTML segments from the DOM document
 */
public static LinkedList<Segment> createSegmentsFromDOMDocument(Document doc){
  XPathFactory xPathFactory=XPathFactory.newInstance();
  XPath xPath=xPathFactory.newXPath();
  String[] htmlSegments=new String[]{"//tr[not(descendant::tr)]","//p[not(descendant::p)]","//li[not(descendant::li)]"};
  for (int x=0; x < htmlSegments.length; x++) {
    String currentHtmlSegment=htmlSegments[x];
    try {
      NodeList nodeList=(NodeList)xPath.evaluate(currentHtmlSegment,doc,XPathConstants.NODESET);
      for (int i=0; i < nodeList.getLength(); i++) {
        Node node=nodeList.item(i);
        Segment segment=new Segment();
        parseDOMTree(node,segment,"");
        _segmentList.add(segment);
      }
    }
 catch (    XPathExpressionException e) {
      e.printStackTrace();
      e.printStackTrace(LogUtil.getErrorStream(LOG));
      return null;
    }
  }
  return _segmentList;
}
 

Example 28

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

Source file: RunMojo.java

  17 
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 29

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

Source file: ConnectBroker.java

  17 
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 30

From project ODE-X, under directory /bpel/src/test/java/org/apache/ode/bpel/tests/.

Source file: CompilerTest.java

  17 
vote

@Test public void testCompileHelloWorld() throws Exception {
  repo.importArtifact(new ArtifactId("{http://ode/bpel/unit-test.wsdl}HelloService",null,null),"HelloWorld.wsdl",true,true,readStream(Thread.currentThread().getContextClassLoader().getResourceAsStream("HelloWorld/HelloWorld.wsdl")));
  repo.importArtifact(new ArtifactId("{http://ode/bpel/unit-test}HelloWorld",null,null),"HelloWorld.bpel",true,true,readStream(Thread.currentThread().getContextClassLoader().getResourceAsStream("HelloWorld/HelloWorld.bpel")));
  buildSystem.build(readStream(Thread.currentThread().getContextClassLoader().getResourceAsStream("HelloWorld/HelloWorld.build")));
  byte[] content=repo.exportArtifact(new ArtifactId("{http://ode/bpel/unit-test}HelloWorld","application/ode-executable","1.0"));
  assertNotNull(content);
  System.out.println(new String(content));
  Document doc=ParserUtils.contentToDom(content);
  XPathFactory xpFactory=XPathFactory.newInstance();
  XPath xPath=xpFactory.newXPath();
  Map<String,String> ns=new HashMap<String,String>();
  ns.put("e",Platform.EXEC_NAMESPACE);
  ns.put("b",BPELComponent.BPEL_INSTRUCTION_SET_NS);
  NamespaceContext ctx=ParserUtils.buildNSContext(ns);
  xPath.setNamespaceContext(ctx);
  assertNotNull(xPath.evaluate("/e:executable/e:block[1]/b:process[1]",doc,XPathConstants.NODE));
  assertNotNull(xPath.evaluate("/e:executable/e:block[1]/b:process[2]",doc,XPathConstants.NODE));
}
 

Example 31

From project remitt, under directory /src/main/java/org/remitt/plugin/translation/.

Source file: FixedFormXml.java

  17 
vote

@Override public byte[] render(Integer jobId,byte[] input,String option) throws Exception {
  log.info("Entered Translate for job #" + jobId.toString());
  StringBuilder sb=new StringBuilder();
  DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
  DocumentBuilder builder=dbFactory.newDocumentBuilder();
  log.debug("Loading input into XmlDocument");
  ByteArrayInputStream inputStream=new ByteArrayInputStream(input);
  org.w3c.dom.Document xmlInput=builder.parse(inputStream);
  XPathFactory xpFactory=XPathFactory.newInstance();
  xpath=xpFactory.newXPath();
  Node root=xmlInput.getDocumentElement();
  NodeList nodeList=(NodeList)xpath.evaluate("/fixedform/page",root,XPathConstants.NODESET);
  for (int iter=0; iter < nodeList.getLength(); iter++) {
    sb.append(TranslatePageFromNode(nodeList.item(iter)));
  }
  log.info("Leaving Translate for job #" + jobId.toString());
  return sb.toString().getBytes();
}
 

Example 32

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

Source file: WsdlDeriver.java

  17 
vote

/** 
 * @see org.overlord.sramp.repository.derived.ArtifactDeriver#derive(org.s_ramp.xmlns._2010.s_ramp.BaseArtifactType,java.io.InputStream)
 */
@Override public Collection<DerivedArtifactType> derive(BaseArtifactType artifact,InputStream content) throws IOException {
  IndexedArtifactCollection derivedArtifacts=new IndexedArtifactCollection();
  try {
    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(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=factory.newDocumentBuilder();
    Document document=builder.parse(content);
    XPathFactory xPathfactory=XPathFactory.newInstance();
    XPath xpath=xPathfactory.newXPath();
    StaticNamespaceContext nsCtx=new StaticNamespaceContext();
    nsCtx.addMapping("xs","http://www.w3.org/2001/XMLSchema");
    nsCtx.addMapping("xsd","http://www.w3.org/2001/XMLSchema");
    nsCtx.addMapping("wsdl","http://schemas.xmlsoap.org/wsdl/");
    xpath.setNamespaceContext(nsCtx);
    Element definitionsElem=document.getDocumentElement();
    processDefinitions(derivedArtifacts,artifact,definitionsElem,xpath);
    for (    DerivedArtifactType derivedArtifact : derivedArtifacts) {
      if (derivedArtifact.getRelatedDocument() == null) {
        DocumentArtifactTarget related=new DocumentArtifactTarget();
        related.setValue(artifact.getUuid());
        related.setArtifactType(DocumentArtifactEnum.fromValue(artifact.getArtifactType()));
        derivedArtifact.setRelatedDocument(related);
      }
    }
  }
 catch (  Exception e) {
    throw new IOException(e);
  }
  return derivedArtifacts;
}
 

Example 33

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

Source file: Policy.java

  17 
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 34

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

Source file: RssUtility.java

  17 
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 35

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

Source file: CompetitionSetupService.java

  17 
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 36

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

Source file: ValidationJsurplusFilesModuleImpl.java

  17 
vote

@Override public boolean validate(File siardDatei) throws ValidationJsurplusFilesException {
  boolean valid=true;
  try {
    String pathToWorkDir=getConfigurationService().getPathToWorkDir();
    File metadataXml=new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header").append(File.separator).append("metadata.xml").toString());
    InputStream fin=new FileInputStream(metadataXml);
    InputSource source=new InputSource(fin);
    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder=factory.newDocumentBuilder();
    Document doc=builder.parse(source);
    fin.close();
    XPathFactory xPathFactory=XPathFactory.newInstance();
    XPath xPath=xPathFactory.newXPath();
    xPath.setNamespaceContext(new SiardNamespaceContext());
    File content=new File(new StringBuilder(pathToWorkDir).append(File.separator).append("content").toString());
    File[] schemas=content.listFiles();
    for (    File schema : schemas) {
      valid=valid && validateSchema(schema,xPath,doc);
    }
  }
 catch (  java.io.IOException e) {
    valid=false;
    getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_D) + getTextResourceService().getText(MESSAGE_DASHES) + "IOException "+ e.getMessage());
  }
catch (  XPathExpressionException e) {
    valid=false;
    getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_D) + getTextResourceService().getText(MESSAGE_DASHES) + "XPathExpressionException "+ e.getMessage());
  }
catch (  ParserConfigurationException e) {
    valid=false;
    getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_D) + getTextResourceService().getText(MESSAGE_DASHES) + "ParserConfigurationException "+ e.getMessage());
  }
catch (  SAXException e) {
    valid=false;
    getMessageService().logError(getTextResourceService().getText(MESSAGE_MODULE_D) + getTextResourceService().getText(MESSAGE_DASHES) + "SAXException "+ e.getMessage());
  }
  return valid;
}
 

Example 37

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

Source file: AlchemyAPISimple.java

  17 
vote

private Document doRequest(HttpURLConnection handle,String outputMode) throws IOException, SAXException, ParserConfigurationException, XPathExpressionException {
  DataInputStream istream=new DataInputStream(handle.getInputStream());
  Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(istream);
  istream.close();
  handle.disconnect();
  XPathFactory factory=XPathFactory.newInstance();
  if (AlchemyAPIParams.OUTPUT_XML.equals(outputMode)) {
    String statusStr=getNodeValue(factory,doc,"/results/status/text()");
    if (null == statusStr || !statusStr.equals("OK")) {
      String statusInfoStr=getNodeValue(factory,doc,"/results/statusInfo/text()");
      if (null != statusInfoStr && statusInfoStr.length() > 0) {
        return null;
      }
      throw new IOException("Error making API call: " + statusStr + '.');
    }
  }
 else   if (AlchemyAPIParams.OUTPUT_RDF.equals(outputMode)) {
    String statusStr=getNodeValue(factory,doc,"//RDF/Description/ResultStatus/text()");
    if (null == statusStr || !statusStr.equals("OK")) {
      String statusInfoStr=getNodeValue(factory,doc,"//RDF/Description/ResultStatus/text()");
      if (null != statusInfoStr && statusInfoStr.length() > 0)       throw new IOException("Error making API call: " + statusInfoStr + '.');
      throw new IOException("Error making API call: " + statusStr + '.');
    }
  }
  return doc;
}
 

Example 38

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

Source file: ImpactoriumHandler.java

  17 
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 39

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

Source file: XPathTest.java

  17 
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 40

From project syncany, under directory /syncany/src/org/syncany/config/.

Source file: ConfigNode.java

  17 
vote

public final List<ConfigNode> findChildrenByXpath(String xpathExpr){
  try {
    XPathFactory factory=XPathFactory.newInstance();
    XPath xpath=factory.newXPath();
    Object result=xpath.evaluate(xpathExpr,node,XPathConstants.NODESET);
    NodeList nodes=(NodeList)result;
    List<ConfigNode> nodeList=new ArrayList<ConfigNode>();
    for (int i=0; i < nodes.getLength(); i++) {
      nodeList.add(new ConfigNode(nodes.item(i)));
    }
    return nodeList;
  }
 catch (  XPathExpressionException ex) {
    Logger.getLogger(ConfigNode.class.getName()).log(Level.SEVERE,null,ex);
    return null;
  }
}
 

Example 41

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

  15 
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 42

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

Source file: AssertXPath.java

  15 
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 43

From project arquillian_deprecated, under directory /containers/glassfish-remote-3.1/src/main/java/org/jboss/arquillian/container/glassfish/remote_3_1/.

Source file: GlassFishRestDeployableContainer.java

  15 
vote

private ProtocolMetaData parseForProtocolMetaData(String xmlResponse) throws XPathExpressionException {
  final ProtocolMetaData protocolMetaData=new ProtocolMetaData();
  final HTTPContext httpContext=new HTTPContext(this.configuration.getRemoteServerAddress(),this.configuration.getRemoteServerHttpPort());
  final XPath xpath=XPathFactory.newInstance().newXPath();
  NodeList servlets=(NodeList)xpath.evaluate("/map/entry[@key = 'properties']/map/entry[@value = 'Servlet']",new InputSource(new StringReader(xmlResponse)),XPathConstants.NODESET);
  for (int i=0; i < servlets.getLength(); i++) {
    httpContext.add(new Servlet(servlets.item(i).getAttributes().getNamedItem("key").getNodeValue(),this.deploymentName));
  }
  protocolMetaData.addContext(httpContext);
  return protocolMetaData;
}
 

Example 44

From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/org/openscience/cdk/structgen/pubchem/.

Source file: PubchemStructureGenerator.java

  15 
vote

/** 
 * @throws Exception 
 * @since JAVA5
 */
private static Node xpathJDK5(String pathString,Document doc) throws Exception {
  XPath xpath=XPathFactory.newInstance().newXPath();
  try {
    Node node=((Node)xpath.evaluate(pathString,doc,XPathConstants.NODE));
    return node;
  }
 catch (  DOMException e) {
    throw new Exception(e.toString());
  }
catch (  XPathExpressionException e) {
    throw new Exception(e.toString());
  }
}
 

Example 45

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

Source file: XmlElements.java

  15 
vote

XPathExpression makeXPathExpression(String xpathExpression) throws XPathExpressionException {
  XPathExpression nodesXPath=pathCache.get().get(xpathExpression);
  if (nodesXPath == null) {
    XPath xpath=XPathFactory.newInstance().newXPath();
    nodesXPath=xpath.compile(xpathExpression);
    pathCache.get().put(xpathExpression,nodesXPath);
  }
  return nodesXPath;
}
 

Example 46

From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/model/test/data/.

Source file: DataCopyOperation.java

  15 
vote

public void retrieveTextNodes(Element literalData,NamespaceContext namespaceContext){
  XPath xpath=XPathFactory.newInstance().newXPath();
  xpath.setNamespaceContext(namespaceContext);
  try {
    Node inputNode;
    inputNode=(Node)xpath.evaluate(getFromXPath(),literalData,XPathConstants.NODE);
    if (inputNode != null) {
      Node inputTextNode=null;
      NodeList children=inputNode.getChildNodes();
      for (int i=0; i < children.getLength(); i++) {
        Node node=children.item(i);
        if (node.getNodeType() == Node.TEXT_NODE) {
          inputTextNode=node;
        }
      }
      if (inputTextNode == null) {
        fStatus=ArtefactStatus.createErrorStatus("Could not find a text node underneath node " + inputNode.getLocalName());
      }
 else {
        fStatus=ArtefactStatus.createInProgressStatus();
        setCopiedValue(inputTextNode.getNodeValue());
      }
    }
 else {
      fStatus=ArtefactStatus.createErrorStatus("XPath expression did not yield a result node.");
    }
  }
 catch (  Exception e) {
    Throwable root=BPELUnitUtil.findRootThrowable(e);
    fStatus=ArtefactStatus.createErrorStatus("XPath Expression Exception when evaluating XPath: " + root.getMessage());
  }
}
 

Example 47

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

Source file: XmlSplitter.java

  15 
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 48

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

Source file: XmlAssert.java

  15 
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 49

From project dev-examples, under directory /template/src/main/java/org/richfaces/example/.

Source file: XMLBody.java

  15 
vote

public NodeList getByXpath(String xpath) throws ParsingException {
  XPath path=XPathFactory.newInstance().newXPath();
  NodeList childNodes;
  try {
    childNodes=(NodeList)path.evaluate(xpath,xmlDocument,XPathConstants.NODESET);
  }
 catch (  XPathExpressionException e) {
    throw new ParsingException("Error evaluate xpath",e);
  }
  return childNodes;
}
 

Example 50

From project drools-mas, under directory /drools-mas-util/src/main/java/org/drools/mas/util/.

Source file: InspectMessageHelper.java

  15 
vote

public static String inspect(ACLMessage message,String path) throws ParseException, XPathExpressionException, ParserConfigurationException, IOException, SAXException {
  AbstractMessageContent content=inspectContent(message);
  if (content.getEncodedContent() != null || !content.getEncodedContent().equals("")) {
switch (message.getEncoding()) {
case JSON:
      Object res=JsonPath.read(content.getEncodedContent(),path);
    return (res != null) ? res.toString() : null;
case XML:
  XPath accessor=XPathFactory.newInstance().newXPath();
InputStream inStream=new ByteArrayInputStream(content.getEncodedContent().getBytes());
Document dox=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inStream);
return (String)accessor.evaluate(path,dox,XPathConstants.STRING);
default :
throw new ParseException("Unable to access byte-encoded message body",0);
}
}
return null;
}
 

Example 51

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

Source file: XmlUtils.java

  15 
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 52

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

Source file: WizardHelpers.java

  15 
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 53

From project eucalyptus, under directory /clc/modules/core/src/edu/ucsb/eucalyptus/util/.

Source file: XMLParser.java

  15 
vote

public XMLParser(){
  xpath=XPathFactory.newInstance().newXPath();
  docFactory=DocumentBuilderFactory.newInstance();
  try {
    docBuilder=docFactory.newDocumentBuilder();
  }
 catch (  ParserConfigurationException ex) {
    ex.printStackTrace();
  }
}
 

Example 54

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

Source file: SchemaReader.java

  15 
vote

/** 
 * Class reads the schema and returns properties contained in it. Specially set up for Castor schemas in xsd namespace.
 * @param schemaUrl
 * @throws Exception
 */
public SchemaReader(final URL schemaUrl) throws Exception {
  DocumentBuilderFactory docBuilder=DocumentBuilderFactory.newInstance();
  docBuilder.setNamespaceAware(true);
  DocumentBuilder builder=docBuilder.newDocumentBuilder();
  this.doc=builder.parse(schemaUrl.openConnection().getInputStream());
  this.factory=XPathFactory.newInstance();
}
 

Example 55

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

Source file: MigrateH1to3Tool.java

  15 
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 56

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

Source file: Mesh3dToSoupConvert.java

  15 
vote

public static void convert(String meshDirectory) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
  XPath xpath=XPathFactory.newInstance().newXPath();
  File xmlFile3d=new File(meshDirectory,JCAEXMLData.xml3dFilename);
  Document document=XMLHelper.parseXML(xmlFile3d);
  String formatVersion=xpath.evaluate("/jcae/@version",document);
  if (formatVersion != null && formatVersion.length() > 0)   throw new RuntimeException("File " + xmlFile3d + " has been written by a newer version of jCAE and cannot be re-read");
  String fnodes=(String)xpath.evaluate("/jcae/mesh/submesh/nodes/file/@location",document,XPathConstants.STRING);
  String ftrias=(String)xpath.evaluate("/jcae/mesh/submesh/triangles/file/@location",document,XPathConstants.STRING);
  FileChannel nodesChannel=new FileInputStream(new File(meshDirectory,fnodes)).getChannel();
  FileChannel triasChannel=new FileInputStream(new File(meshDirectory,ftrias)).getChannel();
  FileChannel soupChannel=new FileOutputStream(new File(meshDirectory,"soup")).getChannel();
  convert(nodesChannel,triasChannel,soupChannel);
  nodesChannel.close();
  triasChannel.close();
  soupChannel.close();
}
 

Example 57

From project jgraphx, under directory /src/com/mxgraph/util/.

Source file: mxUtils.java

  15 
vote

/** 
 * Returns a single node that matches the given XPath expression.
 * @param doc Document that contains the nodes.
 * @param expression XPath expression to be matched.
 * @return Returns a single node matching the given expression.
 */
public static Node selectSingleNode(Document doc,String expression){
  try {
    XPath xpath=XPathFactory.newInstance().newXPath();
    return (Node)xpath.evaluate(expression,doc,XPathConstants.NODE);
  }
 catch (  XPathExpressionException e) {
  }
  return null;
}
 

Example 58

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

Source file: WeatherService.java

  15 
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 59

From project l2jserver2, under directory /l2jserver2-common/src/main/java/com/l2jserver/service/configuration/.

Source file: XMLConfigurationService.java

  15 
vote

/** 
 * Set the transformed value of an property
 * @param xpath the xpath annotation
 * @param value the untransformed value
 * @param type the transformed type
 * @throws XPathExpressionException if any error occur while compiling the XPath
 */
private void set(ConfigurationXPath xpath,Object value,Class<?> type) throws XPathExpressionException {
  Node node=(Node)XPathFactory.newInstance().newXPath().compile(xpath.value()).evaluate(properties,XPathConstants.NODE);
  if (value != null) {
    if (type == Node.class) {
      node.getParentNode().replaceChild(node,(Node)value);
    }
 else {
      node.setNodeValue(transform(value.toString(),type));
      cache.put(xpath.value(),value);
    }
  }
 else {
    node.getParentNode().removeChild(node);
    cache.remove(xpath.value());
  }
}
 

Example 60

From project m2e-core-tests, under directory /org.eclipse.m2e.model.edit.tests/src/org/eclipse/m2e/model/edit/pom/tests/.

Source file: TestConfigurationModification.java

  15 
vote

private void validateXML(String xpathExpr,boolean relative) throws URISyntaxException, IOException, UnsupportedEncodingException, XPathExpressionException {
  IModelManager modelManager=StructuredModelManager.getModelManager();
  URI uri=getPomURI();
  URIConverter uriConverter=new ExtensibleURIConverterImpl();
  IDOMModel domModel;
  InputStream is=uriConverter.createInputStream(uri);
  try {
    domModel=(IDOMModel)modelManager.getModelForEdit(uri.toString(),is,null);
  }
  finally {
    is.close();
  }
  Document doc=domModel.getDocument();
  String docText=domModel.getStructuredDocument().get();
  XPath xpath=XPathFactory.newInstance().newXPath();
  SimpleNamespaceContext nsctx=new SimpleNamespaceContext();
  nsctx.registerPrefix("m","http://maven.apache.org/POM/4.0.0");
  xpath.setNamespaceContext(nsctx);
  if (relative) {
    Element configElement=(Element)xpath.evaluate("/m:project/m:build/m:plugins/m:plugin/m:configuration",doc,XPathConstants.NODE);
    Assert.assertNotNull(docText,configElement);
    Boolean value=(Boolean)xpath.evaluate(xpathExpr,configElement,XPathConstants.BOOLEAN);
    Assert.assertTrue("Cannot find " + xpathExpr + " in "+ docText,value);
  }
 else {
    Boolean value=(Boolean)xpath.evaluate(xpathExpr,doc,XPathConstants.BOOLEAN);
    Assert.assertTrue("Cannot find " + xpathExpr + " in "+ docText,value);
  }
  domModel.releaseFromEdit();
}
 

Example 61

From project m2release-plugin, under directory /src/main/java/org/jvnet/hudson/plugins/m2release/nexus/.

Source file: StageClient.java

  15 
vote

public List<Stage> getOpenStageIDs() throws StageException {
  log.debug("retreiving list of stages");
  try {
    List<Stage> openStages=new ArrayList<Stage>();
    URL url=new URL(nexusURL.toString() + "/service/local/staging/profiles");
    Document doc=getDocument(url);
    String profileExpression="//stagingProfile/id";
    XPath xpathProfile=XPathFactory.newInstance().newXPath();
    NodeList profileNodes=(NodeList)xpathProfile.evaluate(profileExpression,doc,XPathConstants.NODESET);
    for (int i=0; i < profileNodes.getLength(); i++) {
      Node profileNode=profileNodes.item(i);
      String profileID=profileNode.getTextContent();
      String statgeExpression="../stagingRepositoryIds/string";
      XPath xpathStage=XPathFactory.newInstance().newXPath();
      NodeList stageNodes=(NodeList)xpathStage.evaluate(statgeExpression,profileNode,XPathConstants.NODESET);
      for (int j=0; j < stageNodes.getLength(); j++) {
        Node stageNode=stageNodes.item(j);
        openStages.add(new Stage(profileID,stageNode.getTextContent()));
      }
    }
    return openStages;
  }
 catch (  IOException ex) {
    throw createStageExceptionForIOException(nexusURL,ex);
  }
catch (  XPathException ex) {
    throw new StageException(ex);
  }
}
 

Example 62

From project mache, under directory /src/com/streak/logging/analysis/.

Source file: AnalysisUtility.java

  15 
vote

public static void fetchCloudStorageUris(String bucketName,String startKey,String endKey,HttpRequestFactory requestFactory,List<String> urisToProcess,boolean readSchemas) throws IOException {
  String bucketUri="http://commondatastorage.googleapis.com/" + bucketName;
  HttpRequest request=requestFactory.buildGetRequest(new GenericUrl(bucketUri + "?marker=" + startKey));
  HttpResponse response=request.execute();
  try {
    Document responseDoc=DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(response.getContent());
    XPath xPath=XPathFactory.newInstance().newXPath();
    NodeList nodes=(NodeList)xPath.evaluate("//Contents/Key/text()",responseDoc,XPathConstants.NODESET);
    for (int i=0; i < nodes.getLength(); i++) {
      String key=nodes.item(i).getNodeValue();
      if (key.compareTo(endKey) >= 0) {
        break;
      }
      if (key.endsWith(".schema") ^ readSchemas) {
        continue;
      }
      if (readSchemas) {
        key=key.substring(0,key.length() - ".schema".length());
      }
      urisToProcess.add("gs://" + bucketName + "/"+ key);
    }
  }
 catch (  SAXException e) {
    throw new IOException("Error parsing cloud storage response",e);
  }
catch (  ParserConfigurationException e) {
    throw new IOException("Error configuring cloud storage parser",e);
  }
catch (  XPathExpressionException e) {
    throw new IOException("Error finding keys",e);
  }
}
 

Example 63

From project nexus-obr-plugin, under directory /nexus-obr-testsuite/src/test/java/org/sonatype/nexus/plugin/obr/test/.

Source file: ObrProxyIT.java

  15 
vote

private void assertObrPath(final String repositoryId,final String expectedRemoteUrl,final String expectedObrPath) throws Exception {
  final DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
  final DocumentBuilder db=dbf.newDocumentBuilder();
  final Document doc=db.parse(new File(nexus().getWorkDirectory(),"conf/nexus.xml"));
  final XPath xpath=XPathFactory.newInstance().newXPath();
  final Node url=(Node)xpath.evaluate("/nexusConfiguration/repositories/repository[id='" + repositoryId + "']/remoteStorage/url",doc,XPathConstants.NODE);
  assertThat(url,is(notNullValue()));
  assertThat(url.getTextContent(),is(expectedRemoteUrl));
  final Node obrPath=(Node)xpath.evaluate("/nexusConfiguration/repositories/repository[id='" + repositoryId + "']/externalConfiguration/obrPath",doc,XPathConstants.NODE);
  assertThat(obrPath,is(notNullValue()));
  assertThat(obrPath.getTextContent(),is(expectedObrPath));
}
 

Example 64

From project onebusaway-nyc, under directory /onebusaway-nyc-transit-data-manager/onebusaway-nyc-tdm-webapp/src/test/java/org/onebusaway/nyc/transit_data_manager/api/.

Source file: DepotResourceTest.java

  15 
vote

@Test public void test1() throws Exception {
  File tmpInFile=File.createTempFile("tmp",".tmp");
  tmpInFile.deleteOnExit();
  File tmpOutFile=new File("/tmp/results.xml");
  InputStream resource=this.getClass().getResourceAsStream("draft_depot_assignments_with_extra_fields.xml");
  assertNotNull(resource);
  copy(resource,tmpInFile.getCanonicalPath());
  MtaBusDepotsToTcipXmlProcess process=new MtaBusDepotsToTcipXmlProcess(tmpInFile,tmpOutFile);
  process.executeProcess();
  process.writeToFile();
  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
  DocumentBuilder builder=factory.newDocumentBuilder();
  Document doc=builder.parse(tmpOutFile);
  XPath xpath=XPathFactory.newInstance().newXPath();
  NodeList nodes=(NodeList)xpath.evaluate("/cptFleetSubsets",doc,XPathConstants.NODESET);
  assertNotNull(nodes);
  assertEquals(1,nodes.getLength());
  nodes=(NodeList)xpath.evaluate("/cptFleetSubsets/subscriptionInfo",doc,XPathConstants.NODESET);
  assertNotNull(nodes);
  assertTrue(nodes.getLength() > 0);
  nodes=(NodeList)xpath.evaluate("/cptFleetSubsets/subscriptionInfo/requestedType",doc,XPathConstants.NODESET);
  assertNotNull(nodes);
  assertTrue(nodes.getLength() > 0);
  assertEquals("2",xpath.evaluate("/cptFleetSubsets/subscriptionInfo/requestedType/text()",doc,XPathConstants.STRING));
  assertEquals("CAST",xpath.evaluate("/cptFleetSubsets/defined-groups/defined-group/group-name/text()",doc,XPathConstants.STRING));
  assertEquals("1862",xpath.evaluate("/cptFleetSubsets/defined-groups/defined-group/group-members/group-member/vehicle-id/text()",doc,XPathConstants.STRING));
  assertEquals("1865",xpath.evaluate("/cptFleetSubsets/defined-groups/defined-group/group-members/group-member[2]/vehicle-id/text()",doc,XPathConstants.STRING));
  assertEquals("1925",xpath.evaluate("/cptFleetSubsets/defined-groups/defined-group[2]/group-members/group-member[1]/vehicle-id/text()",doc,XPathConstants.STRING));
  assertEquals("3117",xpath.evaluate("/cptFleetSubsets/defined-groups/defined-group[3]/group-members/group-member[1]/vehicle-id/text()",doc,XPathConstants.STRING));
  tmpOutFile.deleteOnExit();
}
 

Example 65

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

Source file: WSPortIT.java

  15 
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 66

From project pluto, under directory /pluto-util/src/main/java/org/apache/pluto/util/descriptors/web/.

Source file: PlutoWebXmlRewriter.java

  15 
vote

public PlutoWebXmlRewriter(Document descriptor){
  this.descriptor=descriptor;
  this.root=descriptor.getDocumentElement();
  this.namespace=root.getNamespaceURI();
  String version=root.getAttribute("version");
  if (version.equals("")) {
    version="2.3";
  }
  try {
    Double.parseDouble(version);
  }
 catch (  NumberFormatException e) {
    throw new RuntimeException("Unable to create Determine wew.xml version: " + version,e);
  }
  descriptor23=version.equals("2.3");
  if (!descriptor23 && version.compareTo("2.3") < 0) {
    throw new RuntimeException("Unsupported (too old?) web.xml version: " + version);
  }
  xpath=XPathFactory.newInstance().newXPath();
  if (namespace != null && namespace.length() > 0) {
    prefix=NAMESPACE_PREFIX + ":";
    xpath.setNamespaceContext(new XPathNamespaceContext(NAMESPACE_PREFIX,namespace));
  }
 else {
    prefix=XMLConstants.DEFAULT_NS_PREFIX;
    xpath.setNamespaceContext(new XPathNamespaceContext(XMLConstants.DEFAULT_NS_PREFIX));
  }
}
 

Example 67

From project Possom, under directory /generic.sesam/velocity-directives/src/main/java/no/sesat/search/view/velocity/.

Source file: XPathDirective.java

  15 
vote

/** 
 * Evaluates xpath expression and writes the result as a string. Expects the following velocity parameters: <ul> <li>optional target variable</li> <li>the expression</li> <li>optional if target variable was not supplied org.w3c.dom.Node to apply expression to (default is value of "document" from cxt)</li> </ul>
 * @param cxt The cxt.
 * @param writer The writer.
 * @param node The node.
 * @return return true on success.
 * @throws IOException
 * @throws ResourceNotFoundException
 * @throws ParseErrorException
 * @throws MethodInvocationException
 */
public boolean render(final InternalContextAdapter cxt,final Writer writer,final Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
  if (node.jjtGetNumChildren() < 1) {
    LOG.error("#" + getName() + " - missing argument");
    return false;
  }
  try {
    int nextArg=targetVariable == null ? 0 : 1;
    final String expression=getArgument(cxt,node,nextArg++);
    final Object doc=node.jjtGetNumChildren() > 1 ? node.jjtGetChild(nextArg).value(cxt) : cxt.get("document");
    final String xPathResult=XPathFactory.newInstance().newXPath().evaluate(expression,doc);
    if (targetVariable == null) {
      writer.write(xPathResult);
    }
 else {
      cxt.put(targetVariable,xPathResult);
    }
    return true;
  }
 catch (  XPathExpressionException e) {
    LOG.error(e);
    return false;
  }
}
 

Example 68

From project ptest-server, under directory /src/main/java/com/mnxfst/testing/plan/.

Source file: TSPlanBuilder.java

  15 
vote

/** 
 * Parses out the global configuration options. If there are not settings, the result will be an empty (but non-null) map
 * @param testPlanDocument
 * @return
 * @throws TSPlanConfigurationFormatException
 */
protected Map<String,TSPlanConfigOption> parseGlobalConfigurationOptions(Document testPlanDocument) throws TSPlanConfigurationFormatException {
  Map<String,TSPlanConfigOption> result=new HashMap<String,TSPlanConfigOption>();
  NodeList configurationOptionsNodes=null;
  XPath xpath=XPathFactory.newInstance().newXPath();
  try {
    configurationOptionsNodes=(NodeList)xpath.evaluate(XPATH_EXPRESSION_ALL_GLOBAL_CONFIG_OPTIONS,testPlanDocument,XPathConstants.NODESET);
  }
 catch (  XPathExpressionException e) {
    throw new TSPlanConfigurationFormatException("Failed to parse provided test plan using a xpath expression. Error: " + e.getMessage(),e);
  }
  if (configurationOptionsNodes != null && configurationOptionsNodes.getLength() > 0) {
    for (int i=0; i < configurationOptionsNodes.getLength(); i++) {
      TSPlanConfigOption cfgOption=configOptionsParser.parseConfigurationNode(configurationOptionsNodes.item(i),null);
      result.put(cfgOption.getName(),cfgOption);
    }
  }
  return result;
}
 

Example 69

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

Source file: Artifacts.java

  15 
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 70

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

Source file: Xml.java

  15 
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 71

From project servicemix-utils, under directory /src/main/java/org/apache/servicemix/expression/.

Source file: JAXPXPathExpression.java

  15 
vote

/** 
 * Compiles the xpath expression.
 */
public void afterPropertiesSet() throws XPathExpressionException {
  if (xPathExpression == null) {
    if (xpath == null) {
      throw new IllegalArgumentException("You must specify the xpath property");
    }
    if (factory == null) {
      factory=XPathFactory.newInstance();
    }
    XPath xpathObject=factory.newXPath();
    xpathObject.setXPathVariableResolver(variableResolver);
    if (functionResolver != null) {
      xpathObject.setXPathFunctionResolver(functionResolver);
    }
    if (namespaceContext != null) {
      xpathObject.setNamespaceContext(namespaceContext);
    }
    xPathExpression=xpathObject.compile(xpath);
  }
}
 

Example 72

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

Source file: UpdateCache.java

  15 
vote

public void read() throws IOException {
  hashCache=new HashMap<String,String>();
  InputStream in;
  try {
    in=new BufferedInputStream(new FileInputStream(file));
    Document doc=parseXml(in);
    XPath xpath=XPathFactory.newInstance().newXPath();
    for (    Node node : getNodes(doc,xpath.compile("/cache/entry"))) {
      String path=getValue(node);
      String hash=getAttrOrNull(node,"hash");
      hashCache.put(path,hash);
    }
    lastUpdateId=getStringOrNull(doc,xpath.compile("/cache/current/text()"));
  }
 catch (  XPathExpressionException e) {
    throw new RuntimeException(e);
  }
catch (  ParserConfigurationException e) {
    throw new RuntimeException(e);
  }
catch (  SAXException e) {
    throw new RuntimeException(e);
  }
}
 

Example 73

From project Solbase-Solr, under directory /src/java/org/apache/solr/handler/component/.

Source file: QueryElevationComponent.java

  15 
vote

private Map<String,ElevationObj> loadElevationMap(Config cfg) throws IOException {
  XPath xpath=XPathFactory.newInstance().newXPath();
  Map<String,ElevationObj> map=new HashMap<String,ElevationObj>();
  NodeList nodes=(NodeList)cfg.evaluate("elevate/query",XPathConstants.NODESET);
  for (int i=0; i < nodes.getLength(); i++) {
    Node node=nodes.item(i);
    String qstr=DOMUtil.getAttr(node,"text","missing query 'text'");
    NodeList children=null;
    try {
      children=(NodeList)xpath.evaluate("doc",node,XPathConstants.NODESET);
    }
 catch (    XPathExpressionException e) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"query requires '<doc .../>' child");
    }
    ArrayList<String> include=new ArrayList<String>();
    ArrayList<String> exclude=new ArrayList<String>();
    for (int j=0; j < children.getLength(); j++) {
      Node child=children.item(j);
      String id=DOMUtil.getAttr(child,"id","missing 'id'");
      String e=DOMUtil.getAttr(child,EXCLUDE,null);
      if (e != null) {
        if (Boolean.valueOf(e)) {
          exclude.add(id);
          continue;
        }
      }
      include.add(id);
    }
    ElevationObj elev=new ElevationObj(qstr,include,exclude);
    if (map.containsKey(elev.analyzed)) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Boosting query defined twice for query: '" + elev.text + "' ("+ elev.analyzed+ "')");
    }
    map.put(elev.analyzed,elev);
  }
  return map;
}
 

Example 74

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

Source file: FlexConfigurationManager.java

  15 
vote

@Override protected void initializeExpressionQuery(){
  if (this.xpath == null) {
    this.xpath=XPathFactory.newInstance().newXPath();
  }
 else {
    this.xpath.reset();
  }
  this.exprCache=new HashMap<String,XPathExpression>();
}
 

Example 75

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

Source file: XpathExpectationsHelper.java

  15 
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);
}
 

Example 76

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

Source file: XPathBuilder.java

  15 
vote

@SuppressWarnings("rawtypes") public XPathFactory getXPathFactory() throws XPathFactoryConfigurationException {
  if (xpathFactory == null) {
    if (objectModelUri != null) {
      logger.info("Using objectModelUri " + objectModelUri + " when creating XPathFactory");
      xpathFactory=XPathFactory.newInstance(objectModelUri);
      return xpathFactory;
    }
    Properties properties=System.getProperties();
    for (    Map.Entry prop : properties.entrySet()) {
      String key=(String)prop.getKey();
      if (key.startsWith(XPathFactory.DEFAULT_PROPERTY_NAME)) {
        String uri=after(key,":");
        if (uri != null) {
          logger.info("Using system property " + key + " with value: "+ prop.getValue()+ " when creating XPathFactory");
          xpathFactory=XPathFactory.newInstance(uri);
          return xpathFactory;
        }
      }
    }
    if (xpathFactory == null) {
      logger.debug("Creating default XPathFactory");
      xpathFactory=XPathFactory.newInstance();
    }
  }
  return xpathFactory;
}
 

Example 77

From project tennera, under directory /ant-gettext/src/main/java/org/fedorahosted/tennera/antgettext/.

Source file: XPath2PotTask.java

  15 
vote

@Override protected void processFile(String filename,File f) throws SAXException, IOException {
  XPath xpath=XPathFactory.newInstance().newXPath();
  String expression=this.xpath;
  InputSource inputSource=new InputSource(f.getPath());
  try {
    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    DocumentBuilder parser=dbf.newDocumentBuilder();
    parser.setEntityResolver(xmlCatalog);
    Document document=parser.parse(inputSource);
    NodeList nodes=(NodeList)xpath.evaluate(expression,document,XPathConstants.NODESET);
    for (int i=0; i < nodes.getLength(); i++) {
      Node node=nodes.item(i);
      String key=node.getTextContent();
      String position=getXPathForElement(node,node.getOwnerDocument());
      recordMatch(filename,key,position);
    }
  }
 catch (  XPathExpressionException e) {
    throw new BuildException(e);
  }
catch (  ParserConfigurationException e) {
    throw new BuildException(e);
  }
}
 

Example 78

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

Source file: ParallelTestExecutionTest.java

  15 
vote

private Set<String> extractExecutedTests(File[] xmlReports) throws FileNotFoundException, XPathExpressionException, IOException {
  XPath xpath=XPathFactory.newInstance().newXPath();
  Set<String> actualTests=new HashSet<String>();
  for (  File xmlReportFile : xmlReports) {
    FileInputStream xmlStream=new FileInputStream(xmlReportFile);
    NodeList testCaseNodes;
    try {
      testCaseNodes=(NodeList)xpath.evaluate("/testsuite/testcase",new InputSource(xmlStream),XPathConstants.NODESET);
    }
  finally {
      xmlStream.close();
    }
    for (int i=0; i < testCaseNodes.getLength(); i++) {
      Element node=(Element)testCaseNodes.item(i);
      String testClassName=node.getAttribute("classname");
      String method=node.getAttribute("name");
      actualTests.add(testClassName + "#" + method);
    }
  }
  return actualTests;
}
 

Example 79

From project WCF-Package-Builder, under directory /src/com/wainox/wcf/pb/gui/.

Source file: PackageBuilderGUI.java

  15 
vote

private void assignHelper(PackageBuilder builder){
  if (this.languageField.isSelected()) {
    XPath xpath=XPathFactory.newInstance().newXPath();
    try {
      NodeList nodeList=(NodeList)xpath.compile("//package/instructions/languages/text()").evaluate(builder.getSource().getPackageInfoDocument(),XPathConstants.NODESET);
      for (int i=0; i < nodeList.getLength(); i++) {
        File file=new File(builder.getSource().getPath() + System.getProperty("file.separator") + nodeList.item(i).getNodeValue());
        new PackageLanguageFileHandler(file);
      }
    }
 catch (    Exception e) {
    }
  }
}
 

Example 80

From project wikbook, under directory /core/src/main/java/org/wikbook/core/model/content/block/.

Source file: ProgramListingElement.java

  15 
vote

public ProgramListingElement(final DocbookBuilderContext context,LanguageSyntax languageSyntax,Integer indent,String content,boolean highlightCode){
  DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
  dbf.setIgnoringElementContentWhitespace(true);
  dbf.setCoalescing(true);
  dbf.setNamespaceAware(true);
  dbf.setXIncludeAware(false);
  DocumentBuilder documentBuilder;
  try {
    documentBuilder=dbf.newDocumentBuilder();
  }
 catch (  ParserConfigurationException e) {
    throw new WikbookException(e);
  }
  this.context=context;
  this.languageSyntax=languageSyntax;
  this.indent=indent;
  this.content=content;
  this.highlightCode=highlightCode;
  this.callouts=new ElementContainer<CalloutElement>(CalloutElement.class);
  this.documentBuilder=documentBuilder;
  this.xpath=XPathFactory.newInstance().newXPath();
}
 

Example 81

From project xwiki-commons, under directory /xwiki-commons-core/xwiki-commons-xml/src/main/java/org/xwiki/xml/internal/html/filter/.

Source file: AttributeFilter.java

  15 
vote

@Override public void filter(Document document,Map<String,String> cleaningParameters){
  StringBuilder xpathExpression=new StringBuilder();
  for (  String attributeName : ATTRIBUTE_TO_CSS_PROPERTY.keySet()) {
    if (xpathExpression.length() > 0) {
      xpathExpression.append('|');
    }
    xpathExpression.append("//@").append(attributeName);
  }
  NodeList attributes=null;
  XPath xpath=XPathFactory.newInstance().newXPath();
  try {
    attributes=(NodeList)xpath.evaluate(xpathExpression.toString(),document,XPathConstants.NODESET);
  }
 catch (  XPathExpressionException e) {
    logger.error("Failed to apply the HTML attribute cleaning filter.",e);
    return;
  }
  for (int i=0; i < attributes.getLength(); i++) {
    Attr attribute=(Attr)attributes.item(i);
    Element element=attribute.getOwnerElement();
    StringBuilder style=new StringBuilder(element.getAttribute(ATTRIBUTE_STYLE).trim());
    if (style.length() > 0 && style.charAt(style.length() - 1) != ';') {
      style.append(';');
    }
    style.append(ATTRIBUTE_TO_CSS_PROPERTY.get(attribute.getName()));
    style.append(':').append(attribute.getValue());
    element.setAttribute(ATTRIBUTE_STYLE,style.toString());
    element.removeAttributeNode(attribute);
  }
}
 

Example 82

From project yanel, under directory /src/resources/registration/src/java/org/wyona/yanel/resources/registration/.

Source file: UserRegistrationResource.java

  15 
vote

/** 
 * Read user registration request from repository node
 * @param node Repository node containing firstname, lastname, etc.
 */
private UserRegistrationBean readRegistrationRequest(Node node) throws Exception {
  Document doc=XMLHelper.readDocument(node.getInputStream());
  XPath xpath=XPathFactory.newInstance().newXPath();
  xpath.setNamespaceContext(new UserRegistrationNamespaceContext());
  String uuid=(String)xpath.evaluate("/ur:registration-request/@uuid",doc,XPathConstants.STRING);
  String gender=(String)xpath.evaluate("/ur:registration-request/ur:gender",doc,XPathConstants.STRING);
  String firstname=(String)xpath.evaluate("/ur:registration-request/ur:firstname",doc,XPathConstants.STRING);
  String lastname=(String)xpath.evaluate("/ur:registration-request/ur:lastname",doc,XPathConstants.STRING);
  String email=(String)xpath.evaluate("/ur:registration-request/ur:email",doc,XPathConstants.STRING);
  String password=(String)xpath.evaluate("/ur:registration-request/ur:password",doc,XPathConstants.STRING);
  UserRegistrationBean urBean=new UserRegistrationBean(gender,firstname,lastname,email,password,"TODO","TODO");
  urBean.setUUID(uuid);
  return urBean;
}
 

Example 83

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

Source file: XmlHelper.java

  15 
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 84

From project zencoder-java, under directory /src/main/java/de/bitzeche/video/transcoding/zencoder/.

Source file: ZencoderClient.java

  15 
vote

public ZencoderClient(String zencoderApiKey,ZencoderAPIVersion apiVersion){
  this.zencoderAPIKey=zencoderApiKey;
  if (ZencoderAPIVersion.API_DEV.equals(apiVersion)) {
    LOGGER.warn("!!! Using development version of zencoder API !!!");
  }
  this.zencoderAPIVersion=apiVersion;
  httpClient=ApacheHttpClient.create();
  httpClient.setFollowRedirects(true);
  xPath=XPathFactory.newInstance().newXPath();
  zencoderAPIBaseUrl=zencoderAPIVersion.getBaseUrl();
}
 

Example 85

From project zencoder-java_1, under directory /src/main/java/de/bitzeche/video/transcoding/zencoder/.

Source file: ZencoderClient.java

  15 
vote

public ZencoderClient(String zencoderApiKey){
  this.ZENCODER_API_KEY=zencoderApiKey;
  httpClient=ApacheHttpClient.create();
  httpClient.setFollowRedirects(true);
  xPath=XPathFactory.newInstance().newXPath();
}