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.dcm4che3.conf.core.Nodes.java

public static Iterator search(Map<String, Object> configurationRoot, String liteXPathExpression)
        throws IllegalArgumentException {
    return JXPathContext.newContext(configurationRoot).iterate(liteXPathExpression);

}

From source file:org.dcm4che3.conf.core.util.ConfigNodeUtil.java

public static void replaceNode(Object rootConfigNode, String path, Object replacementConfigNode) {

    JXPathContext jxPathContext = JXPathContext.newContext(rootConfigNode);
    jxPathContext.setFactory(new AbstractFactory() {
        @Override/*from   ww w. j  a  va  2 s.  c om*/
        public boolean createObject(JXPathContext context, Pointer pointer, Object parent, String name,
                int index) {
            if (parent instanceof Map) {
                ((Map<String, Object>) parent).put(name, new TreeMap<String, Object>());
                return true;
            }
            return false;
        }

        @Override
        public boolean declareVariable(JXPathContext context, String name) {
            return super.declareVariable(context, name);
        }
    });
    jxPathContext.createPathAndSetValue(path, replacementConfigNode);
}

From source file:org.dcm4chee.xds2.persistence.RegistryObject.java

/**
 * Indexed properties that are used in queries. 
 * Do not use the setter - the update is fully seamless - when object is merged/persisted - indexes are re/-created and updated if needed  
 * @return// ww w .j  a  va 2  s . c o  m
 */
@OneToMany(mappedBy = "subject", cascade = CascadeType.ALL, orphanRemoval = true)
@Access(AccessType.PROPERTY)
@SuppressWarnings("unchecked")
public Set<RegistryObjectIndex> getIndexedValues() {
    log.debug("getIndexedValues called for object with id {}", getId());

    // TODO: OPTIMIZATION - if marshalling is fast - can check whether the object has already changed first

    // if fullObject was not initialized - nothing has changed and we could just return old value 
    // (except if reindexing is forced)
    if (fullObject == null && !FORCE_REINDEX)
        return currIndexedValues;

    if (getIndexes() == null)
        return currIndexedValues;

    // validate/update searchIndex table
    // iterate over all enabled indexes
    Set<RegistryObjectIndex> newIndexValues = new HashSet<RegistryObjectIndex>();
    for (XDSSearchIndexKey key : getIndexes()) {
        // run xpath expr on fullobject
        JXPathContext context = JXPathContext.newContext(getFullObject());
        Iterator<String> valueIterator = (Iterator<String>) context.iterate(INDEX_XPATHS.get(key));

        // add to newIndexValues
        while (valueIterator.hasNext()) {
            RegistryObjectIndex ind = new RegistryObjectIndex();
            ind.setSubject(this);
            ind.setKey(key);
            ind.setValue((String) valueIterator.next());
            newIndexValues.add(ind);
        }
    }

    // Retain what we have there already, and add new ones.
    // Note thats retain makes use of a custom equals for RegistryObjectIndex that does not consider the pk.
    currIndexedValues.retainAll(newIndexValues);
    currIndexedValues.addAll(newIndexValues);

    return currIndexedValues;
}

From source file:org.dcm4chee.xds2.registry.ws.XDSPersistenceWrapper.java

/**
 * Correct metadata parameters to conform to XDS specification.
 * Replace non-conformant ids to uuids, update references, check classification scemes, nodes, etc
 *//* ww w  .j a v a 2 s .  c  o m*/
void checkAndCorrectSubmitObjectsRequest(SubmitObjectsRequest req) throws XDSException {

    // TODO: DB_RESTRUCT - CODE INSPECTION - is it correct to replace ids with uuids for ALL identifiables, not only ROs?

    JXPathContext requestContext = JXPathContext.newContext(req);

    ////// Pre-process - move detached classifications from registryObjectList into corresponding objects

    Iterator<JAXBElement<? extends IdentifiableType>> objectListIterator = req.getRegistryObjectList()
            .getIdentifiable().iterator();
    while (objectListIterator.hasNext()) {

        JAXBElement<? extends IdentifiableType> elem = objectListIterator.next();

        /// filter Classifications only
        if (!ClassificationType.class.isAssignableFrom(elem.getValue().getClass()))
            continue;

        /// find referenced object and add the classification to the referenced object 
        ClassificationType cl = (ClassificationType) elem.getValue();
        // this xpath return all nodes in the tree with the specified id 
        Iterator referencedObjs = (Iterator) requestContext
                .iteratePointers(String.format("//*[id = '%s']", cl.getClassifiedObject()));
        try {
            Object o = ((Pointer) referencedObjs.next()).getValue();

            if (!RegistryObjectType.class.isAssignableFrom(o.getClass()))
                throw new XDSException(XDSException.XDS_ERR_REGISTRY_METADATA_ERROR,
                        "Classification " + cl.getId() + " classifies object " + cl.getClassifiedObject()
                                + " which is not a Registry Object",
                        null);
            RegistryObjectType registryObj = (RegistryObjectType) o;

            // add this classification to the classification list
            registryObj.getClassification().add(cl);

        } catch (NoSuchElementException e) {
            throw new XDSException(XDSException.XDS_ERR_REGISTRY_METADATA_ERROR,
                    "Classified object " + cl.getClassifiedObject()
                            + " not found in the request (Classification " + cl.getId() + " )",
                    null);
        }
        // there must be a single node with referenced id
        if (referencedObjs.hasNext())
            throw new XDSException(
                    XDSException.XDS_ERR_REGISTRY_METADATA_ERROR, "Classification " + cl.getId()
                            + " references an object " + cl.getClassifiedObject() + " that is not unique",
                    null);

        /// remove the detached classification from the list
        objectListIterator.remove();
    }

    ////// First run - replace non-uuid IDs with UUIDs for all identifiables, included nested ones

    // Use //id xpath to find all id fields of identifiables in the request
    Iterator ids = (Iterator) requestContext.iteratePointers("//id");

    while (ids.hasNext()) {

        Pointer p = (Pointer) ids.next();
        String oldId = (String) p.getValue();
        String newIdUUID = oldId;

        if (oldId == null)
            continue;

        // Replace non-UUID id with a generated UUID
        if (!oldId.startsWith("urn:")) {
            newIdUUID = "urn:uuid:" + UUID.randomUUID().toString();
            p.setValue(newIdUUID);
            log.debug("Replacing id {} with uuid {}", oldId, newIdUUID);
        }

        newUUIDs.put(oldId, newIdUUID);
    }

    ////// Second run - perform check and correction recursively
    for (JAXBElement<? extends IdentifiableType> elem : req.getRegistryObjectList().getIdentifiable()) {

        // filter RegistryObjects only
        if (!RegistryObjectType.class.isAssignableFrom(elem.getValue().getClass()))
            continue;
        RegistryObjectType ro = (RegistryObjectType) elem.getValue();

        checkAndCorrectMetadata(ro);
    }
}

From source file:org.eclipse.e4.emf.internal.xpath.JXPathContextImpl.java

/**
 * Create a new context//  w ww. j  av  a 2s  . com
 *
 * @param contextBean
 *            the context bean (=root of the xpath expression)
 */
JXPathContextImpl(Object contextBean) {
    this.context = JXPathContext.newContext(contextBean);
    this.context.setFunctions(new ClassFunctions(EMFFunctions.class, "ecore"));
}

From source file:org.fireflow.engine.modules.script.functions.XPath.java

public Object getValue(String xpath) {
    Map<String, Object> contextObjects = this.context.getAllContextObject();
    Map<String, String> namespacePrefixUriMap = null;
    if (contextObjects.containsKey(NAMESPACE_PREFIX_URI_MAP)) {
        namespacePrefixUriMap = (Map<String, String>) contextObjects.remove(NAMESPACE_PREFIX_URI_MAP);
    }/*  w  ww  .  ja v  a  2 s . c o m*/
    JXPathContext jxpathContext = JXPathContext.newContext(contextObjects);

    if (namespacePrefixUriMap != null) {
        Iterator<String> prefixIterator = namespacePrefixUriMap.keySet().iterator();
        while (prefixIterator.hasNext()) {
            String prefix = prefixIterator.next();
            String nsUri = namespacePrefixUriMap.get(prefix);
            jxpathContext.registerNamespace(prefix, nsUri);
        }
    }
    Object result = jxpathContext.getValue(xpath);
    return result;
}

From source file:org.fireflow.engine.modules.script.ScriptEngineHelper.java

private static Object evaluateXpathExpression(Expression fireflowExpression,
        Map<String, Object> contextObjects) {
    Map<String, String> namespacePrefixUriMap = fireflowExpression.getNamespaceMap();

    JXPathContext jxpathContext = JXPathContext.newContext(contextObjects);
    jxpathContext.setFactory(w3cDomFactory);
    if (namespacePrefixUriMap != null) {
        Iterator<String> prefixIterator = namespacePrefixUriMap.keySet().iterator();
        while (prefixIterator.hasNext()) {
            String prefix = prefixIterator.next();
            String nsUri = namespacePrefixUriMap.get(prefix);
            jxpathContext.registerNamespace(prefix, nsUri);
        }//  w w w . ja  v  a2 s .co  m
    }

    //W3C DOM
    //TODO ?dom4j document?jdom document
    Object obj = null;
    Object _node = jxpathContext.selectSingleNode(fireflowExpression.getBody());
    if (_node instanceof org.w3c.dom.Node) {
        if (_node instanceof org.w3c.dom.Document) {
            obj = _node;
        } else {
            obj = ((org.w3c.dom.Node) _node).getTextContent();
        }
    } else {
        obj = _node;
    }
    return obj;
}

From source file:org.fireflow.engine.modules.script.ScriptEngineHelper.java

public static Map<String, Object> resolveAssignments(RuntimeContext runtimeContext,
        List<Assignment> assignments, Map<String, Object> contextVars) throws ScriptException {

    if (assignments == null || assignments.size() == 0) {
        return null;
    }// w w  w.  j  ava2  s.  co  m

    Map<String, Object> jxpathRoot = new HashMap<String, Object>();
    if (contextVars.get(ScriptContextVariableNames.INPUTS) != null) {
        jxpathRoot.put(ScriptContextVariableNames.INPUTS, contextVars.get(ScriptContextVariableNames.INPUTS));
    } else {
        jxpathRoot.put(ScriptContextVariableNames.INPUTS, new HashMap<String, Object>());
    }

    if (contextVars.get(ScriptContextVariableNames.OUTPUTS) != null) {
        jxpathRoot.put(ScriptContextVariableNames.OUTPUTS, contextVars.get(ScriptContextVariableNames.OUTPUTS));
    } else {
        jxpathRoot.put(ScriptContextVariableNames.OUTPUTS, new HashMap<String, Object>());
    }

    jxpathRoot.put(ScriptContextVariableNames.PROCESS_VARIABLES, new HashMap<String, Object>());
    jxpathRoot.put(ScriptContextVariableNames.ACTIVITY_VARIABLES, new HashMap<String, Object>());
    jxpathRoot.put(ScriptContextVariableNames.SESSION_ATTRIBUTES, new HashMap<String, Object>());

    for (Assignment assignment : assignments) {
        Expression fromExpression = assignment.getFrom();

        Object obj = evaluateExpression(runtimeContext, fromExpression, contextVars);

        if (fromExpression.getDataType() != null && obj != null) {
            try {
                obj = JavaDataTypeConvertor.dataTypeConvert(fromExpression.getDataType(), obj, null);
            } catch (ClassCastException e) {
                throw new ScriptException(e);
            } catch (ClassNotFoundException e) {
                throw new ScriptException(e);
            }
        }

        // TODO To ?JXpath??? 
        Expression toExpression = assignment.getTo();

        QName dataType = toExpression.getDataType();
        if (dataType != null && dataType.getNamespaceURI().equals(NameSpaces.JAVA.getUri()) && obj != null) {// ??
            try {
                obj = JavaDataTypeConvertor.dataTypeConvert(dataType, obj, null);
            } catch (ClassCastException e) {
                throw new ScriptException(e);
            } catch (ClassNotFoundException e) {
                throw new ScriptException(e);
            }
        } else {
            // XSD??
            //TODO (?)datestring 
            if (obj instanceof java.util.Date) {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                obj = df.format((java.util.Date) obj);
            }
        }

        JXPathContext jxpathContext = JXPathContext.newContext(jxpathRoot);
        jxpathContext.setFactory(w3cDomFactory);

        Map<String, String> nsMap = toExpression.getNamespaceMap();
        Iterator<String> prefixIterator = nsMap.keySet().iterator();
        while (prefixIterator.hasNext()) {
            String prefix = prefixIterator.next();
            String nsUri = nsMap.get(prefix);
            jxpathContext.registerNamespace(prefix, nsUri);
        }

        //?
        jxpathContext.createPathAndSetValue(toExpression.getBody(), obj);
    }

    return jxpathRoot;
}

From source file:org.fireflow.pdl.fpdl.test.service.callback.TheCallbackServiceProcessTest1.java

@Test
public void testCallbackService() {
    final WorkflowSession session = WorkflowSessionFactory.createWorkflowSession(fireflowRuntimeContext,
            FireWorkflowSystem.getInstance());
    final WorkflowStatement stmt = session.createWorkflowStatement(FpdlConstants.PROCESS_TYPE_FPDL20);

    //0??//w  ww  .j  a  v a2  s.  com
    final WorkflowProcess process = getWorkflowProcess();

    //1???
    transactionTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus arg0) {

            //?
            try {
                ProcessDescriptor descriptor = stmt.uploadProcessObject(process, 0);
                ((ProcessDescriptorImpl) descriptor).setPublishState(true);
                stmt.updateProcessDescriptor(descriptor);
            } catch (InvalidModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    });

    //2?CallbackManagerinit?Webservice
    //TODO WorkflowServer?webservice

    /*
    WebServiceManager callbackManager = this.runtimeContext.getEngineModule(WebServiceManager.class, FpdlConstants.PROCESS_TYPE_FPDL20);
    try {
       callbackManager.publishAllCallbackServices();
    } catch (WebservicePublishException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
    }
    */

    //3???      
    transactionTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus arg0) {

            //??
            try {

                ProcessInstance processInstance = stmt.startProcess(process.getId(), bizId, null);

                if (processInstance != null) {
                    processInstanceId = processInstance.getId();
                }

            } catch (InvalidModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (WorkflowProcessNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvalidOperationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    });

    //JaxwsWebservice      
    Environment env = fireflowRuntimeContext.getEngineModule(Environment.class,
            FpdlConstants.PROCESS_TYPE_FPDL20);
    URL url = null;
    try {
        String contextPath = env.getWebserviceContextPath();
        if (!contextPath.startsWith("/")) {
            contextPath = "/" + contextPath;
        }
        if (!contextPath.endsWith("/")) {
            contextPath = contextPath + "/";
        }
        String address = "http://" + env.getWebserviceIP() + ":" + Integer.toString(env.getWebservicePort())
                + contextPath;
        url = new URL(address + serviceQName.getLocalPart() + "?wsdl");
    } catch (Exception e) {
        e.printStackTrace();
    }

    javax.xml.ws.Service jawsService = javax.xml.ws.Service.create(url, serviceQName);
    Dispatch<Source> dispatch = jawsService.createDispatch(portQName, Source.class,
            javax.xml.ws.Service.Mode.PAYLOAD);

    String messageStr = "<cal:acceptRequest  xmlns:cal=\"http://www.fireflow.org/junit/callbackservice\">"
            + "<cal:id>" + bizId + "</cal:id>" + "<cal:approveResult>" + approveResult + "</cal:approveResult>"
            + "</cal:acceptRequest>";
    java.io.ByteArrayInputStream byteInStream = new java.io.ByteArrayInputStream(messageStr.getBytes());
    StreamSource source = new StreamSource(byteInStream);

    Source response = dispatch.invoke(source);

    DOMResult result = new DOMResult();
    //      StreamResult result = new StreamResult(System.out);
    Transformer transformer = null;
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformer = transformerFactory.newTransformer();
        transformer.transform(response, result);
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException("Couldn't parse response stream.", e);
    } catch (TransformerException e) {
        throw new RuntimeException("Couldn't parse response stream.", e);
    }

    Document theResponsePayload = (Document) result.getNode();
    Assert.assertNotNull(theResponsePayload);
    JXPathContext jxpathContext = JXPathContext.newContext(theResponsePayload);
    jxpathContext.registerNamespace("ns0", targetNsUri);
    String response2 = (String) jxpathContext.getValue("ns0:acceptResponse/ns0:response2");

    Assert.assertEquals(responseResult, response2);

    this.assertResult(session);
}

From source file:org.fireflow.pdl.fpdl.test.service.callback.WebserviceStartProcessTest.java

@Test
public void testCallbackService() {
    final WorkflowSession session = WorkflowSessionFactory.createWorkflowSession(fireflowRuntimeContext,
            FireWorkflowSystem.getInstance());
    final WorkflowStatement stmt = session.createWorkflowStatement(FpdlConstants.PROCESS_TYPE_FPDL20);

    //0??//from   w  w w . java 2s.  co  m
    final WorkflowProcess process = getWorkflowProcess();

    //1???
    transactionTemplate.execute(new TransactionCallback() {
        public Object doInTransaction(TransactionStatus arg0) {

            //?
            try {

                ProcessDescriptor descriptor = stmt.uploadProcessObject(process, 0);
                ((ProcessDescriptorImpl) descriptor).setPublishState(true);
                stmt.updateProcessDescriptor(descriptor);
            } catch (InvalidModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
    });

    //2?CallbackManagerinit?Webservice
    //TODO WorkflowServer?webservice

    //      WebServiceManager callbackManager = this.runtimeContext.getEngineModule(WebServiceManager.class, FpdlConstants.PROCESS_TYPE_FPDL20);
    //      try {
    //         callbackManager.publishAllCallbackServices();
    //      } catch (WebservicePublishException e1) {
    //         // TODO Auto-generated catch block
    //         e1.printStackTrace();
    //      }

    //JaxwsWebservice      
    Environment env = fireflowRuntimeContext.getEngineModule(Environment.class,
            FpdlConstants.PROCESS_TYPE_FPDL20);
    URL url = null;
    try {
        String contextPath = env.getWebserviceContextPath();
        if (!contextPath.startsWith("/")) {
            contextPath = "/" + contextPath;
        }
        if (!contextPath.endsWith("/")) {
            contextPath = contextPath + "/";
        }
        String address = "http://" + env.getWebserviceIP() + ":" + Integer.toString(env.getWebservicePort())
                + contextPath;

        url = new URL(address + serviceQName.getLocalPart() + "?wsdl");
    } catch (Exception e) {
        e.printStackTrace();
    }

    javax.xml.ws.Service jawsService = javax.xml.ws.Service.create(url, serviceQName);
    Dispatch<Source> dispatch = jawsService.createDispatch(portQName, Source.class,
            javax.xml.ws.Service.Mode.PAYLOAD);

    String messageStr = "<cal:acceptRequest  xmlns:cal=\"" + targetNsUri + "\">" + "<cal:id>" + bizId
            + "</cal:id>" + "<cal:approveResult>" + approveResult + "</cal:approveResult>"
            + "</cal:acceptRequest>";
    java.io.ByteArrayInputStream byteInStream = new java.io.ByteArrayInputStream(messageStr.getBytes());
    StreamSource source = new StreamSource(byteInStream);

    Source response = dispatch.invoke(source);

    DOMResult result = new DOMResult();
    //      StreamResult result = new StreamResult(System.out);
    Transformer transformer = null;
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformer = transformerFactory.newTransformer();
        transformer.transform(response, result);
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException("Couldn't parse response stream.", e);
    } catch (TransformerException e) {
        throw new RuntimeException("Couldn't parse response stream.", e);
    }

    Document theResponsePayload = (Document) result.getNode();
    Assert.assertNotNull(theResponsePayload);
    JXPathContext jxpathContext = JXPathContext.newContext(theResponsePayload);
    jxpathContext.registerNamespace("ns0", targetNsUri);
    String response2 = (String) jxpathContext.getValue("ns0:acceptResponse/ns0:response2");
    String response1 = (String) jxpathContext.getValue("ns0:acceptResponse/ns0:response1");
    Assert.assertEquals(responseResult, response2);

    Assert.assertNotNull(response1);

    this.processInstanceId = response1;

    this.assertResult(session);
}