Search in sources :

Example 1 with BPMNJsonException

use of org.wso2.carbon.bpmn.core.types.datatypes.json.BPMNJsonException 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 2 with BPMNJsonException

use of org.wso2.carbon.bpmn.core.types.datatypes.json.BPMNJsonException in project carbon-business-process by wso2.

the class RESTTask method execute.

@Override
public void execute(DelegateExecution execution) {
    if (method == null) {
        String error = "HTTP method for the REST task not found. Please specify the \"method\" form property.";
        throw new RESTClientException(error);
    }
    if (log.isDebugEnabled()) {
        if (serviceURL != null) {
            log.debug("Executing RESTInvokeTask " + method.getValue(execution).toString() + " - " + serviceURL.getValue(execution).toString());
        } else if (serviceRef != null) {
            log.debug("Executing RESTInvokeTask " + method.getValue(execution).toString() + " - " + serviceRef.getValue(execution).toString());
        }
    }
    RESTInvoker restInvoker = BPMNRestExtensionHolder.getInstance().getRestInvoker();
    RESTResponse response;
    String url = null;
    String bUsername = null;
    String bPassword = null;
    JsonNodeObject jsonHeaders = null;
    boolean contentAvailable = false;
    try {
        if (serviceURL != null) {
            url = serviceURL.getValue(execution).toString();
            if (basicAuthUsername != null && basicAuthPassword != null) {
                bUsername = basicAuthUsername.getValue(execution).toString();
                bPassword = basicAuthPassword.getValue(execution).toString();
            }
        } else if (serviceRef != null) {
            String resourcePath = serviceRef.getValue(execution).toString();
            String registryPath;
            int tenantIdInt = Integer.parseInt(execution.getTenantId());
            RealmService realmService = RegistryContext.getBaseInstance().getRealmService();
            String domain = realmService.getTenantManager().getDomain(tenantIdInt);
            Registry registry;
            Resource urlResource;
            try {
                PrivilegedCarbonContext.startTenantFlow();
                if (domain != null) {
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(domain);
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantIdInt);
                } else {
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantIdInt);
                }
                if (resourcePath.startsWith(GOVERNANCE_REGISTRY_PREFIX)) {
                    registryPath = resourcePath.substring(GOVERNANCE_REGISTRY_PREFIX.length());
                    registry = BPMNExtensionsComponent.getRegistryService().getGovernanceSystemRegistry(tenantIdInt);
                } else if (resourcePath.startsWith(CONFIGURATION_REGISTRY_PREFIX)) {
                    registryPath = resourcePath.substring(CONFIGURATION_REGISTRY_PREFIX.length());
                    registry = BPMNExtensionsComponent.getRegistryService().getConfigSystemRegistry(tenantIdInt);
                } else {
                    String msg = "Registry type is not specified for service reference in " + getTaskDetails(execution) + ". serviceRef should begin with gov:/ or conf:/ to indicate the registry type.";
                    throw new RESTClientException(msg);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Reading endpoint from registry location: " + registryPath + " for task " + getTaskDetails(execution));
                }
                urlResource = registry.get(registryPath);
            } finally {
                PrivilegedCarbonContext.endTenantFlow();
            }
            if (urlResource != null) {
                String uepContent = new String((byte[]) urlResource.getContent(), Charset.defaultCharset());
                UnifiedEndpointFactory uepFactory = new UnifiedEndpointFactory();
                OMElement uepElement = AXIOMUtil.stringToOM(uepContent);
                UnifiedEndpoint uep = uepFactory.createEndpoint(uepElement);
                url = uep.getAddress();
                bUsername = uep.getAuthorizationUserName();
                bPassword = uep.getAuthorizationPassword();
            } else {
                String errorMsg = "Endpoint resource " + registryPath + " is not found. Failed to execute REST invocation in task " + getTaskDetails(execution);
                throw new RESTClientException(errorMsg);
            }
        } else {
            String urlNotFoundErrorMsg = "Service URL is not provided for " + getTaskDetails(execution) + ". serviceURL or serviceRef must be provided.";
            throw new RESTClientException(urlNotFoundErrorMsg);
        }
        if (headers != null) {
            String headerContent = headers.getValue(execution).toString();
            jsonHeaders = JSONUtils.parse(headerContent);
        }
        if (POST_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
            String inputContent = input.getValue(execution).toString();
            response = restInvoker.invokePOST(new URI(url), jsonHeaders, bUsername, bPassword, inputContent);
        } else if (GET_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
            response = restInvoker.invokeGET(new URI(url), jsonHeaders, bUsername, bPassword);
        } else if (PUT_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
            String inputContent = input.getValue(execution).toString();
            response = restInvoker.invokePUT(new URI(url), jsonHeaders, bUsername, bPassword, inputContent);
        } else if (DELETE_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
            response = restInvoker.invokeDELETE(new URI(url), jsonHeaders, bUsername, bPassword);
        } else {
            String errorMsg = "Unsupported http method. The REST task only supports GET, POST, PUT and DELETE operations";
            throw new RESTClientException(errorMsg);
        }
        Object output = response.getContent();
        if (output != null) {
            contentAvailable = !response.getContent().equals("");
        }
        boolean contentTypeAvailable = false;
        if (response.getContentType() != null) {
            contentTypeAvailable = true;
        }
        if (contentAvailable && contentTypeAvailable && response.getContentType().contains(APPLICATION_JSON)) {
            output = JSONUtils.parse(String.valueOf(output));
        } else if (contentAvailable && contentTypeAvailable && response.getContentType().contains(APPLICATION_XML)) {
            output = Utils.parse(String.valueOf(output));
        } else {
            output = StringEscapeUtils.escapeXml(String.valueOf(output));
        }
        if (outputVariable != null) {
            String outVarName = outputVariable.getValue(execution).toString();
            execution.setVariable(outVarName, output);
        } else if (outputMappings != null) {
            String outMappings = outputMappings.getValue(execution).toString();
            outMappings = outMappings.trim();
            String[] mappings = outMappings.split(",");
            for (String mapping : mappings) {
                String[] mappingParts = mapping.split(":");
                String varName = mappingParts[0];
                String expression = mappingParts[1];
                Object value;
                if (output instanceof JsonNodeObject) {
                    value = ((JsonNodeObject) output).jsonPath(expression);
                } else {
                    value = ((XMLDocument) output).xPath(expression);
                }
                execution.setVariable(varName, value);
            }
        } else {
            String outputNotFoundErrorMsg = "An outputVariable or outputMappings is not provided. " + "Either an output variable or output mappings  must be provided to save " + "the response.";
            throw new RESTClientException(outputNotFoundErrorMsg);
        }
        if (responseHeaderVariable != null) {
            StringBuilder headerJsonStr = new StringBuilder();
            headerJsonStr.append("{");
            String prefix = "";
            for (Header header : response.getHeaders()) {
                headerJsonStr.append(prefix);
                String name = header.getName().replaceAll("\"", "");
                String value = header.getValue().replaceAll("\"", "");
                headerJsonStr.append("\"").append(name).append("\":\"").append(value).append("\"");
                prefix = ",";
            }
            headerJsonStr.append("}");
            JsonNodeObject headerJson = JSONUtils.parse(headerJsonStr.toString());
            execution.setVariable(responseHeaderVariable.getValue(execution).toString(), headerJson);
        }
        if (httpStatusVariable != null) {
            execution.setVariable(httpStatusVariable.getValue(execution).toString(), response.getHttpStatus());
        }
    } catch (RegistryException | XMLStreamException | URISyntaxException | IOException | SAXException | ParserConfigurationException e) {
        String errorMessage = "Failed to execute " + method.getValue(execution).toString() + " " + url + " within task " + getTaskDetails(execution);
        log.error(errorMessage, e);
        throw new RESTClientException(REST_INVOKE_ERROR, errorMessage);
    } catch (BPMNJsonException | BPMNXmlException e) {
        String errorMessage = "Failed to extract values for output mappings, the response content" + " doesn't support the expression" + method.getValue(execution).toString() + " " + url + " within task " + getTaskDetails(execution);
        log.error(errorMessage, e);
        throw new RESTClientException(REST_INVOKE_ERROR, errorMessage);
    } catch (UserStoreException e) {
        String errorMessage = "Failed to obtain tenant domain information";
        log.error(errorMessage, e);
        throw new RESTClientException(REST_INVOKE_ERROR, errorMessage);
    }
}
Also used : BPMNJsonException(org.wso2.carbon.bpmn.core.types.datatypes.json.BPMNJsonException) JsonNodeObject(org.wso2.carbon.bpmn.core.types.datatypes.json.api.JsonNodeObject) OMElement(org.apache.axiom.om.OMElement) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) UnifiedEndpointFactory(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpointFactory) XMLDocument(org.wso2.carbon.bpmn.core.types.datatypes.xml.api.XMLDocument) SAXException(org.xml.sax.SAXException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Resource(org.wso2.carbon.registry.api.Resource) Registry(org.wso2.carbon.registry.api.Registry) IOException(java.io.IOException) RegistryException(org.wso2.carbon.registry.api.RegistryException) Header(org.apache.http.Header) XMLStreamException(javax.xml.stream.XMLStreamException) RealmService(org.wso2.carbon.user.core.service.RealmService) UnifiedEndpoint(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpoint) JsonNodeObject(org.wso2.carbon.bpmn.core.types.datatypes.json.api.JsonNodeObject) BPMNXmlException(org.wso2.carbon.bpmn.core.types.datatypes.xml.BPMNXmlException)

Aggregations

BPMNJsonException (org.wso2.carbon.bpmn.core.types.datatypes.json.BPMNJsonException)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 IOException (java.io.IOException)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 List (java.util.List)1 Map (java.util.Map)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 XMLStreamException (javax.xml.stream.XMLStreamException)1 OMElement (org.apache.axiom.om.OMElement)1 Header (org.apache.http.Header)1 JsonNodeObject (org.wso2.carbon.bpmn.core.types.datatypes.json.api.JsonNodeObject)1 BPMNXmlException (org.wso2.carbon.bpmn.core.types.datatypes.xml.BPMNXmlException)1 XMLDocument (org.wso2.carbon.bpmn.core.types.datatypes.xml.api.XMLDocument)1 Registry (org.wso2.carbon.registry.api.Registry)1 RegistryException (org.wso2.carbon.registry.api.RegistryException)1 Resource (org.wso2.carbon.registry.api.Resource)1 UnifiedEndpoint (org.wso2.carbon.unifiedendpoint.core.UnifiedEndpoint)1 UnifiedEndpointFactory (org.wso2.carbon.unifiedendpoint.core.UnifiedEndpointFactory)1 UserStoreException (org.wso2.carbon.user.api.UserStoreException)1