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.mitre.ptmatchadapter.format.SimplePatientCsvFormatTest.java

@Test
public void testToCsv() {
    final SimplePatientCsvFormat fmt = new SimplePatientCsvFormat();

    Patient patient = newPatient();//from   ww w .j a  v a  2s. c  om

    JXPathContext patientCtx = JXPathContext.newContext(patient);
    Pointer ptr = patientCtx.getPointer("identifier[system='SSN']");
    assertNotNull(ptr);
    Identifier id = (Identifier) ptr.getValue();
    if (id != null) {
        assertNotNull("ssn", id.getValue());
    }
    Object obj1 = ptr.getNode();

    ptr = patientCtx.getPointer("name[use='official']");
    assertNotNull(ptr);
    Object obj2 = ptr.getValue();
    ptr = patientCtx.getPointer("name[not(use)]");
    assertNotNull(ptr);
    obj2 = ptr.getValue();

    String str = fmt.toCsv(patient);
    LOG.info("CSV: {}", str);
    assertTrue(str.length() > 0);
    // Ensure the literal, null doesn't appear
    assertTrue(!str.contains("null"));
    // Ensure there is no sign of array delimiters
    assertTrue(!str.contains("["));
    // Ensure line doesn't end with a comma
    assertTrue(!str.endsWith(","));
    assertTrue(str.contains("Smith"));

    List<ContactPoint> matches = ContactPointUtil.find(patient.getTelecom(), ContactPointSystem.PHONE,
            ContactPointUse.WORK);
    assertNotNull(matches);
    assertNotNull(matches.get(0));
}

From source file:org.mskcc.pathdb.lucene.ConfigurableIndexCollector.java

/**
 * Initialises the class to search over the given entry object. This MUST be
 * done before any searching can commence
 *
 * @param entry A PSI-MI Entry Object/*  w  ww .j av  a  2 s.  c om*/
 */
public void setContext(Entry entry) {
    context = JXPathContext.newContext(entry);
    resetIterator();
}

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

private JXPathContext createContextForXml(final Document document) {
    Container container = new Container() {

        @Override//from  w w  w .  j  a va  2s  . co  m
        public Object getValue() {
            return document;
        }

        @Override
        public void setValue(Object value) {
            throw new UnsupportedOperationException();
        }
    };

    return JXPathContext.newContext(container);
}

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

private JXPathContext createContextForBean(Object payload) {
    return JXPathContext.newContext(payload);
}

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  ww  .  j av a 2 s.  co  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.
 *//*from   w w  w. j  av  a2 s  .  co  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;
    }/*from  w w  w. j a v a  2 s.  co 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  w  ww.ja  v a2  s  .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.AbstractPathCommand.java

public JXPathContext getXPathContext() {

    if (this.xPathContext == null) {
        log.debug("Create new OneCMDbContext");
        ISession session = this.oneCmdbContext.getSession(getAuth());
        if (session == null) {
            throw new SecurityException("No Session found! Try to do auth() first!");
        }//from w  ww  . ja  va2  s. c o m
        /*
        IModelService mSvc = (IModelService)session.getService(IModelService.class);
        this.xPathContext = JXPathContext.newContext(new OneCMDBContext(new OneCMDBContextBeanProvider(mSvc)));
        */
        this.context.put("session", session);
        this.xPathContext = JXPathContext.newContext(new OneCMDBContext(this.context, session));
        this.xPathContext.setFactory(new OneCMDBFactory());
    }
    return (this.xPathContext);
}

From source file:org.onehippo.forge.content.pojo.model.ContentNode.java

/**
 * Creates and returns a {@link JXPathContext} instance used by default.
 * @return a {@link JXPathContext} instance used by default
 *///from w  w  w. j a  va2 s.  c  o  m
private JXPathContext createJXPathContext() {
    JXPathContext jxpathCtx = JXPathContext.newContext(this);
    jxpathCtx.setLenient(true);
    return jxpathCtx;
}