Example usage for org.apache.commons.jxpath JXPathContext newContext

List of usage examples for org.apache.commons.jxpath JXPathContext newContext

Introduction

In this page you can find the example usage for org.apache.commons.jxpath JXPathContext newContext.

Prototype

public static JXPathContext newContext(Object contextBean) 

Source Link

Document

Creates a new JXPathContext with the specified object as the root node.

Usage

From source file:org.opennms.protocols.json.collector.AbstractJsonCollectionHandler.java

/**
 * Fill collection set./*from   w  w  w  . jav a  2 s.  com*/
 *
 * @param agent the agent
 * @param collectionSet the collection set
 * @param source the source
 * @param json the JSON Object
 * @throws ParseException the parse exception
 */
@SuppressWarnings("unchecked")
protected void fillCollectionSet(CollectionAgent agent, XmlCollectionSet collectionSet, XmlSource source,
        JSONObject json) throws ParseException {
    XmlCollectionResource nodeResource = new XmlSingleInstanceCollectionResource(agent);
    JXPathContext context = JXPathContext.newContext(json);
    for (XmlGroup group : source.getXmlGroups()) {
        LOG.debug("fillCollectionSet: getting resources for XML group {} using XPATH {}", group.getName(),
                group.getResourceXpath());
        Date timestamp = getTimeStamp(context, group);
        Iterator<Pointer> itr = context.iteratePointers(group.getResourceXpath());
        while (itr.hasNext()) {
            JXPathContext relativeContext = context.getRelativeContext(itr.next());
            String resourceName = getResourceName(relativeContext, group);
            LOG.debug("fillCollectionSet: processing XML resource {} of type {}", resourceName,
                    group.getResourceType());
            XmlCollectionResource collectionResource;
            if (group.getResourceType().equalsIgnoreCase(CollectionResource.RESOURCE_TYPE_NODE)) {
                collectionResource = nodeResource;
            } else {
                collectionResource = getCollectionResource(agent, resourceName, group.getResourceType(),
                        timestamp);
            }
            LOG.debug("fillCollectionSet: processing resource {}", collectionResource);
            AttributeGroupType attribGroupType = new AttributeGroupType(group.getName(), group.getIfType());
            for (XmlObject object : group.getXmlObjects()) {
                try {
                    Object obj = relativeContext.getValue(object.getXpath());
                    if (obj != null) {
                        String value = obj.toString();
                        XmlCollectionAttributeType attribType = new XmlCollectionAttributeType(object,
                                attribGroupType);
                        collectionResource.setAttributeValue(attribType, value);
                    }
                } catch (JXPathException ex) {
                    LOG.warn("Unable to get value for {}: {}", object.getXpath(), ex.getMessage());
                }
            }
            processXmlResource(collectionResource, attribGroupType);
            collectionSet.getCollectionResources().add(collectionResource);
        }
    }
}

From source file:org.opennms.protocols.json.collector.JsonCollectorSolarisZonesIT.java

/**
 * Test to verify XPath content./*www.j  a  v  a2  s . c om*/
 *
 * @throws Exception the exception
 */
@Test
@SuppressWarnings("unchecked")
public void testXpath() throws Exception {
    JSONObject json = MockDocumentBuilder.getJSONDocument();
    JXPathContext context = JXPathContext.newContext(json);
    Iterator<Pointer> itr = context.iteratePointers("/zones/zone");
    while (itr.hasNext()) {
        Pointer resPtr = itr.next();
        JXPathContext relativeContext = context.getRelativeContext(resPtr);
        String resourceName = (String) relativeContext.getValue("@name");
        Assert.assertNotNull(resourceName);
        String value = (String) relativeContext.getValue("parameter[@key='nproc']/@value");
        Assert.assertNotNull(Integer.valueOf(value));
    }
}

From source file:org.openvpms.component.business.service.archetype.helper.lookup.AbstractLookupAssertion.java

/**
 * Evaluates a jxpath to return its value.
 *
 * @param context the context object//w  w  w . jav a 2s.c  o  m
 * @param path    the jxpath
 * @return the value of the jxpath
 */
protected String getPathValue(IMObject context, String path) {
    return (String) JXPathContext.newContext(context).getValue(path);
}

From source file:org.openvpms.component.system.common.jxpath.JXPathHelper.java

/**
 * Create a new context for the specified object that has access to the supplied functions.
 *
 * @param object    the context bean//from   w ww . j a v  a2s. com
 * @param functions the functions
 * @return JXPathContext the context object
 */
public static JXPathContext newContext(Object object, Functions functions) {
    JXPathContext context = JXPathContext.newContext(object);
    FunctionLibrary lib = new FunctionLibrary();
    lib.addFunctions(context.getFunctions());
    lib.addFunctions(functions);
    context.setFunctions(lib);
    context.setLenient(true);

    return context;
}

From source file:org.openvpms.web.echo.style.StylePropertyEvaluator.java

/**
 * Returns properties for the specified screen resolution.
 * <p/>/*from  w w  w  . jav  a2s. c  o m*/
 * The <tt>width</tt> and <tt>height</tt> are used to declare the <em>$width</em> and <em>$height</em> variables
 * respectively.
 * The <em>$font.size</em> variable is obtained from <tt>properties</tt> if set, or the default properties if not.
 *
 * @param width      the screen width
 * @param height     the screen height
 * @param properties properties to override the defaults. May be <tt>null</tt>
 * @return properties for the screen resolution
 */
public Map<String, String> getProperties(int width, int height, Map<String, String> properties) {
    Map<String, String> result = new HashMap<String, String>(defaults);
    if (properties != null) {
        result.putAll(properties);
    }
    JXPathContext context = JXPathContext.newContext(new Object());
    Variables variables = context.getVariables();
    variables.declareVariable("width", width);
    variables.declareVariable("height", height);
    evaluateAndDeclare(FONT_SIZE, result, context);
    evaluateAndDeclare(FONT_H4_SIZE, result, context);
    evaluateAndDeclare(PADDING_LARGE, result, context);
    evaluateAndDeclare(PADDING_MEDIUM, result, context);
    evaluateAndDeclare(PADDING_SMALL, result, context);
    evaluateAndDeclare(PADDING_SMALLER, result, context);
    evaluateAndDeclare(PADDING_TINY, result, context);

    evaluate(result, context);
    return result;
}

From source file:org.paxle.tools.ieporter.cm.impl.ConfigurationIEPorterTest.java

public void testExportConfiguration() throws ParserConfigurationException {
    final Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put("myProperty.Integer", Integer.valueOf(1));
    props.put("myProperty.intArray", new int[] { 1, 2, 3, 4 });
    props.put("myProperty.String", "test");
    props.put("myProperty.StringArray", new String[] { "test1", "test2", "test3" });

    final Configuration config = mock(Configuration.class);
    checking(new Expectations() {
        {/*from  ww  w . j a  va2 s  .  c om*/
            atLeast(1).of(config).getPid();
            will(returnValue("testPid"));
            atLeast(1).of(config).getProperties();
            will(returnValue(props));
            never(config);
        }
    });

    Map<String, Document> configs = this.ieporter.exportConfiguration(config);
    assertNotNull(configs);
    assertEquals(1, configs.size());
    assertTrue(configs.containsKey("testPid"));

    Document doc = configs.get("testPid");
    assertNotNull(doc);
    JXPathContext objContext = JXPathContext.newContext(doc);
    assertEquals("testPid", objContext.getValue("//service.pid"));
    assertEquals(props.size(), ((Double) objContext.getValue("count(//property)")).intValue());
    assertEquals(props.get("myProperty.Integer").toString(),
            objContext.getValue("//property[@key='myProperty.Integer']/value"));
    assertEquals(Array.getLength(props.get("myProperty.intArray")),
            ((Double) objContext.getValue("count(//property[@key='myProperty.intArray']/values/value)"))
                    .intValue());
    assertEquals(props.get("myProperty.String").toString(),
            objContext.getValue("//property[@key='myProperty.String']/value"));
    assertEquals(Array.getLength(props.get("myProperty.StringArray")),
            ((Double) objContext.getValue("count(//property[@key='myProperty.StringArray']/values/value)"))
                    .intValue());
}

From source file:org.paxml.core.Context.java

/**
 * Select objects with xpath.//w  w  w  .  j  a  v  a2  s . c o  m
 * 
 * @param from
 *            the object to select properties from, null to select from
 *            entire context.
 * @param xpath
 *            the xpath
 * @param alwaysList
 *            true to return a list with one item inside if the xpath
 *            results in one object to be selected.
 * @return either a list of objects that satisfies the xpath, or the object
 *         itself if the xpath results in one object to be selected and the
 *         "alwaysList" parameter is false.
 */
public Object xpathSelect(Object from, String xpath, boolean alwaysList) {
    Variables vars = new BasicVariables();

    if (from == null) {
        ObjectTree nameGlobal = getRootContext().getNameMap(false, true);
        ObjectTree nameLocal = getNameMap(true, false);

        vars.declareVariable(XPATH_NAME_GLOBAL_VAR, nameGlobal);
        vars.declareVariable(XPATH_NAME_LOCAL_VAR, nameLocal);

        ObjectTree nameAuto = new ObjectTree(null, nameGlobal);
        nameAuto.addValues(nameLocal);

        from = nameAuto;
    }

    JXPathContext xpathContext = JXPathContext.newContext(from);
    xpathContext.setVariables(vars);
    xpathContext.setIdentityManager(this);

    setXpathFunctions(xpathContext);

    try {
        Object selected = xpathContext.iterate(xpath);

        List<Object> list = new ArrayList<Object>(1);
        if (selected instanceof Iterator) {
            final Iterator<?> it = (Iterator<?>) selected;
            while (it.hasNext()) {
                Object obj = it.next();
                list.add(getXpathResultObject(obj));
            }
            if (list.size() == 1) {
                selected = list.get(0);
            } else {
                selected = list;
            }
        } else {

            selected = getXpathResultObject(selected);

            if (selected != null && alwaysList) {
                list.add(selected);
            }
        }
        if (alwaysList) {
            return list;
        } else {
            if (selected instanceof List) {
                list = (List) selected;
                final int size = list.size();
                if (size == 0) {
                    return null;
                } else if (size == 1) {
                    return list.get(0);
                }
            }
            return selected;
        }
    } catch (NullPointerException e) {
        // when jxpath throws null pointer exception, it has problem
        // searching non-existing paths
        return null;
    }
}

From source file:org.prevayler.demos.jxpath.Main.java

/**
 * Lists an object graph using an XPath expression.
 * /*w  w w  . j  a v a2s.  co m*/
 * @param prevayler PrevalentSystem to query
 * @param xpathExp XPath expression to use
 */
private static void list(Prevayler prevayler, String xpathExp) {
    System.out.println("Executing XPath expression...");

    ProjectManagementSystem pms = (ProjectManagementSystem) prevayler.prevalentSystem();
    JXPathContext context = JXPathContext.newContext(pms);
    Iterator i = context.iterate(xpathExp);

    while (i.hasNext()) {

        Object obj = (Object) i.next();
        System.out.println(obj.toString());
    }
}

From source file:org.romaframework.core.schema.SchemaHelper.java

/**
 * Returns the object of field in expression.
 * //from  ww w.java 2  s. com
 * @param iStartingObject
 *          Starting object to navigate
 * @param iExpression
 *          Path of field
 * @return
 */
public static Object getFieldObject(Object iStartingObject, String iExpression) {
    int lastSep = iExpression.lastIndexOf('.');
    if (lastSep == -1) {
        return iStartingObject;
    }

    String exp = iExpression.substring(0, lastSep);
    exp = exp.replace('.', '/');

    JXPathContext context = JXPathContext.newContext(iStartingObject);
    return context.getValue(exp);
}

From source file:org.solmix.datax.xmlfile.XmlFileDataService.java

@Override
protected DSResponse executeFetch(DSRequest req) throws DSCallException {
    OperationInfo oi = req.getOperationInfo();
    Object dataUrl = oi.getProperty("dataUrl");

    Object recordXPath = oi.getProperty("recordXPath");
    DSResponseImpl res = new DSResponseImpl(this, req);
    Object value = getDataFromFile(dataUrl);
    if (recordXPath != null) {
        JXPathContext context = JXPathContext.newContext(value);
        res.setRawData(context.getValue(recordXPath.toString()));
    } else {/*from   w  w  w  . j av a 2s  .com*/
        res.setRawData(value);
    }
    return res;
}