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

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

Introduction

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

Prototype

public abstract JXPathContext getRelativeContext(Pointer pointer);

Source Link

Document

Returns a JXPathContext that is relative to the current JXPathContext.

Usage

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

/**
 * Fill collection set.//from   w  w w . j ava 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./*from   ww  w  . j  a v a 2s .c o m*/
 *
 * @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.xchain.framework.jxpath.JXPathContextTest.java

@Test
public void testRelativeContext() throws Exception {
    Node root = new Node("root");
    Node child = new Node("child");
    root.getChild().add(child);/*from w ww  .j  a  v  a  2 s.c om*/

    JXPathContext rootContext = JXPathContext.newContext(root);

    JXPathContext childContext = rootContext.getRelativeContext(rootContext.getPointer("/child"));

    String rootName = (String) childContext.getValue("/name");
    assertEquals("The root node has the wrong name.", "root", rootName);

    String childName = (String) childContext.getValue("name");
    assertEquals("The context node has the wrong name.", "child", childName);
}

From source file:org.xchain.framework.lifecycle.Execution.java

/**
 * <p>Signals that we are creating a local context for context bean
 * that has the same variable and function scope as the last context
 * bean.</p>//w  w  w  .jav a 2s .  co  m
 * 
 * <p>The user can safely call this method.</p>
 * 
 * @param context the current local context.
 * @param contextPointer A Pointer to the new context bean.
 * 
 * @return the new local context that shares variables and namespace context with the previous local context,
 * but it has a new context bean.
 */
public static JXPathContext startContextPointer(JXPathContext context, Pointer contextPointer) {
    // make sure that this is the current local context.
    testCurrentLocalContext(context);

    // create the relative context.
    JXPathContext localContext = context.getRelativeContext(contextPointer);

    // push the context onto the stack.
    chainContextStack.push(localContext);

    // return the new local context.
    return localContext;
}

From source file:pt.webdetails.cdf.dd.datasources.CdaDataSourceReader.java

protected static List<CdaDataSource> getCdaDataSources(JXPathContext docContext) {
    ArrayList<CdaDataSource> dataSources = new ArrayList<CdaDataSource>();
    //external/*from w w w  .ja v  a 2  s . c  om*/
    @SuppressWarnings("unchecked")
    Iterator<Pointer> extDataSources = docContext
            .iteratePointers("/datasources/rows[properties/name='dataAccessId']");
    while (extDataSources.hasNext()) {
        Pointer source = extDataSources.next();
        if (!(source instanceof NullPointer)) {
            dataSources.add(new CdaDataSource(docContext.getRelativeContext(source)));
        }
    }

    @SuppressWarnings("unchecked")
    Iterator<Pointer> builtInDataSources = docContext.iteratePointers("/datasources/rows[meta='CDA']");
    if (builtInDataSources.hasNext()) {
        //built-in
        String fileName = XPathUtils.getStringValue(docContext, "/filename");
        if (StringUtils.endsWith(fileName, ".wcdf")) {
            fileName = StringUtils.replace(fileName, ".wcdf", ".cda");
        } else {
            fileName = StringUtils.replace(fileName, ".cdfde", ".cda");
        }
        //just add cda name
        dataSources.add(new CdaDataSource(fileName, null));
    }

    return dataSources;
}

From source file:pt.webdetails.cdf.dd.datasources.DataSourceReader.java

private static List<CdaDataSource> getCdaDataSources(JXPathContext docContext) {

    ArrayList<CdaDataSource> dataSources = new ArrayList<CdaDataSource>();
    //external//from w ww.ja va 2s  .com
    @SuppressWarnings("unchecked")
    Iterator<Pointer> extDataSources = docContext
            .iteratePointers("/datasources/rows[properties/name='dataAccessId']");
    while (extDataSources.hasNext()) {
        Pointer source = extDataSources.next();
        if (!(source instanceof NullPointer)) {
            dataSources.add(new CdaDataSource(docContext.getRelativeContext(source)));
        }
    }

    @SuppressWarnings("unchecked")
    Iterator<Pointer> builtInDataSources = docContext.iteratePointers("/datasources/rows[meta='CDA']");
    if (builtInDataSources.hasNext()) {
        //built-in
        String fileName = XPathUtils.getStringValue(docContext, "/filename");
        String toReplace = ".cdfde";
        String replaceWith = ".cda";
        if (StringUtils.endsWith(fileName, ".wcdf")) {
            toReplace = ".wcdf";
        }
        fileName = StringUtils.replace(fileName, toReplace, replaceWith);
        //just add cda name
        dataSources.add(new CdaDataSource(fileName, null));
        //      
        //  
        //      while(builtInDataSources.hasNext()){
        //        Pointer source = builtInDataSources.next();
        //        if(!(source instanceof NullPointer)){
        //          dataSources.add(new CdaDataSource(docContext.getRelativeContext(source), fileName));
        //        }
        //      }
    }

    return dataSources;
}

From source file:pt.webdetails.cdf.dd.model.inst.reader.cdfdejs.CdfdeJsDashboardReader.java

private void readKind(Dashboard.Builder builder, String thingKind, JXPathContext source,
        Iterator<Pointer> componentPointers, CdfdeJsReadContext context, String sourcePath)
        throws ThingReadException {
    while (componentPointers.hasNext()) {
        Pointer componentPointer = componentPointers.next();
        JXPathContext compXP = source.getRelativeContext(componentPointer);

        String className = (String) compXP.getValue("type");

        // Ignore label components (it's OK for current needs)
        if (className == null || !className.equalsIgnoreCase("label")) {
            IThingReader reader;/*from  w  ww.j a  va2  s.c o  m*/
            try {
                reader = context.getFactory().getReader(thingKind, className, null);
            } catch (UnsupportedThingException ex) {
                logger.error("While rendering dashboard. " + ex);
                continue;
            }

            Component.Builder compBuilder = (Component.Builder) reader.read(context, compXP, sourcePath);

            builder.addComponent(compBuilder);
        }
    }
}

From source file:pt.webdetails.cdf.dd.render.RenderLayout.java

private void renderRows(final JXPathContext doc, final Iterator nodeIterator,
        final Map<String, CdfRunJsDashboardWriteResult> widgetsByContainerId, final String alias,
        final StringBuffer layout, final int indent) throws Exception {
    while (nodeIterator.hasNext()) {
        final Pointer pointer = (Pointer) nodeIterator.next();
        final JXPathContext context = doc.getRelativeContext(pointer);

        final String rowId = (String) context.getValue("id");
        final String rowName = XPathUtils.getStringValue(context, "properties[name='name']/value");

        final Render renderer = (Render) getRender(context);
        renderer.processProperties();/*from  w  ww .j ava2s . co m*/
        renderer.aliasId(alias);
        // when rendering rows for the layout of a dashboard AMD module, skip NEWLINE and indentation
        if (indent > -1) {
            layout.append(NEWLINE).append(getIndent(indent)).append(renderer.renderStart());
            if (widgetsByContainerId != null && widgetsByContainerId.containsKey(rowName)) {
                CdfRunJsDashboardWriteResult widgetResult = widgetsByContainerId.get(rowName);
                layout.append(widgetResult.getLayout());
            } else {
                renderRows(context, context.iteratePointers(MessageFormat.format(XPATH_FILTER, rowId, "")),
                        widgetsByContainerId, alias, layout, indent + 2);
            }
            layout.append(NEWLINE).append(getIndent(indent)).append(renderer.renderClose());
        } else {
            layout.append(renderer.renderStart());
            if (widgetsByContainerId != null && widgetsByContainerId.containsKey(rowName)) {
                CdfRunJsDashboardWriteResult widgetResult = widgetsByContainerId.get(rowName);
                layout.append(widgetResult.getLayout());
            } else {
                renderRows(context, context.iteratePointers(MessageFormat.format(XPATH_FILTER, rowId, "")),
                        widgetsByContainerId, alias, layout, -1);
            }
            layout.append(renderer.renderClose());
        }
    }
}

From source file:pt.webdetails.cdf.dd.render.RenderMobileLayout.java

private void renderRows(final JXPathContext doc, final Iterator<Pointer> nodeIterator,
        final StringBuffer layout, final int ident) throws Exception {
    while (nodeIterator.hasNext()) {
        final Pointer pointer = nodeIterator.next();
        final JXPathContext context = doc.getRelativeContext(pointer);
        final String rowId = (String) context.getValue("id");
        final Render renderer = (Render) getRender(context);

        renderer.processProperties();/*from   w ww . ja va  2s  . c o  m*/

        layout.append(NEWLINE).append(getIndent(ident));
        layout.append(renderer.renderStart());

        // Render Child Rows
        renderRows(context, context.iteratePointers(MessageFormat.format(XPATH_FILTER, rowId)), layout,
                ident + 2);

        layout.append(NEWLINE).append(getIndent(ident));
        layout.append(renderer.renderClose());
    }
}