org.apache.commons.jxpath.JXPathContext Java Examples

The following examples show how to use org.apache.commons.jxpath.JXPathContext. 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: JXPathContextReferenceImpl.java    From commons-jxpath with Apache License 2.0 6 votes vote down vote up
/**
 * Get the named Function.
 * @param functionName name
 * @param parameters function args
 * @return Function
 */
public Function getFunction(QName functionName, Object[] parameters) {
    String namespace = functionName.getPrefix();
    String name = functionName.getName();
    JXPathContext funcCtx = this;
    Function func;
    Functions funcs;
    while (funcCtx != null) {
        funcs = funcCtx.getFunctions();
        if (funcs != null) {
            func = funcs.getFunction(namespace, name, parameters);
            if (func != null) {
                return func;
            }
        }
        funcCtx = funcCtx.getParentContext();
    }
    throw new JXPathFunctionNotFoundException(
        "Undefined function: " + functionName.toString());
}
 
Example #2
Source File: SimplePathInterpreterTest.java    From commons-jxpath with Apache License 2.0 6 votes vote down vote up
protected void setUp() throws Exception {
    bean = TestBeanWithNode.createTestBeanWithDOM();
    HashMap submap = new HashMap();
    submap.put("key", new NestedTestBean("Name 9"));
    submap.put("strings", bean.getNestedBean().getStrings());
    bean.getList().add(new int[]{1, 2});
    bean.getList().add(bean.getVendor());
    bean.getMap().put("Key3",
        new Object[]{
            new NestedTestBean("some"),
            new Integer(2),
            bean.getVendor(),
            submap
        }
    );
    bean.getMap().put("Key4", bean.getVendor());
    bean.getMap().put("Key5", submap);
    bean.getMap().put("Key6", new Object[0]);
    context = JXPathContext.newContext(null, bean);
    context.setLenient(true);
    context.setFactory(new TestBeanFactory());
}
 
Example #3
Source File: JXPathServletContexts.java    From commons-jxpath with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a JXPathContext bound to the "session" scope. Caches that context
 * within the session itself.
 * @param session as described
 * @param servletContext operative
 * @return JXPathContext
 */
public static JXPathContext getSessionContext(HttpSession session,
        ServletContext servletContext) {
    JXPathContext context =
        (JXPathContext) session.getAttribute(Constants.JXPATH_CONTEXT);
    if (context == null) {
        JXPathContext parentContext = getApplicationContext(servletContext);
        HttpSessionAndServletContext handle =
            new HttpSessionAndServletContext(session, servletContext);
        context = factory.newContext(parentContext, handle);
        context.setVariables(
            new KeywordVariables(Constants.SESSION_SCOPE, handle));
        session.setAttribute(Constants.JXPATH_CONTEXT, context);
    }
    return context;
}
 
Example #4
Source File: StressTest.java    From commons-jxpath with Apache License 2.0 6 votes vote down vote up
public void testThreads() throws Throwable {
    context = JXPathContext.newContext(null, new Double(100));
    Thread[] threadArray = new Thread[THREAD_COUNT];
    for (int i = 0; i < THREAD_COUNT; i++) {
        threadArray[i] = new Thread(new StressRunnable());
    }
    
    for (int i = 0; i < threadArray.length; i++) {
        threadArray[i].start();
    }

    for (int i = 0; i < threadArray.length; i++) {
        try {
            threadArray[i].join();
        }
        catch (InterruptedException e) {
            assertTrue("Interrupted", false);
        }
    }

    if (exception != null) {
        throw exception;
    }
    assertEquals("Test count", THREAD_COUNT * THREAD_DURATION, count);
}
 
Example #5
Source File: ContainerModelTest.java    From commons-jxpath with Apache License 2.0 6 votes vote down vote up
public void testContainerMapWithCollection() {
    ListContainer container = new ListContainer();
    List list = (List) container.getValue();
            
    Map map = new HashMap();
    map.put("container", container);
    
    JXPathContext context = JXPathContext.newContext(map);
    
    assertXPathValueAndPointer(context, "/container", 
            list, "/.[@name='container']");
    assertXPathValueAndPointer(context, "/container[1]",
            list.get(0), "/.[@name='container'][1]");
    assertXPathValueAndPointer(context, "/container[2]",
            list.get(1), "/.[@name='container'][2]");
    
    assertXPathSetValue(context, "/container[1]", "baz");
    assertEquals("Checking setValue(index)", "baz", list.get(0));
}
 
Example #6
Source File: TestXPathExpressionEngine.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if the JXPathContext is correctly initialized with the node pointer
 * factory.
 */
@Test
public void testNodePointerFactory()
{
    JXPathContext.newContext(this);
    final NodePointerFactory[] factories =
            JXPathContextReferenceImpl.getNodePointerFactories();
    boolean found = false;
    for (final NodePointerFactory factory : factories)
    {
        if (factory instanceof ConfigurationNodePointerFactory)
        {
            found = true;
        }
    }
    assertTrue("No configuration pointer factory found", found);
}
 
Example #7
Source File: TestDOMFactory.java    From commons-jxpath with Apache License 2.0 6 votes vote down vote up
/**
 * Return <b>false</b> if this factory cannot create the requested object.
 */
public boolean createObject(
    JXPathContext context,
    Pointer pointer,
    Object parent,
    String name,
    int index) 
{
    if (name.equals("location")
        || name.equals("address")
        || name.equals("street")) {
        addDOMElement((Node) parent, index, name, null);
        return true;
    }
    if (name.startsWith("price:")) {
        String namespaceURI = context.getNamespaceURI("price");
        addDOMElement((Node) parent, index, name, namespaceURI);
        return true;
    }
    return false;
}
 
Example #8
Source File: VariablePointer.java    From commons-jxpath with Apache License 2.0 6 votes vote down vote up
public NodePointer createChild(
    JXPathContext context,
    QName name,
    int index) {
    Object collection = createCollection(context, index);
    if (!isActual() || (index != 0 && index != WHOLE_COLLECTION)) {
        AbstractFactory factory = getAbstractFactory(context);
        boolean success =
            factory.createObject(
                context,
                this,
                collection,
                getName().toString(),
                index);
        if (!success) {
            throw new JXPathAbstractFactoryException(
                    "Factory could not create object path: " + asPath());
        }
        NodePointer cln = (NodePointer) clone();
        cln.setIndex(index);
        return cln;
    }
    return this;
}
 
Example #9
Source File: JXPathServletContexts.java    From commons-jxpath with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a JXPathContext bound to the "page" scope. Caches that context
 * within the PageContext itself.
 * @param pageContext as described
 * @return JXPathContext
 */
public static JXPathContext getPageContext(PageContext pageContext) {
    JXPathContext context =
        (JXPathContext) pageContext.getAttribute(Constants.JXPATH_CONTEXT);
    if (context == null) {
        JXPathContext parentContext =
            getRequestContext(
                pageContext.getRequest(),
                pageContext.getServletContext());
        context = factory.newContext(parentContext, pageContext);
        context.setVariables(
            new KeywordVariables(
                Constants.PAGE_SCOPE,
                new PageScopeContext(pageContext)));
        pageContext.setAttribute(Constants.JXPATH_CONTEXT, context);
    }
    return context;
}
 
Example #10
Source File: JXPathServletContexts.java    From commons-jxpath with Apache License 2.0 6 votes vote down vote up
/**
 * Returns  a JXPathContext bound to the "application" scope. Caches that
 * context within the servlet context itself.
 * @param servletContext operative
 * @return JXPathContext
 */
public static JXPathContext getApplicationContext(
        ServletContext servletContext) {
    JXPathContext context =
        (JXPathContext) servletContext.getAttribute(
            Constants.JXPATH_CONTEXT);
    if (context == null) {
        context = factory.newContext(null, servletContext);
        context.setVariables(
            new KeywordVariables(
                Constants.APPLICATION_SCOPE,
                servletContext));
        servletContext.setAttribute(Constants.JXPATH_CONTEXT, context);
    }
    return context;
}
 
Example #11
Source File: AssertionUtils.java    From cougar with Apache License 2.0 6 votes vote down vote up
private static void doJsonSorting(JSONObject doc, String x) throws XPathExpressionException, IOException, JSONException {
    JXPathContext ctx = JXPathContext.newContext(doc);
    String parentX = x.substring(0,x.lastIndexOf("/"));
    if ("".equals(parentX)) {
        parentX = "/";
    }
    String childName = x.substring(x.lastIndexOf("/")+1);
    Iterator it = ctx.iterate(parentX);
    while (it.hasNext()) {
        JSONObject p = (JSONObject) it.next();
        JSONArray n = p.getJSONArray(childName);
        List allKids = new ArrayList<>(n.length());
        for (int j=0; j<n.length(); j++) {
            allKids.add(n.get(j));
        }
        Collections.sort(allKids, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(o2.toString());
            }
        });
        JSONArray newArray = new JSONArray(allKids);
        p.put(childName,newArray);
    }
}
 
Example #12
Source File: NullPointer.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
public NodePointer createPath(JXPathContext context, Object value) {
    if (parent != null) {
        return parent.createPath(context, value).getValuePointer();
    }
    throw new UnsupportedOperationException(
        "Cannot create the root object: " + asPath());
}
 
Example #13
Source File: JXPath172Test.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
public void testIssue172_PropertyUnexisting()
{
    final JXPathContext context = getContext(null, true);
    final Object bRet = context.selectSingleNode("unexisting");
    assertNull("not null!!", bRet);

    final Pointer pointer = context.getPointer("unexisting");
    assertNotNull(pointer);
    assertEquals(NullPropertyPointer.class, pointer.getClass());
    assertNull(pointer.getValue());
}
 
Example #14
Source File: JXPath172DynamicTest.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
/**
 * Helper, returns a {@link JXPathContext} filled with a Map whose "value"
 * key is associated to the passed <code>val</code> value.
 * 
 * @param val
 * @return A {@link JXPathContext}, never <code>null</code>.
 */
private JXPathContext getContext(final String val, boolean lenient)
{
    final HashMap map = new HashMap();
    // if (val!=null) // no diffs
    map.put("value", val);
    final Object target = map;
    final JXPathContext context = JXPathContext.newContext(null, target);
    context.setLenient(lenient);
    return context;
}
 
Example #15
Source File: PropertyPointer.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
public NodePointer createChild(
    JXPathContext context,
    QName name,
    int index) {
    PropertyPointer prop = (PropertyPointer) clone();
    if (name != null) {
        prop.setPropertyName(name.toString());
    }
    prop.setIndex(index);
    return prop.createPath(context);
}
 
Example #16
Source File: PropertyPointer.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
public NodePointer createChild(
    JXPathContext context,
    QName name,
    int index,
    Object value) {
    PropertyPointer prop = (PropertyPointer) clone();
    if (name != null) {
        prop.setPropertyName(name.toString());
    }
    prop.setIndex(index);
    return prop.createPath(context, value);
}
 
Example #17
Source File: BeanModelTestCase.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
/**
 * Test contributed by Kate Dvortsova
 */
public void testIteratePointerSetValue() {
    JXPathContext context = JXPathContext.newContext(createContextBean());

    assertXPathValue(context, "/beans[1]/name", "Name 1");
    assertXPathValue(context, "/beans[2]/name", "Name 2");

    // Test setting via context
    context.setValue("/beans[2]/name", "Name 2 set");
    assertXPathValue(context, "/beans[2]/name", "Name 2 set");

    // Restore original value
    context.setValue("/beans[2]/name", "Name 2");
    assertXPathValue(context, "/beans[2]/name", "Name 2");

    int iterCount = 0;
    Iterator iter = context.iteratePointers("/beans/name");
    while (iter.hasNext()) {
        iterCount++;
        Pointer pointer = (Pointer) iter.next();
        String s = (String) pointer.getValue();
        s = s + "suffix";
        pointer.setValue(s);
        assertEquals("pointer.getValue", s, pointer.getValue());
        // fails right here, the value isn't getting set in the bean.
        assertEquals(
            "context.getValue",
            s,
            context.getValue(pointer.asPath()));
    }
    assertEquals("Iteration count", 2, iterCount);

    assertXPathValue(context, "/beans[1]/name", "Name 1suffix");
    assertXPathValue(context, "/beans[2]/name", "Name 2suffix");
}
 
Example #18
Source File: CollectionPointer.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
public NodePointer createChild(
    JXPathContext context,
    QName name,
    int index) {
    NodePointer ptr = (NodePointer) clone();
    ptr.setIndex(index);
    return ptr.createPath(context);
}
 
Example #19
Source File: JXPath172DynamicTest.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
public void testIssue172_propertyExistAndIsNotNull()
{
    final JXPathContext context = getContext("ciao", false);
    final Object bRet = context.selectSingleNode("value");
    assertNotNull("null!!", bRet);
    assertEquals("Is " + bRet.getClass(), "ciao", bRet);

    final Pointer pointer = context.getPointer("value");
    assertNotNull(pointer);
    assertEquals(DynamicPropertyPointer.class, pointer.getClass());
    assertEquals("ciao", pointer.getValue());
}
 
Example #20
Source File: TestXPathExpressionEngine.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests an add operation with a query that does not return a single node.
 */
@Test(expected = IllegalArgumentException.class)
public void testPrepareAddInvalidParent()
{
    final JXPathContext ctx = expectSelect();
    final XPathExpressionEngine engine = setUpEngine(ctx);
    engine.prepareAdd(root, TEST_KEY + " test", handler);
}
 
Example #21
Source File: CoreFunctionTest.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
public void setUp() {
    if (context == null) {
        context = JXPathContext.newContext(new TestMixedModelBean());
        Variables vars = context.getVariables();
        vars.declareVariable("nan", Double.NaN);
        vars.declareVariable("bool_true", Boolean.TRUE);
        vars.declareVariable("bool_false", Boolean.FALSE);
    }
}
 
Example #22
Source File: NullPointer.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
public NodePointer createPath(JXPathContext context) {
    if (parent != null) {
        return parent.createPath(context).getValuePointer();
    }
    throw new UnsupportedOperationException(
        "Cannot create the root object: " + asPath());
}
 
Example #23
Source File: PropertyPointer.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
public NodePointer createPath(JXPathContext context, Object value) {
    // If neccessary, expand collection
    if (index != WHOLE_COLLECTION && index >= getLength()) {
        createPath(context);
    }
    setValue(value);
    return this;
}
 
Example #24
Source File: TestXPathExpressionEngine.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests adding a complete path whose final node is an attribute.
 */
@Test
public void testPrepareAddAttributePath()
{
    final JXPathContext ctx = expectSelect(root);
    final XPathExpressionEngine engine = setUpEngine(ctx);
    final NodeAddData<ImmutableNode> data =
            engine.prepareAdd(root, TEST_KEY + " a/full/path@attr", handler);
    checkAddPath(data, true, "a", "full", "path", "attr");
}
 
Example #25
Source File: CoreFunction.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
/**
 * id() implementation.
 * @param context evaluation context
 * @return Pointer
 */
protected Object functionID(EvalContext context) {
    assertArgCount(1);
    String id = InfoSetUtil.stringValue(getArg1().computeValue(context));
    JXPathContext jxpathContext = context.getJXPathContext();
    NodePointer pointer = (NodePointer) jxpathContext.getContextPointer();
    return pointer.getPointerByID(jxpathContext, id);
}
 
Example #26
Source File: TestXPathExpressionEngine.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests adding a single child node.
 */
@Test
public void testPrepareAddNode()
{
    final JXPathContext ctx = expectSelect(root);
    final XPathExpressionEngine engine = setUpEngine(ctx);
    final NodeAddData<ImmutableNode> data =
            engine.prepareAdd(root, TEST_KEY + "  newNode", handler);
    checkAddPath(data, false, "newNode");
}
 
Example #27
Source File: TestXPathExpressionEngine.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests a query that has no results. This should return an empty list.
 */
@Test
public void testQueryWithoutResult()
{
    final JXPathContext ctx = expectSelect();
    final XPathExpressionEngine engine = setUpEngine(ctx);
    assertTrue("Got results", engine.query(root, TEST_KEY, handler)
            .isEmpty());
}
 
Example #28
Source File: BeanModelTestCase.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
public void testRelativeContextInheritance() {
    context.setFunctions(new ClassFunctions(TestFunctions.class, "test"));
    JXPathContext relative =
        context.getRelativeContext(context.getPointer("nestedBean"));
    
    assertXPathValue(relative, 
        "test:countPointers(strings)", 
        new Integer(3));
}
 
Example #29
Source File: TestXPathExpressionEngine.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the query() method with an expression yielding a node.
 */
@Test
public void testQueryNodeExpression()
{
    final JXPathContext ctx = expectSelect(root);
    final XPathExpressionEngine engine = setUpEngine(ctx);
    final List<QueryResult<ImmutableNode>> result =
            engine.query(root, TEST_KEY, handler);
    assertEquals("Incorrect number of results", 1, result.size());
    assertSame("Wrong result node", root, result.get(0).getNode());
    assertFalse("No node result", result.get(0).isAttributeResult());
}
 
Example #30
Source File: JXPath149Test.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
public void testComplexOperationWithVariables() {
    JXPathContext context = JXPathContext.newContext(null);
    context.getVariables().declareVariable("a", Integer.valueOf(0));
    context.getVariables().declareVariable("b", Integer.valueOf(0));
    context.getVariables().declareVariable("c", Integer.valueOf(1));
    assertXPathValue(context, "$a + $b <= $c", Boolean.TRUE);
}