Java Code Examples for javax.xml.xpath.XPath#setXPathVariableResolver()

The following examples show how to use javax.xml.xpath.XPath#setXPathVariableResolver() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XPathHelper.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new {@link XPath} with the passed variable resolver, function
 * resolver and namespace context.
 *
 * @param aXPathFactory
 *        The XPath factory object to use. May not be <code>null</code>.
 * @param aVariableResolver
 *        Variable resolver to be used. May be <code>null</code>.
 * @param aFunctionResolver
 *        Function resolver to be used. May be <code>null</code>.
 * @param aNamespaceContext
 *        Namespace context to be used. May be <code>null</code>.
 * @return The created non-<code>null</code> {@link XPath} object
 */
@Nonnull
public static XPath createNewXPath (@Nonnull final XPathFactory aXPathFactory,
                                    @Nullable final XPathVariableResolver aVariableResolver,
                                    @Nullable final XPathFunctionResolver aFunctionResolver,
                                    @Nullable final NamespaceContext aNamespaceContext)
{
  ValueEnforcer.notNull (aXPathFactory, "XPathFactory");

  final XPath aXPath = aXPathFactory.newXPath ();
  if (aVariableResolver != null)
    aXPath.setXPathVariableResolver (aVariableResolver);
  if (aFunctionResolver != null)
    aXPath.setXPathFunctionResolver (aFunctionResolver);
  if (aNamespaceContext != null)
    aXPath.setNamespaceContext (aNamespaceContext);
  return aXPath;
}
 
Example 2
Source File: XPathScheme.java    From rice with Educational Community License v2.0 6 votes vote down vote up
public Object load(Property property, final RouteContext context) {
    XPath xpath = XPathHelper.newXPath();
    final BranchService branchService = KEWServiceLocator.getBranchService();
    xpath.setXPathVariableResolver(new XPathVariableResolver() {
        public Object resolveVariable(QName name) {
            LOG.debug("Resolving XPath variable: " + name);
            String value = branchService.getScopedVariableValue(context.getNodeInstance().getBranch(), BranchState.VARIABLE_PREFIX + name.getLocalPart());
            LOG.debug("Resolved XPath variable " + name + " to " + value);
            return value;
        }
    });
    try {
        String docContent = context.getDocument().getDocContent();
        LOG.debug("Executing xpath expression '" + property.locator + "' in doc '" + docContent + "'");
        return xpath.evaluate(property.locator, new InputSource(new StringReader(docContent)), XPathConstants.STRING);
    } catch (XPathExpressionException xpee) {
        throw new RuntimeException("Error evaluating xpath expression '" + property.locator + "'", xpee);
    }
}
 
Example 3
Source File: XPathAPITest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testXPathVariableResolver() throws Exception {
    XPath xpath = getXPath();
    xpath.setXPathVariableResolver(new MyXPathVariableResolver());
    assertEquals(xpath.evaluate("//astro:stardb/astro:star[astro:hr=$id]/astro:constellation", doc.getDocumentElement()), "Peg");

}
 
Example 4
Source File: JDKEngine.java    From jlibs with Apache License 2.0 5 votes vote down vote up
@Override
public List<Object> evaluate(TestCase testCase, String file) throws Exception{
    Document doc = toDOM(file);
    List<Object> results = new ArrayList<Object>(testCase.xpaths.size());
    XPath xpathObj = factory.newXPath();
    if(xpathObj instanceof XPathEvaluator){
        XPathEvaluator xpe = (XPathEvaluator)xpathObj;
        xpe.getConfiguration().setVersionWarning(false);
        ((StandardErrorListener)xpe.getConfiguration().getErrorListener()).setRecoveryPolicy(Configuration.RECOVER_SILENTLY);
        xpe.getStaticContext().setBackwardsCompatibilityMode(true);
    }
    for(XPathInfo xpathInfo: testCase.xpaths){
        xpathObj.setXPathVariableResolver(testCase.variableResolver);
        xpathObj.setXPathFunctionResolver(testCase.functionResolver);
        xpathObj.setNamespaceContext(testCase.nsContext);

        if(xpathInfo.forEach==null)
            results.add(xpathObj.evaluate(xpathInfo.xpath, doc, xpathInfo.resultType));
        else{
            List<Object> list = new ArrayList<Object>();
            NodeList nodeList = (NodeList)xpathObj.evaluate(xpathInfo.forEach, doc, XPathConstants.NODESET);
            for(int i=0; i<nodeList.getLength(); i++){
                Object context = nodeList.item(i);
                list.add(xpathObj.evaluate(xpathInfo.xpath, context, xpathInfo.resultType));
            }
            results.add(list);
        }
    }
    return results;
}
 
Example 5
Source File: XPathTableModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
public XPathTableModel( final ResourceData xmlResource,
                        final ResourceManager resourceManager,
                        final String xPathExpression,
                        final DataRow parameters,
                        final int maxRowsToProcess )
  throws ReportDataFactoryException {
  try {
    columnTypes = new ArrayList<Class>();

    final XPath xPath = XPathFactory.newInstance().newXPath();
    xPath.setXPathVariableResolver( new InternalXPathVariableResolver( parameters ) );

    // load metadata (number of rows, row names, row types)

    final String nodeValue = computeColDeclaration( xmlResource, resourceManager, xPath );
    if ( nodeValue != null ) {
      final StringTokenizer stringTokenizer = new StringTokenizer( nodeValue, "," );
      while ( stringTokenizer.hasMoreTokens() ) {
        final String className = stringTokenizer.nextToken();
        if ( SUPPORTED_TYPES.containsKey( className ) ) {
          columnTypes.add( SUPPORTED_TYPES.get( className ) );
        } else {
          columnTypes.add( String.class );
        }
      }
    }

    if ( maxRowsToProcess == -1 ) {
      dataLimit = Integer.MAX_VALUE;
    } else {
      this.dataLimit = Math.min( 1, maxRowsToProcess );
    }

    backend = new TypedTableModel();
    final LinkedHashMap<String, String> results = new LinkedHashMap<String, String>();
    // try to find all valid column names
    // visit all entries and add the names as we find them
    final NodeList rows = evaluateNodeList( xPath, xPathExpression, xmlResource, resourceManager );
    for ( int r = 0; r < rows.getLength(); r++ ) {
      // Get the next value from the result sequence
      final Node rowValue = rows.item( r );

      final short nodeType = rowValue.getNodeType();
      // Print this value
      if ( nodeType == Node.ELEMENT_NODE ) {
        // explodes into columns ..
        if ( processNode( rowValue, results, backend ) == false ) {
          return;
        }
      } else {
        final String columnName = rowValue.getNodeValue();
        results.put( columnName, rowValue.toString() );
        if ( addRow( results, backend ) == false ) {
          return;
        }
        results.clear();
      }
      //     System.out.println("NodeType: " + nodeType + "\n" + value.toString());
    }
  } catch ( Exception e ) {
    throw new ReportDataFactoryException( "Failed to query XPath datasource", e );
  }
}