Search in sources :

Example 61 with Task

use of org.wso2.carbon.humantask.core.dao.jpa.openjpa.model.Task in project carbon-business-process by wso2.

the class UserSubstitutionUtils method handleScheduledEventByTenant.

public static synchronized boolean handleScheduledEventByTenant(int tenantId) {
    boolean result = true;
    TransitivityResolver resolver = SubstitutionDataHolder.getInstance().getTransitivityResolver();
    ActivitiDAO activitiDAO = SubstitutionDataHolder.getInstance().getActivitiDAO();
    if (SubstitutionDataHolder.getInstance().isTransitivityEnabled()) {
        // update transitives, only the map is updated here
        result = resolver.resolveTransitiveSubs(true, tenantId);
    } else {
        resolver.subsMap = activitiDAO.selectActiveSubstitutesByTenant(tenantId, new Date(System.currentTimeMillis()));
    }
    // flush into db
    for (Map.Entry<String, SubstitutesDataModel> entry : resolver.subsMap.entrySet()) {
        // go through the updated map
        SubstitutesDataModel model = entry.getValue();
        try {
            // set carbon context
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext context = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            context.setUsername(model.getUser());
            context.setTenantId(tenantId, true);
            if (SubstitutionDataHolder.getInstance().isTransitivityEnabled()) {
                activitiDAO.updateSubstituteInfo(model);
            }
            if (!BPMNConstants.BULK_REASSIGN_PROCESSED.equals(model.getTaskList())) {
                // active substitution, not yet bulk reassigned
                String sub = getActualSubstitute(model);
                if (model.getTaskList() == null) {
                    // reassign all
                    if (sub != null) {
                        bulkReassign(model.getUser(), sub, null);
                    } else {
                        // transitivity undefined, assign to task owner or un-claim
                        assignToTaskOwner(model.getUser(), null);
                    }
                } else {
                    List<String> taskList = getTaskListFromString(model.getTaskList());
                    if (sub != null) {
                        bulkReassign(model.getUser(), sub, taskList);
                    } else {
                        // transitivity undefined, assign to task owner or un-claim
                        assignToTaskOwner(model.getUser(), taskList);
                    }
                }
                model.setTaskList(BPMNConstants.BULK_REASSIGN_PROCESSED);
                activitiDAO.updateSubstituteInfo(model);
            }
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
            PrivilegedCarbonContext.destroyCurrentContext();
        }
    }
    // disable expired records
    disableExpiredRecords(tenantId);
    return result;
}
Also used : PaginatedSubstitutesDataModel(org.wso2.carbon.bpmn.core.mgt.model.PaginatedSubstitutesDataModel) SubstitutesDataModel(org.wso2.carbon.bpmn.core.mgt.model.SubstitutesDataModel) ActivitiDAO(org.wso2.carbon.bpmn.core.mgt.dao.ActivitiDAO) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext)

Example 62 with Task

use of org.wso2.carbon.humantask.core.dao.jpa.openjpa.model.Task 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)

Example 63 with Task

use of org.wso2.carbon.humantask.core.dao.jpa.openjpa.model.Task in project carbon-business-process by wso2.

the class SOAPTask method execute.

@Override
public void execute(DelegateExecution execution) {
    String endpointURL;
    String payloadRequest;
    String version;
    String connection;
    String transferEncoding;
    String[] transportHeaderList;
    String action = "";
    String soapVersionURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
    List<Header> headerList = new ArrayList<Header>();
    try {
        if (serviceURL != null) {
            endpointURL = serviceURL.getValue(execution).toString();
        } else if (serviceRef != null) {
            String resourcePath = serviceRef.getValue(execution).toString();
            String registryPath;
            String tenantId = execution.getTenantId();
            Registry registry;
            if (resourcePath.startsWith(GOVERNANCE_REGISTRY_PREFIX)) {
                registryPath = resourcePath.substring(GOVERNANCE_REGISTRY_PREFIX.length());
                registry = BPMNExtensionsComponent.getRegistryService().getGovernanceSystemRegistry(Integer.parseInt(tenantId));
            } else if (resourcePath.startsWith(CONFIGURATION_REGISTRY_PREFIX)) {
                registryPath = resourcePath.substring(CONFIGURATION_REGISTRY_PREFIX.length());
                registry = BPMNExtensionsComponent.getRegistryService().getConfigSystemRegistry(Integer.parseInt(tenantId));
            } else {
                String msg = "Registry type is not specified for service reference in " + " serviceRef should begin with gov:/ or conf:/ to indicate the registry type.";
                throw new SOAPException(SOAP_INVOKE_ERROR_CODE, msg);
            }
            if (log.isDebugEnabled()) {
                log.debug("Reading endpoint from registry location: " + registryPath + " for task " + execution.getCurrentActivityName());
            }
            Resource urlResource = registry.get(registryPath);
            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);
                endpointURL = uep.getAddress();
            } else {
                String errorMsg = "Endpoint resource " + registryPath + " is not found. Failed to execute REST invocation in task " + execution.getCurrentActivityName();
                throw new SOAPException(SOAP_INVOKE_ERROR_CODE, errorMsg);
            }
        } else {
            String urlNotFoundErrorMsg = "Service URL is not provided. serviceURL must be provided.";
            throw new SOAPException(SOAP_INVOKE_ERROR_CODE, urlNotFoundErrorMsg);
        }
        if (payload != null) {
            payloadRequest = payload.getValue(execution).toString();
        } else {
            String payloadNotFoundErrorMsg = "Payload request is not provided. Payload must be provided.";
            throw new SOAPException(SOAP_INVOKE_ERROR_CODE, payloadNotFoundErrorMsg);
        }
        if (soapVersion != null) {
            version = soapVersion.getValue(execution).toString();
            if (version.equalsIgnoreCase(SOAP12_VERSION)) {
                soapVersionURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            } else if (version.equalsIgnoreCase(SOAP11_VERSION)) {
                soapVersionURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            } else {
                String invalidVersionErrorMsg = "Invalid soap version string specified";
                throw new SOAPException(SOAP_INVOKE_ERROR_CODE, invalidVersionErrorMsg);
            }
        }
        // Adding the connection
        Header connectionHeader = new Header();
        if (httpConnection != null) {
            connection = httpConnection.getValue(execution).toString();
            if (connection != null && !connection.trim().equals("Keep-Alive")) {
                log.debug("Setting Keep-Alive header ");
                connectionHeader.setName("Connection");
                connectionHeader.setValue(connection);
                headerList.add(connectionHeader);
            }
        }
        // Adding the additional transport headers
        if (transportHeaders != null) {
            String headerContent = transportHeaders.getValue(execution).toString();
            if (headerContent != null) {
                transportHeaderList = headerContent.split(",");
                for (String transportHeader : transportHeaderList) {
                    String[] pair = transportHeader.split(":");
                    Header additionalHeader = new Header();
                    if (pair.length == 1) {
                        additionalHeader.setName(pair[0]);
                        additionalHeader.setValue("");
                        if (log.isDebugEnabled()) {
                            log.debug("Adding transport headers " + pair[0]);
                        }
                    } else {
                        additionalHeader.setName(pair[0]);
                        additionalHeader.setValue(pair[1]);
                        if (log.isDebugEnabled()) {
                            log.debug("Adding transport headers " + pair[0] + " " + pair[1]);
                        }
                    }
                    headerList.add(additionalHeader);
                }
            }
        }
        // Adding the soap action
        if (soapAction != null) {
            action = soapAction.getValue(execution).toString();
            if (log.isDebugEnabled()) {
                log.debug("Setting soap action " + soapAction);
            }
        }
        // Converting the payload to an OMElement
        OMElement payLoad = AXIOMUtil.stringToOM(payloadRequest);
        // Creating the Service client
        ServiceClient sender = new ServiceClient();
        OMElement response;
        // Creating options to set the headers
        Options options = new Options();
        options.setTo(new EndpointReference(endpointURL));
        options.setAction(action);
        options.setSoapVersionURI(soapVersionURI);
        options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, headerList);
        // Adding the soap header block to the SOAP Header block when creating the SOAP Envelope
        if (headers != null) {
            String headerContent = headers.getValue(execution).toString();
            OMElement headerElement = AXIOMUtil.stringToOM(headerContent);
            sender.addHeader(headerElement);
            if (log.isDebugEnabled()) {
                log.debug("Adding soap header " + headerContent);
            }
        }
        // Adding the transfer encoding
        if (httpTransferEncoding != null) {
            transferEncoding = httpTransferEncoding.getValue(execution).toString();
            if (transferEncoding.equalsIgnoreCase("chunked")) {
                options.setProperty(HTTPConstants.CHUNKED, Boolean.TRUE);
                if (log.isDebugEnabled()) {
                    log.debug("Enabling transfer encoding chunked ");
                }
            } else {
                options.setProperty(HTTPConstants.CHUNKED, Boolean.FALSE);
                if (log.isDebugEnabled()) {
                    log.debug("Disabling transfer encoding chunked ");
                }
            }
        }
        sender.setOptions(options);
        // Invoking the endpoint
        response = sender.sendReceive(payLoad);
        // Getting the response as a string
        String responseStr = response.toStringWithConsume();
        if (outputVariable != null) {
            String outVarName = outputVariable.getValue(execution).toString();
            execution.setVariableLocal(outVarName, responseStr);
        } else {
            String outputNotFoundErrorMsg = "Output variable is not provided. " + "outputVariable must be provided to save " + "the response.";
            throw new SOAPException(SOAP_INVOKE_ERROR_CODE, outputNotFoundErrorMsg);
        }
    } catch (AxisFault axisFault) {
        log.error("Axis2 Fault", axisFault);
        throw new SOAPException(SOAP_INVOKE_ERROR_CODE, "Exception while getting response :" + axisFault.getMessage());
    } catch (XMLStreamException | RegistryException e) {
        log.error("Exception in processing", e);
        throw new SOAPException(SOAP_INVOKE_ERROR_CODE, "Exception in processing  :" + e.getMessage());
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) Options(org.apache.axis2.client.Options) ArrayList(java.util.ArrayList) Resource(org.wso2.carbon.registry.api.Resource) OMElement(org.apache.axiom.om.OMElement) Registry(org.wso2.carbon.registry.api.Registry) RegistryException(org.wso2.carbon.registry.api.RegistryException) UnifiedEndpointFactory(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpointFactory) EndpointReference(org.apache.axis2.addressing.EndpointReference) Header(org.apache.commons.httpclient.Header) XMLStreamException(javax.xml.stream.XMLStreamException) ServiceClient(org.apache.axis2.client.ServiceClient) UnifiedEndpoint(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpoint)

Example 64 with Task

use of org.wso2.carbon.humantask.core.dao.jpa.openjpa.model.Task in project carbon-business-process by wso2.

the class BaseExecutionService method createExecutionVariable.

protected Response createExecutionVariable(Execution execution, boolean override, int variableType, HttpServletRequest httpServletRequest, UriInfo uriInfo) {
    Object result = null;
    Response.ResponseBuilder responseBuilder = Response.ok();
    List<RestVariable> inputVariables = new ArrayList<>();
    List<RestVariable> resultVariables = new ArrayList<>();
    if (Utils.isApplicationJsonRequest(httpServletRequest)) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            @SuppressWarnings("unchecked") List<Object> variableObjects = (List<Object>) objectMapper.readValue(httpServletRequest.getInputStream(), List.class);
            for (Object restObject : variableObjects) {
                RestVariable restVariable = objectMapper.convertValue(restObject, RestVariable.class);
                inputVariables.add(restVariable);
            }
        } catch (Exception e) {
            throw new ActivitiIllegalArgumentException("Failed to serialize to a RestVariable instance", e);
        }
    } else if (Utils.isApplicationXmlRequest(httpServletRequest)) {
        JAXBContext jaxbContext = null;
        try {
            jaxbContext = JAXBContext.newInstance(RestVariableCollection.class);
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
            inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
            XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(new StreamSource(httpServletRequest.getInputStream()));
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            RestVariableCollection restVariableCollection = (RestVariableCollection) jaxbUnmarshaller.unmarshal(xmlReader);
            if (restVariableCollection == null) {
                throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a " + "RestVariable Collection instance.");
            }
            List<RestVariable> restVariableList = restVariableCollection.getRestVariables();
            if (restVariableList.size() == 0) {
                throw new ActivitiIllegalArgumentException("xml request body could not identify any rest " + "variables to be updated");
            }
            for (RestVariable restVariable : restVariableList) {
                inputVariables.add(restVariable);
            }
        } catch (JAXBException | IOException | XMLStreamException e) {
            throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a " + "RestVariable instance.", e);
        }
    }
    if (inputVariables.size() == 0) {
        throw new ActivitiIllegalArgumentException("Request didn't contain a list of variables to create.");
    }
    RestVariable.RestVariableScope sharedScope = null;
    RestVariable.RestVariableScope varScope = null;
    Map<String, Object> variablesToSet = new HashMap<String, Object>();
    for (RestVariable var : inputVariables) {
        // Validate if scopes match
        varScope = var.getVariableScope();
        if (var.getName() == null) {
            throw new ActivitiIllegalArgumentException("Variable name is required");
        }
        if (varScope == null) {
            varScope = RestVariable.RestVariableScope.LOCAL;
        }
        if (sharedScope == null) {
            sharedScope = varScope;
        }
        if (varScope != sharedScope) {
            throw new ActivitiIllegalArgumentException("Only allowed to update multiple variables in the same scope.");
        }
        if (!override && hasVariableOnScope(execution, var.getName(), varScope)) {
            throw new BPMNConflictException("Variable '" + var.getName() + "' is already present on execution '" + execution.getId() + "'.");
        }
        Object actualVariableValue = new RestResponseFactory().getVariableValue(var);
        variablesToSet.put(var.getName(), actualVariableValue);
        resultVariables.add(new RestResponseFactory().createRestVariable(var.getName(), actualVariableValue, varScope, execution.getId(), variableType, false, uriInfo.getBaseUri().toString()));
    }
    if (!variablesToSet.isEmpty()) {
        RuntimeService runtimeService = BPMNOSGIService.getRuntimeService();
        if (sharedScope == RestVariable.RestVariableScope.LOCAL) {
            runtimeService.setVariablesLocal(execution.getId(), variablesToSet);
        } else {
            if (execution.getParentId() != null) {
                // Explicitly set on parent, setting non-local variables on execution itself will override local-variables if exists
                runtimeService.setVariables(execution.getParentId(), variablesToSet);
            } else {
                // Standalone task, no global variables possible
                throw new ActivitiIllegalArgumentException("Cannot set global variables on execution '" + execution.getId() + "', task is not part of process.");
            }
        }
    }
    RestVariableCollection restVariableCollection = new RestVariableCollection();
    restVariableCollection.setRestVariables(resultVariables);
    responseBuilder.entity(restVariableCollection);
    return responseBuilder.status(Response.Status.CREATED).build();
}
Also used : BPMNConflictException(org.wso2.carbon.bpmn.rest.common.exception.BPMNConflictException) XMLStreamReader(javax.xml.stream.XMLStreamReader) JAXBContext(javax.xml.bind.JAXBContext) RestVariable(org.wso2.carbon.bpmn.rest.engine.variable.RestVariable) ActivitiIllegalArgumentException(org.activiti.engine.ActivitiIllegalArgumentException) Unmarshaller(javax.xml.bind.Unmarshaller) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory) RuntimeService(org.activiti.engine.RuntimeService) StreamSource(javax.xml.transform.stream.StreamSource) ActivitiException(org.activiti.engine.ActivitiException) BPMNContentNotSupportedException(org.wso2.carbon.bpmn.rest.common.exception.BPMNContentNotSupportedException) XMLStreamException(javax.xml.stream.XMLStreamException) ActivitiObjectNotFoundException(org.activiti.engine.ActivitiObjectNotFoundException) BPMNConflictException(org.wso2.carbon.bpmn.rest.common.exception.BPMNConflictException) ActivitiIllegalArgumentException(org.activiti.engine.ActivitiIllegalArgumentException) JAXBException(javax.xml.bind.JAXBException) DataResponse(org.wso2.carbon.bpmn.rest.model.common.DataResponse) Response(javax.ws.rs.core.Response) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 65 with Task

use of org.wso2.carbon.humantask.core.dao.jpa.openjpa.model.Task in project carbon-business-process by wso2.

the class AnalyticsConfigurationService method configureTaskLevelEvents.

@PUT
@Path("/processes/{process_id}/tasks/{task_id}")
@Consumes({ MediaType.APPLICATION_JSON })
public void configureTaskLevelEvents(@PathParam("process_id") String processDefinitionId, @PathParam("task_id") String taskId, DataPublisherConfig dataPublisherConfig) {
    try {
        RepositoryService repositoryService = BPMNOSGIService.getRepositoryService();
        ProcessDefinition process = repositoryService.getProcessDefinition(processDefinitionId);
        if (process != null && process instanceof ProcessDefinitionEntity) {
            ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) process;
            Map<String, TaskDefinition> taskDefinitions = processDefinitionEntity.getTaskDefinitions();
            TaskDefinition taskDefinition = taskDefinitions.get(taskId);
            if (taskDefinition != null) {
                if (dataPublisherConfig.isEnabled()) {
                    List<TaskListener> completionListeners = taskDefinition.getTaskListener(TaskListener.EVENTNAME_COMPLETE);
                    TaskListener taskCompletionListener = null;
                    for (TaskListener listener : completionListeners) {
                        if (listener instanceof TaskCompletionListener) {
                            taskCompletionListener = listener;
                            break;
                        }
                    }
                    if (taskCompletionListener == null) {
                        if (log.isDebugEnabled()) {
                            log.debug("Adding task completion listener to task: " + taskId + " of process: " + processDefinitionId);
                        }
                        taskDefinition.addTaskListener(TaskListener.EVENTNAME_COMPLETE, new TaskCompletionListener());
                    }
                } else {
                    List<TaskListener> completionListeners = taskDefinition.getTaskListener(TaskListener.EVENTNAME_COMPLETE);
                    TaskListener taskCompletionListener = null;
                    for (TaskListener listener : completionListeners) {
                        if (listener instanceof TaskCompletionListener) {
                            taskCompletionListener = listener;
                            break;
                        }
                    }
                    if (taskCompletionListener != null) {
                        if (log.isDebugEnabled()) {
                            log.debug("Removing task completion listener from task: " + taskId + " of process: " + processDefinitionId);
                        }
                        completionListeners.remove(taskCompletionListener);
                    }
                }
            }
        }
    } catch (Exception e) {
        String msg = "Failed to configure events for task: " + taskId + " of process: " + processDefinitionId;
        log.error(msg, e);
        throw new BPMNRestException(msg, e);
    }
}
Also used : TaskCompletionListener(org.wso2.carbon.bpmn.analytics.publisher.listeners.TaskCompletionListener) TaskDefinition(org.activiti.engine.impl.task.TaskDefinition) TaskListener(org.activiti.engine.delegate.TaskListener) ProcessDefinition(org.activiti.engine.repository.ProcessDefinition) BPMNRestException(org.wso2.carbon.bpmn.rest.common.exception.BPMNRestException) ProcessDefinitionEntity(org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity) BPMNRestException(org.wso2.carbon.bpmn.rest.common.exception.BPMNRestException) RepositoryService(org.activiti.engine.RepositoryService)

Aggregations

HumanTaskRuntimeException (org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskRuntimeException)41 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)35 HumanTaskIllegalAccessException (org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalAccessException)28 HumanTaskIllegalArgumentException (org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalArgumentException)28 HumanTaskIllegalStateException (org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalStateException)28 UserStoreException (org.wso2.carbon.user.core.UserStoreException)28 TaskDAO (org.wso2.carbon.humantask.core.dao.TaskDAO)27 HumanTaskException (org.wso2.carbon.humantask.core.engine.HumanTaskException)27 RestResponseFactory (org.wso2.carbon.bpmn.rest.common.RestResponseFactory)25 BaseTaskService (org.wso2.carbon.bpmn.rest.service.base.BaseTaskService)25 HumanTaskIllegalOperationException (org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalOperationException)25 ArrayList (java.util.ArrayList)14 RestVariable (org.wso2.carbon.bpmn.rest.engine.variable.RestVariable)13 Element (org.w3c.dom.Element)12 QName (javax.xml.namespace.QName)11 HistoricTaskInstance (org.activiti.engine.history.HistoricTaskInstance)11 IOException (java.io.IOException)9 HumanTaskEngine (org.wso2.carbon.humantask.core.engine.HumanTaskEngine)9 AxisFault (org.apache.axis2.AxisFault)8 HumanTaskDeploymentException (org.wso2.carbon.humantask.core.deployment.HumanTaskDeploymentException)8