Java Code Examples for javax.xml.xpath.XPath

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

  22 
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 arquillian_deprecated, under directory /containers/glassfish-remote-3.1/src/main/java/org/jboss/arquillian/container/glassfish/remote_3_1/.

Source file: GlassFishRestDeployableContainer.java

  22 
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 3

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

Source file: SWCResourceRoot.java

  22 
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 4

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

Source file: PubchemStructureGenerator.java

  22 
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 5

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

Source file: XmlElements.java

  22 
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 6

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

Source file: SendDataSpecification.java

  22 
vote

public int getDelay(ActivityContext activityContext) throws DataSourceException, XPathExpressionException {
  if (getDelayExpression() != null) {
    final Context vtlContext=activityContext.createVelocityContext();
    final ContextXPathVariableResolver xpathResolver=new ContextXPathVariableResolver(vtlContext);
    final XPath xpath=XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(getNamespaceContext());
    xpath.setXPathVariableResolver(xpathResolver);
    fDelay=((Double)xpath.evaluate(getDelayExpression(),fLiteralData,XPathConstants.NUMBER)).intValue();
    setDelayExpression(null);
  }
  return fDelay;
}
 

Example 7

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

Source file: XMLUtils.java

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

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

Source file: XMLBody.java

  22 
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 9

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

  22 
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 10

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

Source file: WizardHelpers.java

  22 
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 11

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

Source file: FedoraResponseImpl.java

  22 
vote

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

Example 12

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

Source file: ASDocScreenScraper.java

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

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 14

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

Source file: XPathUtil.java

  22 
vote

/** 
 * Evaluate an XPath expression to a String value. 
 */
public String valueOf(Node n,String xpathString) throws JspTagException {
  staticInit();
  XPathVariableResolver jxvr=new JSTLXPathVariableResolver(pageContext);
  Node contextNode=adaptParamsForXalan(n,xpathString.trim(),jxvr);
  XPath xpath=XPATH_FACTORY.newXPath();
  xpath.setNamespaceContext(jstlXPathNamespaceContext);
  xpath.setXPathVariableResolver(jxvr);
  try {
    return xpath.evaluate(xpathString,contextNode);
  }
 catch (  XPathExpressionException ex) {
    throw new JspTagException(ex.toString(),ex);
  }
}
 

Example 15

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

Source file: JAXPModuleTest.java

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

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 17

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

Source file: mxUtils.java

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

From project jsfunit, under directory /jboss-jsfunit-analysis/src/main/java/org/jboss/jsfunit/analysis/util/.

Source file: ParserUtils.java

  22 
vote

public static NodeList query(Node node,String xpathQuery,final String filePath){
  if (node == null)   throw new NullPointerException("document was null " + filePath);
  XPath xpath=xPathFactory.newXPath();
  try {
    return (NodeList)xpath.evaluate(xpathQuery,node,XPathConstants.NODESET);
  }
 catch (  Exception e) {
    throw new RuntimeException("Could not run XPath query '" + xpathQuery + "' on document "+ filePath);
  }
}
 

Example 19

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 20

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

Source file: UpdateablePartialBinding.java

  22 
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 21

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

Source file: CreateAssetXmlTest.java

  22 
vote

private NodeList getAssetNodeChildren(Document document) throws XPathExpressionException {
  String path="/rdf:RDF/oslc_asset:Asset";
  XPath xpath=OSLCUtils.getXPath();
  Node asset=(Node)xpath.evaluate(path,document,XPathConstants.NODE);
  return asset.getChildNodes();
}
 

Example 22

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

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

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 24

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

Source file: ObrProxyIT.java

  22 
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 25

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 26

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 27

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

Source file: Book.java

  22 
vote

public Book(Document doc,Node newBookNode) throws XPathExpressionException {
  bookNode=newBookNode;
  XPath xpath=Unixref.getXPath(doc);
  BOOK_META_EXPR=xpath.compile("book_metadata");
  BOOK_SET_META_EXPR=xpath.compile("book_set_metadata");
  BOOK_SERIES_META_EXPR=xpath.compile("book_series_metadata");
  EDITION_NUMBER_EXPR=xpath.compile("edition_number");
  DOI_EXPR=xpath.compile("doi_data/doi");
  ISBN_EXPR=xpath.compile("isbn");
  ISSN_EXPR=xpath.compile("issn");
  mdNode=XPathHelpers.oneOf(bookNode,BOOK_META_EXPR,BOOK_SET_META_EXPR,BOOK_SERIES_META_EXPR);
}
 

Example 28

From project Possom, under directory /view-config-spi/src/main/java/no/sesat/search/view/navigation/.

Source file: OptionsNavigationConfig.java

  22 
vote

public OptionsNavigationConfig(final NavigationConfig.Nav parent,final NavigationConfig.Navigation navigation,final Element element){
  super(parent,navigation,element);
  try {
    final XPath xPath=XPathFactory.newInstance().newXPath();
    final NodeList optionNodes=(NodeList)xPath.evaluate("config/*",element,XPathConstants.NODESET);
    processOptions(optionNodes);
  }
 catch (  XPathExpressionException e) {
    throw new RuntimeException(e);
  }
}
 

Example 29

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 30

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 31

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 32

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 33

From project seamless, under directory /xml/src/test/java/org/seamless/test/xhtml/.

Source file: Wrapping.java

  22 
vote

@Test public void workFragment() throws Exception {
  XHTMLParser parser=createParser();
  XPath xpath=parser.createXPath();
  XHTML xhtml=parser.createDocument();
  XHTMLElement root=xhtml.createRoot(xpath,XHTML.ELEMENT.div).setAttribute(XHTML.ATTR.CLASS,"foo").setAttribute(XHTML.ATTR.id,"div1");
  root.createChild(XHTML.ELEMENT.a).setAttribute(XHTML.ATTR.CLASS,"test1 bar").setAttribute(XHTML.ATTR.href,"http://test1.foo.bar");
  root.createChild(XHTML.ELEMENT.a).setAttribute(XHTML.ATTR.CLASS,"test2 bar").setAttribute(XHTML.ATTR.href,"http://test2.foo.bar");
  assertEquals(xhtml.getRoot(xpath).findAllAnchors(null,"bar").length,2);
}
 

Example 34

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 35

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

Source file: Config.java

  22 
vote

public Object evaluate(String path,QName type){
  XPath xpath=xpathFactory.newXPath();
  try {
    String xstr=normalize(path);
    Object o=xpath.evaluate(xstr,doc,type);
    return o;
  }
 catch (  XPathExpressionException e) {
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Error in xpath:" + path + " for "+ name,e,false);
  }
}
 

Example 36

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

Source file: StandardXmlArtifactAnalyzer.java

  22 
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 37

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

Source file: XpathExpectationsHelper.java

  22 
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 38

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

Source file: XPath2PotTestRun.java

  22 
vote

public static void main(String[] args) throws XPathExpressionException {
  File f=new File("src/test/resources/taskdefs/meta/studio_eclipse_option.meta");
  XPath xpath=XPathFactory.newInstance().newXPath();
  String expression="//attribute::*[namespace-uri()='http://test.example.org/'] | //@displayName | //XModelAttribute/@name | //XModelAttribute/@default | //Constraint/value/@name";
  InputSource inputSource=new InputSource(f.getPath());
  NodeList nodes=(NodeList)xpath.evaluate(expression,inputSource,XPathConstants.NODESET);
  for (int i=0; i < nodes.getLength(); i++) {
    Node node=nodes.item(i);
    String key=node.getTextContent();
    Document doc=node.getOwnerDocument();
    String path=XPath2PotTask.getXPathForElement(node,doc);
    System.out.println(key + ": " + path);
  }
}
 

Example 39

From project TomP2P, under directory /src/main/java/net/tomp2p/upnp/.

Source file: Action.java

  22 
vote

Action(Service parent,Node xml) throws XPathExpressionException {
  this.parent=parent;
  XPath xpath=XMLUtil.xpath;
  name=xpath.evaluate("name",xml);
  Node argList=(Node)xpath.evaluate("argumentList",xml,XPathConstants.NODE);
  int argCount=argList == null ? 0 : Integer.parseInt(xpath.evaluate("count( argument )",argList));
  arguments=new Argument[argCount];
  for (int i=1; i <= argCount; i++) {
    Node argXML=(Node)xpath.evaluate("argument[ " + i + " ]",argList,XPathConstants.NODE);
    arguments[i - 1]=new Argument(argXML);
  }
}
 

Example 40

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

Source file: PackageBuilderGUI.java

  22 
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 41

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

Source file: UserRegistrationResource.java

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

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 43

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 44

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

Source file: BuildInfoRecorder.java

  21 
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 45

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 46

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 47

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

Source file: AppConfigParser.java

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

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 49

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 50

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

Source file: InspectMessageHelper.java

  21 
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 eucalyptus, under directory /clc/modules/image-manager/src/edu/ucsb/eucalyptus/cloud/ws/.

Source file: ImageManager.java

  21 
vote

private static Long getSize(String userId,String manifestPath){
  Long size=0l;
  try {
    String[] imagePathParts=manifestPath.split("/");
    Document inputSource=ImageManager.getManifestData(EucalyptusProperties.NAME,imagePathParts[0],imagePathParts[1]);
    XPath xpath=XPathFactory.newInstance().newXPath();
    String rootSize="0";
    try {
      rootSize=(String)xpath.evaluate("/manifest/image/size/text()",inputSource,XPathConstants.STRING);
      try {
        size=Long.parseLong(rootSize);
      }
 catch (      NumberFormatException e) {
        LOG.error(e,e);
      }
    }
 catch (    XPathExpressionException e) {
      LOG.error(e,e);
    }
  }
 catch (  EucalyptusCloudException e) {
    LOG.error(e,e);
  }
  return size;
}
 

Example 52

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 53

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

Source file: SolrContainerFactory.java

  21 
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 54

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 55

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 56

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

Source file: AnnotationTool.java

  21 
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 57

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

  21 
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 58

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

Source file: StageClient.java

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

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

Source file: AnalysisUtility.java

  21 
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 60

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 61

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 62

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

Source file: CompilerTest.java

  21 
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 63

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

  21 
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 64

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

Source file: TSPlanBuilder.java

  21 
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 65

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 66

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

Source file: WsdlDeriver.java

  21 
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 67

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 68

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 69

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 70

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

Source file: JAXPXPathExpression.java

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

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

Source file: ValidationJsurplusFilesModuleImpl.java

  21 
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 72

From project SIREn, under directory /siren-solr/src/main/java/org/sindice/siren/solr/schema/.

Source file: SirenTopLevelAnalyzerConfig.java

  21 
vote

/** 
 * Read the XML config file, and load the analyzers.
 */
private void readConfig(final InputSource is){
  log.info("Reading SIREn top-level analyzer configuration");
  try {
    final Config analyzerConf=new Config(loader,"analyzerConfig",is,"/analyzerConfig/");
    final Document document=analyzerConf.getDocument();
    final XPath xpath=analyzerConf.getXPath();
    final Node node=(Node)xpath.evaluate("/analyzerConfig/@name",document,XPathConstants.NODE);
    if (node == null) {
      log.warn("analyzerConfig has no name!");
    }
 else {
      name=node.getNodeValue();
      log.info("analyzerConfig name=" + name);
    }
    version=analyzerConf.get("/analyzerConfig/@version");
    String expression="/analyzerConfig/analyzer[@type='index']";
    Node anode=(Node)xpath.evaluate(expression,node,XPathConstants.NODE);
    analyzer=AnalyzerConfigReader.readAnalyzer(anode,loader,luceneMatchVersion);
    if (analyzer == null) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Configuration Error: No analyzer defined for type 'index'");
    }
    expression="/analyzerConfig/analyzer[@type='keyword-query']";
    anode=(Node)xpath.evaluate(expression,node,XPathConstants.NODE);
    kqAnalyzer=AnalyzerConfigReader.readAnalyzer(anode,loader,luceneMatchVersion);
    if (kqAnalyzer == null) {
      throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"Configuration Error: No analyzer defined for type 'keyword-query'");
    }
  }
 catch (  final SolrException e) {
    SolrConfig.severeErrors.add(e);
    throw e;
  }
catch (  final Exception e) {
    SolrConfig.severeErrors.add(e);
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,"SIREn top-level analyzer configuration parsing failed",e,false);
  }
}
 

Example 73

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

Source file: UpdateCache.java

  21 
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 74

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 75

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 76

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

Source file: ConfigNode.java

  21 
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 77

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

Source file: ParallelTestExecutionTest.java

  21 
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 78

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

  21 
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 79

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

Source file: XPathOperation.java

  19 
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 80

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

Source file: XMLUtils.java

  19 
vote

/** 
 * getStringFromXPath Gets a string from an xml.
 * @param expression The XPath expression to evaluate, returns a string
 * @return The result of evaluating the given XPath expression.
 */
public static String getStringFromXPath(Document doc,XPath xpath,String expression){
synchronized (xpath) {
    try {
      return xpath.evaluate(expression,doc);
    }
 catch (    Exception e) {
      System.err.println("Error evaluating xpath expression: " + expression);
      e.printStackTrace();
    }
    return "";
  }
}