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.lilyproject.runtime.conf.ConfImpl.java

public String evalInheritanceConstraint(Conf conf, String inheritConstraint) {
    try {/*  ww  w. ja  v a 2  s  . c  om*/
        JXPathContext jxpc = JXPathContext.newContext(conf);
        return (String) jxpc.getValue(inheritConstraint);
    } catch (Exception e) {
        throw new ConfException(
                "Error evaluating configuration inheritance uniqueness constraint expression: \""
                        + inheritConstraint + "\" on conf defined at " + conf.getLocation(),
                e);
    }
}

From source file:org.lilyproject.runtime.conf.test.JXPathTest.java

public void testIt() throws Exception {
    String path = "jxpathconf.xml";
    Conf conf = XmlConfBuilder.build(getClass().getResourceAsStream(path), path);

    JXPathContext context = JXPathContext.newContext(conf);

    assertEquals("Venus", context.getValue("planet"));
    assertEquals("Mars", context.getValue("@planet"));

    assertEquals("5", context.getValue("/things/thing[@name='Book']/@quantity"));
    assertEquals("50", context.getValue("/things/thing[@name='Bicycle']/@quantity"));

    assertEquals("Book", context.getValue("/things/thing[1]/@name"));

    assertEquals("Bicycle", context.getValue("/things/thing[2]/@name"));
    assertEquals("Bicycle", context.getValue("/things/thing[last()]/@name"));

    List<Conf> things = new ArrayList<Conf>();
    Iterator thingsIt = context.iteratePointers("things/thing[position() < 3]");
    while (thingsIt.hasNext()) {
        Pointer pointer = (Pointer) thingsIt.next();
        assertTrue(pointer.getNode() instanceof Conf);
        things.add((Conf) pointer.getNode());
    }/*from w  ww . java  2  s . c  om*/
    assertEquals(2, things.size());
}

From source file:org.lilyproject.runtime.rapi.ConfPlaceholderConfigurer.java

@Override
protected String resolvePlaceholder(String placeholder, Properties props, int systemPropertiesMode) {
    int colonPos = placeholder.indexOf(':');
    if (colonPos == -1) {
        return null;
    }//from w  w  w  .  ja  v  a2  s.  c  o m

    try {
        String confPath = placeholder.substring(0, colonPos);
        String confExpr = placeholder.substring(colonPos + 1);

        Conf conf = confRegistry.getConfiguration(confPath);
        JXPathContext context = JXPathContext.newContext(conf);
        Object value = context.getValue(confExpr);

        return value == null ? "" : value.toString();
    } catch (Exception e) {
        throw new RuntimeException(
                "Error fetching configuration value for placeholder \"" + placeholder + "\".", e);
    }
}

From source file:org.mitre.ptmatchadapter.format.SimplePatientCsvFormat.java

/**
 * Returns supported Patient properties as a string of comma-separated values.
 * Values of String fields are enclosed by double-quotes.
 * //from w  ww .  jav a2 s.  com
 * @param patient
 *          the patient resource to serialize to a CSV string
 * @return
 *          comma-delimited values of fields associated with the Patient
 */
public String toCsv(Patient patient) {
    final StringBuilder sb = new StringBuilder(INITIAL_ROW_LENGTH);
    JXPathContext patientCtx = JXPathContext.newContext(patient);

    try {
        // resource id (logical id only)
        sb.append(patient.getIdElement().getIdPart());
    } catch (NullPointerException e) {
        // check for null by exception since it is unexpected. 
        // Privacy concern keeps me from logging anything about this patient.
        LOG.error("Patient has null identifier element. This is unexpected!");
    }
    sb.append(COMMA);

    // identifiers of interest
    for (String sysName : identifierSystems) {
        Pointer ptr = patientCtx.getPointer("identifier[system='" + sysName + "']");
        Identifier id = (Identifier) ptr.getValue();
        if (id != null) {
            sb.append(id.getValue());
        }
        sb.append(COMMA);
    }

    // Extract Name Parts of interest
    for (String use : nameUses) {
        Pointer ptr;
        if (use.isEmpty()) {
            ptr = patientCtx.getPointer("name[not(use)]");
        } else {
            ptr = patientCtx.getPointer("name[use='" + use + "']");
        }
        HumanName name = (HumanName) ptr.getValue();
        if (name != null) {
            JXPathContext nameCtx = JXPathContext.newContext(ptr.getValue());
            for (String part : nameParts) {
                sb.append(DOUBLE_QUOTE);
                if (TEXT_NAME_PART.equals(part)) {
                    Object val = nameCtx.getValue(part);
                    if (val != null) {
                        sb.append(val.toString());
                    }
                } else {
                    // other supported parts return lists of string types
                    Object namePart = nameCtx.getValue(part);
                    if (namePart instanceof List<?>) {
                        List<StringType> partList = (List<StringType>) namePart;
                        if (partList.size() > 0) {
                            sb.append(partList.get(0).getValue());
                        }
                    }
                }
                sb.append(DOUBLE_QUOTE);
                sb.append(COMMA);
            }
        } else {
            // add blank sections for the name parts
            for (int i = 0; i < nameParts.length; i++) {
                sb.append(COMMA);
            }
        }
    }

    // Gender
    sb.append(patient.getGender().toString());
    sb.append(COMMA);

    // Date of Birth
    Date dob = patient.getBirthDate();
    if (dob != null) {
        sb.append(dateFormat.format(dob));
    }

    sb.append(COMMA);
    sb.append(buidContactInfo(patient));

    return sb.toString();
}

From source file:org.mule.module.xml.expression.JXPathExpressionEvaluator.java

private Object getExpressionValue(JXPathContext context, String expression) {
    NamespaceManager theNamespaceManager = getNamespaceManager();
    if (theNamespaceManager != null) {
        addNamespacesToContext(theNamespaceManager, context);
    }//www  . j a  v  a  2 s .  c o  m

    Object result = null;

    try {
        result = context.getValue(expression);
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("failed to process JXPath expression: " + expression, e);
        }
    }

    return result;
}

From source file:org.mule.module.xml.filters.JXPathFilter.java

private boolean accept(Object obj) {
    if (obj == null) {
        logger.warn("Applying JXPathFilter to null object.");
        return false;
    }/*from   w  w w  .j ava  2 s .c  o  m*/
    if (pattern == null) {
        logger.warn("Expression for JXPathFilter is not set.");
        return false;
    }
    if (expectedValue == null) {
        // Handle the special case where the expected value really is null.
        if (pattern.endsWith("= null") || pattern.endsWith("=null")) {
            expectedValue = "null";
            pattern = pattern.substring(0, pattern.lastIndexOf("="));
        } else {
            if (logger.isInfoEnabled()) {
                logger.info("Expected value for JXPathFilter is not set, using 'true' by default");
            }
            expectedValue = Boolean.TRUE.toString();
        }
    }

    Object xpathResult = null;
    boolean accept = false;

    Document dom4jDoc;
    try {
        dom4jDoc = XMLUtils.toDocument(obj, muleContext);
    } catch (Exception e) {
        logger.warn("JxPath filter rejected message because of an error while parsing XML: " + e.getMessage(),
                e);
        return false;
    }

    // Payload is XML
    if (dom4jDoc != null) {
        if (namespaces == null) {
            // no namespace defined, let's perform a direct evaluation
            xpathResult = dom4jDoc.valueOf(pattern);
        } else {
            // create an xpath expression with namespaces and evaluate it
            XPath xpath = DocumentHelper.createXPath(pattern);
            xpath.setNamespaceURIs(namespaces);
            xpathResult = xpath.valueOf(dom4jDoc);
        }
    }
    // Payload is a Java object
    else {
        if (logger.isDebugEnabled()) {
            logger.debug("Passing object of type " + obj.getClass().getName() + " to JXPathContext");
        }
        JXPathContext context = JXPathContext.newContext(obj);
        initialise(context);
        xpathResult = context.getValue(pattern);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("JXPathFilter Expression result = '" + xpathResult + "' -  Expected value = '"
                + expectedValue + "'");
    }
    // Compare the XPath result with the expected result.
    if (xpathResult != null) {
        accept = xpathResult.toString().equals(expectedValue);
    } else {
        // A null result was actually expected.
        if (expectedValue.equals("null")) {
            accept = true;
        }
        // A null result was not expected, something probably went wrong.
        else {
            logger.warn("JXPathFilter expression evaluates to null: " + pattern);
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("JXPathFilter accept object  : " + accept);
    }

    return accept;
}

From source file:org.mule.module.xml.transformer.JXPathExtractor.java

/**
 * Evaluate the expression in the context of the given object and returns the
 * result. If the given object is a string, it assumes it is an valid xml and
 * parses it before evaluating the xpath expression.
 *///ww  w .j  a v  a  2  s. c  o  m
@Override
public Object doTransform(Object src, String encoding) throws TransformerException {
    try {
        Object result = null;
        if (src instanceof String) {
            Document doc = DocumentHelper.parseText((String) src);

            XPath xpath = doc.createXPath(expression);
            if (namespaces != null) {
                xpath.setNamespaceURIs(namespaces);
            }

            // This is the way we always did it before, so keep doing it that way
            // as xpath.evaluate() will return non-string results (like Doubles)
            // for some scenarios.
            if (outputType == null && singleResult) {
                return xpath.valueOf(doc);
            }

            // TODO handle non-list cases, see
            //http://www.dom4j.org/apidocs/org/dom4j/XPath.html#evaluate(java.lang.Object)
            Object obj = xpath.evaluate(doc);
            if (obj instanceof List) {
                for (int i = 0; i < ((List) obj).size(); i++) {
                    final Node node = (Node) ((List) obj).get(i);
                    result = add(result, node);

                    if (singleResult) {
                        break;
                    }
                }
            } else {
                result = add(result, obj);
            }

        } else {
            JXPathContext context = JXPathContext.newContext(src);
            result = context.getValue(expression);
        }
        return result;
    } catch (Exception e) {
        throw new TransformerException(this, e);
    }

}

From source file:org.mule.providers.bpm.osworkflow.functions.SendMuleEvent.java

public void execute(Map transientVars, Map args, PropertySet ps) throws WorkflowException {
    boolean synchronous = "true".equals(args.get("synchronous"));

    String endpoint = (String) args.get("endpoint");
    String transformers = (String) args.get("transformers");
    if (transformers != null) {
        endpoint += "?transformers=" + transformers;
    }//  w  w  w.j  av a  2 s .  c o  m

    // Use "payload" to easily specify the payload as a string directly in the process definition.
    // Use "payloadSource" to get the payload from a process variable. 
    String payload = (String) args.get("payload");
    String payloadSource = (String) args.get("payloadSource");

    // Get the actual payload (as an object).
    Object payloadObject;
    if (payload == null) {
        if (payloadSource == null) {
            payloadObject = ps.getObject(ProcessConnector.PROCESS_VARIABLE_DATA);
            if (payloadObject == null) {
                payloadObject = ps.getObject(ProcessConnector.PROCESS_VARIABLE_INCOMING);
            }
        } else {
            // The payloadSource may be specified using JavaBean notation (e.g.,
            // "myObject.myStuff.myField" would first retrieve the process
            // variable "myObject" and then call .getMyStuff().getMyField()
            String[] tokens = StringUtils.split(payloadSource, ".", 2);
            payloadObject = ps.getObject(tokens[0]);
            if (tokens.length > 1) {
                JXPathContext context = JXPathContext.newContext(payloadObject);
                payloadObject = context.getValue(tokens[1]);
            }
        }
    } else {
        payloadObject = payload;
    }
    if (payloadObject == null) {
        throw new IllegalArgumentException(
                "Payload for message is null.  Payload source is \"" + payloadSource + "\"");
    }

    /////////////////////////////////////////////////////////////////////////////////

    // Get info. on the current process.
    WorkflowEntry entry = (WorkflowEntry) transientVars.get("entry");
    Map props = new HashMap();
    props.put(ProcessConnector.PROPERTY_PROCESS_TYPE, entry.getWorkflowName());
    props.put(ProcessConnector.PROPERTY_PROCESS_ID, new Long(entry.getId()));
    props.put(MuleProperties.MULE_CORRELATION_ID_PROPERTY, new Long(entry.getId()));

    // Get a callback to Mule from the configuration.
    MuleConfiguration config = (MuleConfiguration) transientVars.get("configuration");
    MessageService mule = config.getMsgService();

    // Generate a message in Mule.
    UMOMessage response;
    try {
        response = mule.generateMessage(endpoint, payloadObject, props, synchronous);
    } catch (Exception e) {
        throw new WorkflowException(e);
    }

    // If the message is synchronous, pipe the response back into the workflow.
    if (synchronous) {
        if (response != null) {
            ps.setObject(ProcessConnector.PROCESS_VARIABLE_INCOMING, response.getPayload());
        } else {
            logger.info(
                    "Synchronous message was sent to endpoint " + endpoint + ", but no response was returned.");
        }
    }
}

From source file:org.mule.transport.bpm.jbpm4.customactivity.SendMuleEvent.java

public void sendMuleEvent(ActivityExecution execution) throws Exception {
    if (jbpm4 == null) {
        throw new Exception("Configuration problem - Jbpm4 is null. " + "Its reference needs to be set.");
    }/*from ww  w.  j  a  v  a2s  . co  m*/
    MessageService mule = jbpm4.getMessageService();

    if (transformers != null) {
        endpoint += "?transformers=" + transformers;
    }

    if (payload == null) {
        if (payloadSource == null) {
            payloadObject = execution.getVariable(ProcessConnector.PROCESS_VARIABLE_DATA);
            if (payloadObject == null) {
                payloadObject = execution.getVariable(ProcessConnector.PROCESS_VARIABLE_INCOMING);
            }
        } else {
            // The payloadSource may be specified using JavaBean notation (e.g.,
            // "myObject.myStuff.myField" would first retrieve the process
            // variable "myObject" and then call .getMyStuff().getMyField()
            String[] tokens = org.apache.commons.lang.StringUtils.split(payloadSource, ".", 2);
            payloadObject = execution.getVariable(tokens[0]);
            if (tokens.length > 1) {
                JXPathContext context = JXPathContext.newContext(payloadObject);
                payloadObject = context.getValue(tokens[1].replaceAll("\\.", "/"));
            }
        }
    } else {
        payloadObject = payload;
    }
    if (payloadObject == null) {
        throw new IllegalArgumentException(
                "Payload for message is null.  Payload source is \"" + payloadSource + "\"");
    }

    Map<String, Object> props = new HashMap<String, Object>();

    // TODO: this probably isn't the best. I'm casting to an Impl because it's
    // the only way I could see to get the name of the process definition
    props.put(ProcessConnector.PROPERTY_PROCESS_TYPE,
            ((ExecutionImpl) execution).getProcessDefinition().getName());
    props.put(ProcessConnector.PROPERTY_PROCESS_ID, execution.getProcessInstance().getId());
    props.put(MuleProperties.MULE_CORRELATION_ID_PROPERTY, execution.getProcessInstance().getId());
    /*
     * TODO: get process start // looks like we can get this from
     * historyService, but do we really need it? props
     * .put(ProcessConnector.PROPERTY_PROCESS_STARTED, );
     */
    if (properties != null) {
        props.putAll(properties);
    }

    MuleMessage response = mule.generateMessage(endpoint, payloadObject, props, synchronous);
    if (synchronous) {
        if (response != null) {
            execution.setVariable(variableName, response.getPayload());
        } else {
            log.info(
                    "Synchronous message was sent to endpoint " + endpoint + ", but no response was returned.");
        }
    }

}

From source file:org.onecmdb.core.utils.xpath.commands.CreateCommand.java

@Override
public void transfer(OutputStream out) {
    this.context.put("create", true);

    JXPathContext xPathContext = getXPathContext();
    xPathContext.setLenient(true);/*  ww  w. java2  s  .c o  m*/
    Object o = xPathContext.getValue(getPath());
    if (o != null) {
        throw new IllegalArgumentException("Path '" + getPath() + "' exists.");
    }
    setupTX();

    Pointer p = xPathContext.createPath(getPath());

    JXPathContext relContext = getRelativeContext(p);

    for (String outputAttribute : getInputAttributeNameAsArray()) {

        /*
        Iterator<Pointer> outputAttrPointersIter = context.iteratePointers(outputAttribute);
        while(outputAttrPointersIter.hasNext()) {
           Pointer vPointer = outputAttrPointersIter.next();
           Object values = getValues(outputAttribute);
           //NodePointer nP = (NodePointer)vPointer;
           //nP.getImmediateValuePointer().setValue(values);
           vPointer.setValue(values);
        }
        */
        Object values = getValues(outputAttribute);
        relContext.setValue(outputAttribute, values);
    }

    processTX();
}