Search in sources :

Example 36 with Node

use of org.wso2.charon3.core.utils.codeutils.Node in project carbon-business-process by wso2.

the class JsonNodeObject method jsonPath.

/**
 * Function to evaluate jsonpath over JsonNodeObject
 * @param jsonPathStr jsonpath
 * @return returns the evaluation result. The returned Object can be a
 *                      com.fasterxml.jackson.databind.JsonNode (in case the result is json object)
 *                      com.fasterxml.jackson.databind.node.ArrayNode (in case the result is json array)
 *                      Or main primitive data types (String, Integer, Byte, Character, Short, Long, Float, Double, Boolean)
 *                 This function returns new Object representing the evaluation results, no a reference to a node
 * @throws IOException
 * @throws BPMNJsonException is thrown if the the resulting data type cannot be identified
 */
public Object jsonPath(String jsonPathStr) throws IOException, BPMNJsonException {
    ObjectMapper mapper = new ObjectMapper();
    Map map = mapper.convertValue(jsonNode, Map.class);
    Object result = JsonPath.read(map, jsonPathStr);
    JsonBuilder builder = new JsonBuilder(mapper);
    if (result instanceof Map) {
        // If the result is a Map, then it should be a json object
        return builder.createJsonNodeFromMap((Map<String, Object>) result);
    } else if (result instanceof List) {
        // when result is a list, then it should be a json array
        return builder.createJsonArrayFromMap((List<Object>) result);
    } else if (result == null || result instanceof String || result instanceof Integer || result instanceof Byte || result instanceof Character || result instanceof Short || result instanceof Long || result instanceof Float || result instanceof Double || result instanceof Boolean) {
        // If result is primitive data type, then return it as it is
        return result;
    } else {
        // Un-filtered data type, considered as unknown types
        throw new BPMNJsonException("Unknown type data type: " + result.getClass().getName() + " resulted while evaluating json path");
    }
}
Also used : BPMNJsonException(org.wso2.carbon.bpmn.core.types.datatypes.json.BPMNJsonException) List(java.util.List) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 37 with Node

use of org.wso2.charon3.core.utils.codeutils.Node in project carbon-business-process by wso2.

the class LiteralBasedOrgEntityProvider method getOrganizationalEntities.

public List<OrganizationalEntityDAO> getOrganizationalEntities(PeopleQueryEvaluator peopleQueryEvaluator, TFrom tFrom, EvaluationContext evaluationContext) {
    TLiteral literal = tFrom.getLiteral();
    List<OrganizationalEntityDAO> orgEntityList = new ArrayList<OrganizationalEntityDAO>();
    Element domNode = (Element) literal.getDomNode();
    if (domNode != null) {
        NodeList orgEntityNodes = domNode.getElementsByTagNameNS(HumanTaskConstants.organizationalEntityQname.getNamespaceURI(), HumanTaskConstants.organizationalEntityQname.getLocalPart());
        // There should be only one organizational Entity
        if (orgEntityNodes.getLength() == 1) {
            Node orgEntityNode = orgEntityNodes.item(0);
            addOrgEntitiesForOrganizationEntityNode(orgEntityNode, peopleQueryEvaluator, orgEntityList);
        } else {
            NodeList elements = domNode.getElementsByTagNameNS(HumanTaskConstants.userQname.getNamespaceURI(), HumanTaskConstants.userQname.getLocalPart());
            if (elements.getLength() == 1) {
                // There should only be one user element
                CommonTaskUtil.addOrgEntityForUserNode(elements.item(0), peopleQueryEvaluator, orgEntityList);
            }
        }
    }
    return orgEntityList;
}
Also used : TLiteral(org.wso2.carbon.humantask.TLiteral) OrganizationalEntityDAO(org.wso2.carbon.humantask.core.dao.OrganizationalEntityDAO) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList)

Example 38 with Node

use of org.wso2.charon3.core.utils.codeutils.Node in project charon by wso2.

the class GroupResourceManager method listWithGET.

/*
     * Method to list the groups at the /Groups endpoint
     *
     * @param usermanager
     * @param filter
     * @param startIndex
     * @param count
     * @param sortBy
     * @param sortOrder
     * @param attributes
     * @param excludeAttributes
     * @return
     */
@Override
public SCIMResponse listWithGET(UserManager userManager, String filter, int startIndex, int count, String sortBy, String sortOrder, String attributes, String excludeAttributes) {
    // According to SCIM 2.0 spec minus values will be considered as 0
    if (count < 0) {
        count = 0;
    }
    // According to SCIM 2.0 spec minus values will be considered as 1
    if (startIndex < 1) {
        startIndex = 1;
    }
    FilterTreeManager filterTreeManager = null;
    Node rootNode = null;
    JSONEncoder encoder = null;
    try {
        // check whether provided sortOrder is valid or not
        if (sortOrder != null) {
            if (!(sortOrder.equalsIgnoreCase(SCIMConstants.OperationalConstants.ASCENDING) || sortOrder.equalsIgnoreCase(SCIMConstants.OperationalConstants.DESCENDING))) {
                String error = " Invalid sortOrder value is specified";
                throw new BadRequestException(error, ResponseCodeConstants.INVALID_VALUE);
            }
        }
        // ascending.
        if (sortOrder == null && sortBy != null) {
            sortOrder = SCIMConstants.OperationalConstants.ASCENDING;
        }
        // unless configured returns core-user schema or else returns extended user schema)
        SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema();
        if (filter != null) {
            filterTreeManager = new FilterTreeManager(filter, schema);
            rootNode = filterTreeManager.buildTree();
        }
        // obtain the json encoder
        encoder = getEncoder();
        // get the URIs of required attributes which must be given a value
        Map<String, Boolean> requiredAttributes = ResourceManagerUtil.getOnlyRequiredAttributesURIs((SCIMResourceTypeSchema) CopyUtil.deepCopy(schema), attributes, excludeAttributes);
        List<Object> returnedGroups;
        int totalResults = 0;
        // API group should pass a usermanager usermanager to GroupResourceEndpoint.
        if (userManager != null) {
            List<Object> tempList = userManager.listGroupsWithGET(rootNode, startIndex, count, sortBy, sortOrder, requiredAttributes);
            totalResults = (int) tempList.get(0);
            tempList.remove(0);
            returnedGroups = tempList;
            for (Object group : returnedGroups) {
                // perform service provider side validation.
                ServerSideValidator.validateRetrievedSCIMObjectInList((Group) group, SCIMSchemaDefinitions.SCIM_GROUP_SCHEMA, attributes, excludeAttributes);
            }
            // create a listed resource object out of the returned groups list.
            ListedResource listedResource = createListedResource(returnedGroups, startIndex, totalResults);
            // convert the listed resource into specific format.
            String encodedListedResource = encoder.encodeSCIMObject(listedResource);
            // if there are any http headers to be added in the response header.
            Map<String, String> responseHeaders = new HashMap<String, String>();
            responseHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON);
            return new SCIMResponse(ResponseCodeConstants.CODE_OK, encodedListedResource, responseHeaders);
        } else {
            String error = "Provided user manager handler is null.";
            // throw internal server error.
            throw new InternalErrorException(error);
        }
    } catch (CharonException e) {
        return encodeSCIMException(e);
    } catch (NotFoundException e) {
        return encodeSCIMException(e);
    } catch (InternalErrorException e) {
        return encodeSCIMException(e);
    } catch (BadRequestException e) {
        return encodeSCIMException(e);
    } catch (NotImplementedException e) {
        return encodeSCIMException(e);
    } catch (IOException e) {
        String error = "Error in tokenization of the input filter";
        CharonException charonException = new CharonException(error);
        return AbstractResourceManager.encodeSCIMException(charonException);
    }
}
Also used : HashMap(java.util.HashMap) Node(org.wso2.charon3.core.utils.codeutils.Node) NotImplementedException(org.wso2.charon3.core.exceptions.NotImplementedException) NotFoundException(org.wso2.charon3.core.exceptions.NotFoundException) InternalErrorException(org.wso2.charon3.core.exceptions.InternalErrorException) IOException(java.io.IOException) FilterTreeManager(org.wso2.charon3.core.utils.codeutils.FilterTreeManager) ListedResource(org.wso2.charon3.core.objects.ListedResource) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) JSONEncoder(org.wso2.charon3.core.encoder.JSONEncoder) SCIMResourceTypeSchema(org.wso2.charon3.core.schema.SCIMResourceTypeSchema) CharonException(org.wso2.charon3.core.exceptions.CharonException) SCIMResponse(org.wso2.charon3.core.protocol.SCIMResponse)

Example 39 with Node

use of org.wso2.charon3.core.utils.codeutils.Node in project carbon-business-process by wso2.

the class AnalyticsPublisherExtensionOperation method evaluateXPathExpression.

private String evaluateXPathExpression(ExtensionContext context, String xpath, Element element) throws FaultException {
    String result = "";
    QName qnVariableData = new QName(Namespaces.BPEL11_NS, "getVariableData");
    QName qnGetVariableProperty = new QName(Namespaces.BPEL11_NS, "getVariableProperty");
    QName qnGetLinkStatus = new QName(Namespaces.BPEL11_NS, "getLinkStatus");
    QName qnDoXslTransform = new QName(Namespaces.BPEL11_NS, "getDoXslTransform");
    OXPath20ExpressionBPEL20 oexpr = new OXPath20ExpressionBPEL20(context.getInternalInstance().getProcessModel().getOwner(), qnVariableData, qnGetVariableProperty, qnGetLinkStatus, qnDoXslTransform, false);
    OExpressionLanguage oExpressionLanguage = new OExpressionLanguage(context.getProcessModel().getOwner(), null);
    oExpressionLanguage.expressionLanguageUri = "urn:oasis:names:tc:wsbpel:2.0:sublang:xpath2.0";
    oexpr.expressionLanguage = oExpressionLanguage;
    oExpressionLanguage.properties.put("runtime-class", "org.apache.ode.bpel.elang.xpath20.runtime.XPath20ExpressionRuntime");
    try {
        context.getInternalInstance().getExpLangRuntime().registerRuntime(oExpressionLanguage);
    } catch (ConfigurationException ex) {
        String errMsg = "Error when trying to register xpath runtime";
        log.error(errMsg, ex);
        handleException(errMsg, ex);
    }
    oexpr.insertMissingData = true;
    ScopeFrame scopeFrame = ((ExtensionContextImpl) context).getScopeFrame();
    ExprEvaluationContextImpl exprEvaluationContext = new ExprEvaluationContextImpl(scopeFrame, context.getInternalInstance());
    oexpr.vars = (HashMap) context.getVisibleVariables();
    oexpr.namespaceCtx = context.getProcessModel().namespaceContext;
    try {
        oexpr.xpath = xpath;
        List resultList = context.getInternalInstance().getExpLangRuntime().evaluate(oexpr, exprEvaluationContext);
        if (result != null) {
            Iterator iterator = resultList.iterator();
            /**
             * for analytics publishing to work, there should only be a single node here
             */
            while (iterator.hasNext()) {
                Node node = ((Node) iterator.next());
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    result += node.getTextContent();
                } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
                    result += node.getNodeValue();
                }
            }
        }
    } catch (EvaluationException e) {
        String errMsg = "Xpath evaluation failed";
        log.error(errMsg);
        handleException(errMsg, e);
    }
    return result;
}
Also used : DataEndpointConfigurationException(org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException) ConfigurationException(org.apache.ode.bpel.explang.ConfigurationException) DataEndpointAgentConfigurationException(org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException) ScopeFrame(org.apache.ode.bpel.runtime.ScopeFrame) QName(javax.xml.namespace.QName) OXPath20ExpressionBPEL20(org.apache.ode.bpel.elang.xpath20.o.OXPath20ExpressionBPEL20) Node(org.w3c.dom.Node) Iterator(java.util.Iterator) ExtensionContextImpl(org.apache.ode.bpel.runtime.ExtensionContextImpl) NodeList(org.w3c.dom.NodeList) List(java.util.List) EvaluationException(org.apache.ode.bpel.explang.EvaluationException) ExprEvaluationContextImpl(org.apache.ode.bpel.runtime.ExprEvaluationContextImpl) OExpressionLanguage(org.apache.ode.bpel.o.OExpressionLanguage)

Example 40 with Node

use of org.wso2.charon3.core.utils.codeutils.Node in project carbon-business-process by wso2.

the class AnalyticsPublisherExtensionOperation method fillDataArray.

private void fillDataArray(Object[] dataArray, List<AnalyticsKey> payloadAnalyticsKeyList, int startIndex, ExtensionContext context, Element element) throws FaultException {
    for (int i = 0; i < payloadAnalyticsKeyList.size(); i++) {
        AnalyticsKey analyticsKey = payloadAnalyticsKeyList.get(i);
        if (analyticsKey.getExpression() != null) {
            String expression = evaluateXPathExpression(context, analyticsKey.getExpression(), element);
            convertDataType(dataArray, (i + startIndex), analyticsKey, expression);
        } else if (analyticsKey.getVariable() != null && analyticsKey.getPart() == null) {
            if (analyticsKey.getQuery() == null) {
                String variable = context.readVariable(analyticsKey.getVariable()).getTextContent();
                convertDataType(dataArray, (i + startIndex), analyticsKey, variable);
            /* simple types should be specified for here */
            } else {
                String errMsg = "This functionality is currently not supported";
                log.error(errMsg);
                handleException(errMsg);
            }
        } else if (analyticsKey.getVariable() != null && analyticsKey.getPart() != null) {
            NodeList childNodes = context.readVariable(analyticsKey.getVariable()).getChildNodes();
            String result = null;
            String part = analyticsKey.getPart();
            for (int j = 0; j < childNodes.getLength(); j++) {
                Node item = childNodes.item(j);
                if (item != null && item.getNodeType() == Node.ELEMENT_NODE && item.getLocalName().equals(part)) {
                    /* remove the payload part */
                    result = DOMUtils.domToString(DOMUtils.getFirstChildElement(item));
                }
            }
            convertDataType(dataArray, (i + startIndex), analyticsKey, result);
            dataArray[i + startIndex] = result;
        }
    }
}
Also used : AnalyticsKey(org.wso2.carbon.bpel.core.ode.integration.config.analytics.AnalyticsKey) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node)

Aggregations

ArrayList (java.util.ArrayList)19 Node (org.w3c.dom.Node)13 BLangVariable (org.wso2.ballerinalang.compiler.tree.BLangVariable)13 BLangRecordLiteral (org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral)13 List (java.util.List)12 SymbolEnv (org.wso2.ballerinalang.compiler.semantics.model.SymbolEnv)11 Map (java.util.Map)10 BLangNode (org.wso2.ballerinalang.compiler.tree.BLangNode)10 DiagnosticPos (org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos)10 QName (javax.xml.namespace.QName)8 NodeList (org.w3c.dom.NodeList)8 BLangExpression (org.wso2.ballerinalang.compiler.tree.expressions.BLangExpression)8 Name (org.wso2.ballerinalang.compiler.util.Name)8 Arrays (java.util.Arrays)7 HashMap (java.util.HashMap)7 AnnotationAttachmentNode (org.ballerinalang.model.tree.AnnotationAttachmentNode)7 Node (org.ballerinalang.model.tree.Node)7 BLangEndpoint (org.wso2.ballerinalang.compiler.tree.BLangEndpoint)7 BLangFunction (org.wso2.ballerinalang.compiler.tree.BLangFunction)7 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)7