Search in sources :

Example 56 with Scope

use of org.wso2.ballerinalang.compiler.semantics.model.Scope in project carbon-business-process by wso2.

the class WorkflowTaskService method deleteVariable.

@DELETE
@Path("/{taskId}/variables/{variableName}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response deleteVariable(@PathParam("taskId") String taskId, @PathParam("variableName") String variableName) {
    String scopeString = uriInfo.getQueryParameters().getFirst("scope");
    Task task = getTaskFromRequest(taskId);
    // Determine scope
    RestVariable.RestVariableScope scope = RestVariable.RestVariableScope.LOCAL;
    if (scopeString != null) {
        scope = RestVariable.getScopeFromString(scopeString);
    }
    if (!hasVariableOnScope(task, variableName, scope)) {
        throw new ActivitiObjectNotFoundException("Task '" + task.getId() + "' doesn't have a variable '" + variableName + "' in scope " + scope.name().toLowerCase(), VariableInstanceEntity.class);
    }
    RuntimeService runtimeService = BPMNOSGIService.getRuntimeService();
    TaskService taskService = BPMNOSGIService.getTaskService();
    if (scope == RestVariable.RestVariableScope.LOCAL) {
        taskService.removeVariableLocal(task.getId(), variableName);
    } else {
        // Safe to use executionId, as the hasVariableOnScope whould have stopped a global-var update on standalone task
        runtimeService.removeVariable(task.getExecutionId(), variableName);
    }
    return Response.ok().status(Response.Status.NO_CONTENT).build();
}
Also used : RestVariable(org.wso2.carbon.bpmn.rest.engine.variable.RestVariable) BaseTaskService(org.wso2.carbon.bpmn.rest.service.base.BaseTaskService)

Example 57 with Scope

use of org.wso2.ballerinalang.compiler.semantics.model.Scope in project carbon-business-process by wso2.

the class WorkflowTaskService method createTaskVariable.

@POST
@Path("/{taskId}/variables")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response createTaskVariable(@PathParam("taskId") String taskId, @Context HttpServletRequest httpServletRequest) {
    Task task = getTaskFromRequest(taskId);
    List<RestVariable> inputVariables = new ArrayList<>();
    List<RestVariable> resultVariables = new ArrayList<>();
    Response.ResponseBuilder responseBuilder = Response.ok();
    try {
        if (Utils.isApplicationJsonRequest(httpServletRequest)) {
            try {
                @SuppressWarnings("unchecked") List<Object> variableObjects = (List<Object>) new ObjectMapper().readValue(httpServletRequest.getInputStream(), List.class);
                for (Object restObject : variableObjects) {
                    RestVariable restVariable = new ObjectMapper().convertValue(restObject, RestVariable.class);
                    inputVariables.add(restVariable);
                }
            } catch (IOException e) {
                throw new ActivitiIllegalArgumentException("request body could not be transformed to a RestVariable " + "instance.", e);
            }
        } else if (Utils.isApplicationXmlRequest(httpServletRequest)) {
            JAXBContext jaxbContext = null;
            try {
                jaxbContext = JAXBContext.newInstance(RestVariableCollection.class);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                RestVariableCollection restVariableCollection = (RestVariableCollection) jaxbUnmarshaller.unmarshal(getXMLReader(httpServletRequest.getInputStream()));
                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 e) {
                throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a " + "RestVariable instance.", e);
            }
        }
    } catch (Exception e) {
        throw new ActivitiIllegalArgumentException("Failed to serialize 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<>();
    RestResponseFactory restResponseFactory = new RestResponseFactory();
    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 (hasVariableOnScope(task, var.getName(), varScope)) {
            throw new BPMNConflictException("Variable '" + var.getName() + "' is already present on task '" + task.getId() + "'.");
        }
        Object actualVariableValue = restResponseFactory.getVariableValue(var);
        variablesToSet.put(var.getName(), actualVariableValue);
        resultVariables.add(restResponseFactory.createRestVariable(var.getName(), actualVariableValue, varScope, task.getId(), RestResponseFactory.VARIABLE_TASK, false, uriInfo.getBaseUri().toString()));
    }
    RuntimeService runtimeService = BPMNOSGIService.getRuntimeService();
    TaskService taskService = BPMNOSGIService.getTaskService();
    if (!variablesToSet.isEmpty()) {
        if (sharedScope == RestVariable.RestVariableScope.LOCAL) {
            taskService.setVariablesLocal(task.getId(), variablesToSet);
        } else {
            if (task.getExecutionId() != null) {
                // Explicitly set on execution, setting non-local variables on task will override local-variables if exists
                runtimeService.setVariables(task.getExecutionId(), variablesToSet);
            } else {
                // Standalone task, no global variables possible
                throw new ActivitiIllegalArgumentException("Cannot set global variables on task '" + task.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) JAXBContext(javax.xml.bind.JAXBContext) RestVariable(org.wso2.carbon.bpmn.rest.engine.variable.RestVariable) Unmarshaller(javax.xml.bind.Unmarshaller) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory) BaseTaskService(org.wso2.carbon.bpmn.rest.service.base.BaseTaskService) XMLStreamException(javax.xml.stream.XMLStreamException) BPMNForbiddenException(org.wso2.carbon.bpmn.rest.common.exception.BPMNForbiddenException) BPMNConflictException(org.wso2.carbon.bpmn.rest.common.exception.BPMNConflictException) JAXBException(javax.xml.bind.JAXBException) DataResponse(org.wso2.carbon.bpmn.rest.model.common.DataResponse) Response(javax.ws.rs.core.Response)

Example 58 with Scope

use of org.wso2.ballerinalang.compiler.semantics.model.Scope in project carbon-business-process by wso2.

the class WorkflowTaskService method getVariableData.

@GET
@Path("/{taskId}/variables/{variableName}/data")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response getVariableData(@PathParam("taskId") String taskId, @PathParam("variableName") String variableName) {
    String scope = uriInfo.getQueryParameters().getFirst("scope");
    Response.ResponseBuilder responseBuilder = Response.ok();
    try {
        byte[] result = null;
        RestVariable variable = getVariableFromRequest(taskId, variableName, scope, true, uriInfo.getBaseUri().toString());
        if (RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variable.getType())) {
            result = (byte[]) variable.getValue();
            responseBuilder.type(MediaType.APPLICATION_OCTET_STREAM);
        } else if (RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variable.getType())) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            ObjectOutputStream outputStream = new ObjectOutputStream(buffer);
            outputStream.writeObject(variable.getValue());
            outputStream.close();
            result = buffer.toByteArray();
            responseBuilder.type("application/x-java-serialized-object");
        } else {
            throw new ActivitiObjectNotFoundException("The variable does not have a binary data stream.", null);
        }
        return responseBuilder.entity(result).build();
    } catch (IOException ioe) {
        // Re-throw IOException
        throw new ActivitiException("Unexpected error getting variable data", ioe);
    }
}
Also used : DataResponse(org.wso2.carbon.bpmn.rest.model.common.DataResponse) Response(javax.ws.rs.core.Response) RestVariable(org.wso2.carbon.bpmn.rest.engine.variable.RestVariable)

Example 59 with Scope

use of org.wso2.ballerinalang.compiler.semantics.model.Scope in project carbon-business-process by wso2.

the class WorkflowTaskService method setSimpleVariable.

protected RestVariable setSimpleVariable(RestVariable restVariable, Task task, boolean isNew) {
    if (restVariable.getName() == null) {
        throw new ActivitiIllegalArgumentException("Variable name is required");
    }
    // Figure out scope, revert to local is omitted
    RestVariable.RestVariableScope scope = restVariable.getVariableScope();
    if (scope == null) {
        scope = RestVariable.RestVariableScope.LOCAL;
    }
    RestResponseFactory restResponseFactory = new RestResponseFactory();
    Object actualVariableValue = restResponseFactory.getVariableValue(restVariable);
    setVariable(task, restVariable.getName(), actualVariableValue, scope, isNew);
    return restResponseFactory.createRestVariable(restVariable.getName(), actualVariableValue, scope, task.getId(), RestResponseFactory.VARIABLE_TASK, false, uriInfo.getBaseUri().toString());
}
Also used : RestVariable(org.wso2.carbon.bpmn.rest.engine.variable.RestVariable) RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory)

Example 60 with Scope

use of org.wso2.ballerinalang.compiler.semantics.model.Scope in project carbon-business-process by wso2.

the class BaseExecutionService method createBinaryExecutionVariable.

protected RestVariable createBinaryExecutionVariable(Execution execution, int responseVariableType, UriInfo uriInfo, boolean isNew, MultipartBody multipartBody) {
    boolean debugEnabled = log.isDebugEnabled();
    Response.ResponseBuilder responseBuilder = Response.ok();
    List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments = multipartBody.getAllAttachments();
    int attachmentSize = attachments.size();
    if (attachmentSize <= 0) {
        throw new ActivitiIllegalArgumentException("No Attachments found with the request body");
    }
    AttachmentDataHolder attachmentDataHolder = new AttachmentDataHolder();
    for (int i = 0; i < attachmentSize; i++) {
        org.apache.cxf.jaxrs.ext.multipart.Attachment attachment = attachments.get(i);
        String contentDispositionHeaderValue = attachment.getHeader("Content-Disposition");
        String contentType = attachment.getHeader("Content-Type");
        if (debugEnabled) {
            log.debug("Going to iterate:" + i);
            log.debug("contentDisposition:" + contentDispositionHeaderValue);
        }
        if (contentDispositionHeaderValue != null) {
            contentDispositionHeaderValue = contentDispositionHeaderValue.trim();
            Map<String, String> contentDispositionHeaderValueMap = Utils.processContentDispositionHeader(contentDispositionHeaderValue);
            String dispositionName = contentDispositionHeaderValueMap.get("name");
            DataHandler dataHandler = attachment.getDataHandler();
            OutputStream outputStream = null;
            if ("name".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Name Reading error occured", e);
                }
                if (outputStream != null) {
                    String fileName = outputStream.toString();
                    attachmentDataHolder.setName(fileName);
                }
            } else if ("type".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Type Reading error occured", e);
                }
                if (outputStream != null) {
                    String typeName = outputStream.toString();
                    attachmentDataHolder.setType(typeName);
                }
            } else if ("scope".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Description Reading error occured", e);
                }
                if (outputStream != null) {
                    String description = outputStream.toString();
                    attachmentDataHolder.setScope(description);
                }
            }
            if (contentType != null) {
                if ("file".equals(dispositionName)) {
                    InputStream inputStream = null;
                    try {
                        inputStream = dataHandler.getInputStream();
                    } catch (IOException e) {
                        throw new ActivitiIllegalArgumentException("Error Occured During processing empty body.", e);
                    }
                    if (inputStream != null) {
                        attachmentDataHolder.setContentType(contentType);
                        byte[] attachmentArray = new byte[0];
                        try {
                            attachmentArray = IOUtils.toByteArray(inputStream);
                        } catch (IOException e) {
                            throw new ActivitiIllegalArgumentException("Processing Attachment Body Failed.", e);
                        }
                        attachmentDataHolder.setAttachmentArray(attachmentArray);
                    }
                }
            }
        }
    }
    attachmentDataHolder.printDebug();
    if (attachmentDataHolder.getName() == null) {
        throw new ActivitiIllegalArgumentException("Attachment name is required.");
    }
    if (attachmentDataHolder.getAttachmentArray() == null) {
        throw new ActivitiIllegalArgumentException("Empty attachment body was found in request body after " + "decoding the request" + ".");
    }
    String variableScope = attachmentDataHolder.getScope();
    String variableName = attachmentDataHolder.getName();
    String variableType = attachmentDataHolder.getType();
    if (log.isDebugEnabled()) {
        log.debug("variableScope:" + variableScope + " variableName:" + variableName + " variableType:" + variableType);
    }
    try {
        // Validate input and set defaults
        if (variableName == null) {
            throw new ActivitiIllegalArgumentException("No variable name was found in request body.");
        }
        if (variableType != null) {
            if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType) && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) {
                throw new ActivitiIllegalArgumentException("Only 'binary' and 'serializable' are supported as variable type.");
            }
        } else {
            variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE;
        }
        RestVariable.RestVariableScope scope = RestVariable.RestVariableScope.LOCAL;
        if (variableScope != null) {
            scope = RestVariable.getScopeFromString(variableScope);
        }
        if (RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType)) {
            // Use raw bytes as variable value
            setVariable(execution, variableName, attachmentDataHolder.getAttachmentArray(), scope, isNew);
        } else {
            // Try deserializing the object
            try (InputStream inputStream = new ByteArrayInputStream(attachmentDataHolder.getAttachmentArray());
                ObjectInputStream stream = new ObjectInputStream(inputStream)) {
                Object value = stream.readObject();
                setVariable(execution, variableName, value, scope, isNew);
            }
        }
        if (responseVariableType == RestResponseFactory.VARIABLE_PROCESS) {
            return new RestResponseFactory().createBinaryRestVariable(variableName, scope, variableType, null, null, execution.getId(), uriInfo.getBaseUri().toString());
        } else {
            return new RestResponseFactory().createBinaryRestVariable(variableName, scope, variableType, null, execution.getId(), null, uriInfo.getBaseUri().toString());
        }
    } catch (IOException ioe) {
        throw new ActivitiIllegalArgumentException("Could not process multipart content", ioe);
    } catch (ClassNotFoundException ioe) {
        throw new BPMNContentNotSupportedException("The provided body contains a serialized object for which the class is nog found: " + ioe.getMessage());
    }
}
Also used : DataHandler(javax.activation.DataHandler) BPMNContentNotSupportedException(org.wso2.carbon.bpmn.rest.common.exception.BPMNContentNotSupportedException) RestVariable(org.wso2.carbon.bpmn.rest.engine.variable.RestVariable) ActivitiIllegalArgumentException(org.activiti.engine.ActivitiIllegalArgumentException) JAXBContext(javax.xml.bind.JAXBContext) RestResponseFactory(org.wso2.carbon.bpmn.rest.common.RestResponseFactory) DataResponse(org.wso2.carbon.bpmn.rest.model.common.DataResponse) Response(javax.ws.rs.core.Response)

Aggregations

Scope (org.wso2.carbon.apimgt.core.models.Scope)41 HashMap (java.util.HashMap)25 RestVariable (org.wso2.carbon.bpmn.rest.engine.variable.RestVariable)25 Test (org.testng.annotations.Test)23 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)19 Response (javax.ws.rs.core.Response)16 ScopeInfo (org.wso2.carbon.apimgt.core.auth.dto.ScopeInfo)15 FileInputStream (java.io.FileInputStream)14 API (org.wso2.carbon.apimgt.core.models.API)14 ArrayList (java.util.ArrayList)13 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)13 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)13 Map (java.util.Map)12 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)12 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)12 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)12 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)11 RestResponseFactory (org.wso2.carbon.bpmn.rest.common.RestResponseFactory)11 ActivitiObjectNotFoundException (org.activiti.engine.ActivitiObjectNotFoundException)10 Scope (org.wso2.ballerinalang.compiler.semantics.model.Scope)10