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

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

Introduction

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

Prototype

public abstract Object getValue(String xpath);

Source Link

Document

Evaluates the xpath and returns the resulting object.

Usage

From source file:org.onecmdb.core.utils.xpath.generator.CSVContentGenerator.java

public void transfer(OutputStream out) {
    log.debug("Debug Query path <" + cmd.getPath() + ">");
    PrintWriter text = new PrintWriter(new OutputStreamWriter(out), false);
    Iterator<Pointer> iter = cmd.getPathPointers();

    // Need to peek inside the iter.
    Pointer p = null;/*w  w  w. j  a  va  2 s  . c  om*/
    if (iter.hasNext()) {
        p = (Pointer) iter.next();
    }

    boolean first = true;

    String[] outputAttributes = cmd.getOutputAttributeAsArray();

    if (outputAttributes.length == 1 && outputAttributes[0].equals("*")) {
        // Expand all.
        if (p != null) {
            Object v = p.getValue();
            if (v instanceof IDynamicHandler) {
                IDynamicHandler dynBean = (IDynamicHandler) v;
                outputAttributes = dynBean.getProperties();
            }
        }
    }

    if (outputAttributes.length == 0) {
        out(text, cmd.getPath());
    } else {
        for (int i = 0; i < outputAttributes.length; i++) {
            String outAttr = outputAttributes[i];
            text.print(cmd.getPath() + "/" + outAttr);
            if (i < (outputAttributes.length - 1)) {
                out(text, delimiter);
            }
        }
    }

    outln(text, "");
    if (p != null) {
        do {
            if (p == null) {
                p = iter.next();
            }
            if (outputAttributes.length == 0) {
                out(text, p.getValue().toString());
            } else {
                for (int i = 0; i < outputAttributes.length; i++) {
                    String outputAttribute = outputAttributes[i];
                    if (false) {
                        JXPathContext context = cmd.getRelativeContext(p);

                        Object o = context.getValue(outputAttribute);
                        if (o != null) {
                            if (o instanceof List) {
                                if (((List) o).size() == 1) {
                                    o = ((List) o).get(0);
                                }
                            }
                            out(text, o.toString());
                        }
                    }
                    if (true) {
                        Iterator<Pointer> outputAttrPointersIter = cmd.getRelativePointers(p, outputAttribute);
                        while (outputAttrPointersIter.hasNext()) {
                            Pointer outputPointer = outputAttrPointersIter.next();
                            String value = outputPointer.getValue().toString();
                            out(text, value);
                            if (outputAttrPointersIter.hasNext()) {
                                out(text, ",");
                            }
                        }
                    }
                    if (i < (outputAttributes.length - 1)) {
                        out(text, delimiter);
                    }

                }
            }
            outln(text, "");
            p = null;
        } while (iter.hasNext());
    }
    text.flush();
}

From source file:org.openinfinity.core.aspect.ArgumentBuilder.java

/**
 * Executes field callbacks on found and defined attribute names.
 * //w ww.  j  a v  a2s  . c  om
 * @param argumentGatheringCallback Represents the actual callback method.
 * @param arguments Represents the arguments for method.
 * @param allowedFields Represents the allowed argument's field names.
 */
public void executeArgumentGatheringCallbackBasedOnDefinedFields(
        ArgumentGatheringFieldCallback<Field, Object> argumentGatheringCallback, Object[] arguments,
        String[] allowedFields) {
    for (String allowedField : allowedFields) {
        for (Object object : arguments) {
            try {
                JXPathContext context = JXPathContext.newContext(object);
                Object value = context.getValue(allowedField);
                String argument = object == null ? "null argument" : object.getClass().getName();
                generateKeyValueString(builder, object, value, argument);
                Field field = getField(allowedField, object, argument);
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                argumentGatheringCallback.onField(field, object);
            } catch (Throwable throwable) {
                LOGGER.warn(ExceptionUtil.getStackTraceString(throwable));
            }
        }
    }
}

From source file:org.openinfinity.core.aspect.ArgumentBuilder.java

/**
 * Returns builded argument information based on allowed field names presented by using XPATH.
 * //from  w  w  w .  ja  va 2s .  co m
 * @param name
 * @param argumentInfo
 * @return
 */
public void extractArgumentInfoByFilteringFields(JoinPoint joinPoint, String[] allowedFields) {
    Object[] objects = joinPoint.getArgs();
    if (objects.length > 0) {
        for (String allowedField : allowedFields) {
            for (Object object : objects) {
                try {
                    JXPathContext context = JXPathContext.newContext(object);
                    Object value = context.getValue(allowedField);
                    builder.append(
                            object == null ? "null argument" : object.getClass().getName() + "." + allowedField)
                            .append("=[").append((value == null ? "null value" : (value))).append("] ");
                } catch (Throwable throwable) {
                    LOGGER.warn(ExceptionUtil.getStackTraceString(throwable));
                }
            }
        }
    } else {
        builder.append("without any parameters");
    }
}

From source file:org.openinfinity.core.aspect.ArgumentGatheringJoinPointInterceptor.java

private void buildFieldBasedArgumentInformation(String[] allowedFields, StringBuilder builder,
        Object[] objects) {//from ww w  . j  av a2s .  c om
    for (String allowedField : allowedFields) {
        for (Object object : objects) {
            try {
                JXPathContext context = JXPathContext.newContext(object);
                Object value = context.getValue(allowedField);
                builder.append(
                        object == null ? "null argument" : object.getClass().getName() + "." + allowedField)
                        .append("=[").append((value == null ? "null value" : (value))).append("] ");
            } catch (Throwable throwable) {
                LOGGER.warn(ExceptionUtil.getStackTraceString(throwable));
            }
        }
    }
}

From source file:org.openlmis.fulfillment.service.OrderCsvHelper.java

private Object getColumnValue(int counter, JXPathContext orderContext, JXPathContext lineItemContext,
        OrderFileColumn orderFileColumn) {
    Object columnValue;//  w w w .  j a va 2s . c  o  m

    switch (orderFileColumn.getNested()) {
    case STRING:
        columnValue = orderFileColumn.getKeyPath();
        break;
    case LINE_NO:
        columnValue = counter;
        break;
    case ORDER:
        columnValue = orderContext.getValue(orderFileColumn.getKeyPath());
        break;
    default:
        columnValue = lineItemContext.getValue(orderFileColumn.getKeyPath());
        break;
    }

    if (orderFileColumn.getRelated() != null && !orderFileColumn.getRelated().isEmpty()) {
        columnValue = getRelatedColumnValue((UUID) columnValue, orderFileColumn);
    }

    return columnValue == null ? "" : columnValue;
}

From source file:org.openlmis.fulfillment.service.OrderCsvHelper.java

private Object getValue(Object object, String keyPath) {
    JXPathContext context = JXPathContext.newContext(object);

    return context.getValue(keyPath);
}

From source file:org.openlmis.order.helper.OrderCsvHelper.java

private Object getColumnValue(int counter, JXPathContext orderContext, JXPathContext lineItemContext,
        OrderFileColumn orderFileColumn) {
    Object columnValue;/*  w  w  w .ja v  a2  s .  c o  m*/

    switch (orderFileColumn.getNested()) {
    case STRING:
        columnValue = orderFileColumn.getKeyPath();
        break;
    case LINE_NO:
        columnValue = counter;
        break;
    case ORDER:
        columnValue = orderContext.getValue(orderFileColumn.getKeyPath());
        break;
    default:
        columnValue = lineItemContext.getValue(orderFileColumn.getKeyPath());
        break;
    }
    return columnValue;
}

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

/**
 * Fill collection set.// ww  w.j a  va  2s  . c  o  m
 *
 * @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.AbstractJsonCollectionHandler.java

/**
 * Gets the resource name.//from   w ww  .java 2 s  . c om
 *
 * @param context the JXpath context
 * @param group the group
 * @return the resource name
 */
private String getResourceName(JXPathContext context, XmlGroup group) {
    // Processing multiple-key resource name.
    if (group.hasMultipleResourceKey()) {
        List<String> keys = new ArrayList<String>();
        for (String key : group.getXmlResourceKey().getKeyXpathList()) {
            LOG.debug("getResourceName: getting key for resource's name using {}", key);
            String keyName = (String) context.getValue(key);
            keys.add(keyName);
        }
        return StringUtils.join(keys, "_");
    }
    // If key-xpath doesn't exist or not found, a node resource will be assumed.
    if (group.getKeyXpath() == null) {
        return "node";
    }
    // Processing single-key resource name.
    LOG.debug("getResourceName: getting key for resource's name using {}", group.getKeyXpath());
    return (String) context.getValue(group.getKeyXpath());
}

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

/**
 * Gets the time stamp./*from  w w  w  .j  a  v  a  2  s .co m*/
 * 
 * @param context the JXPath context
 * @param group the group
 * @return the time stamp
 */
protected Date getTimeStamp(JXPathContext context, XmlGroup group) {
    if (group.getTimestampXpath() == null) {
        return null;
    }
    String pattern = group.getTimestampFormat() == null ? "yyyy-MM-dd HH:mm:ss" : group.getTimestampFormat();
    LOG.debug(
            "getTimeStamp: retrieving custom timestamp to be used when updating RRDs using XPATH {} and pattern {}",
            group.getTimestampXpath(), pattern);
    Date date = null;
    String value = (String) context.getValue(group.getTimestampXpath());
    try {
        DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
        DateTime dateTime = dtf.parseDateTime(value);
        date = dateTime.toDate();
    } catch (Exception e) {
        LOG.warn("getTimeStamp: can't convert custom timestamp {} using pattern {}", value, pattern);
    }
    return date;
}