use of org.activiti.engine.history.HistoricVariableInstance in project alfresco-remote-api by Alfresco.
the class WorkflowRestImpl method validateIfUserAllowedToWorkWithProcess.
/**
* Validates if the logged in user is allowed to get information about a specific process instance.
* If the user is not allowed an exception is thrown.
*
* @param processId identifier of the process instance
*/
protected List<HistoricVariableInstance> validateIfUserAllowedToWorkWithProcess(String processId) {
List<HistoricVariableInstance> variableInstances = activitiProcessEngine.getHistoryService().createHistoricVariableInstanceQuery().processInstanceId(processId).list();
Map<String, Object> variableMap = new HashMap<String, Object>();
if (variableInstances != null && variableInstances.size() > 0) {
for (HistoricVariableInstance variableInstance : variableInstances) {
variableMap.put(variableInstance.getVariableName(), variableInstance.getValue());
}
} else {
throw new EntityNotFoundException(processId);
}
if (tenantService.isEnabled()) {
String tenantDomain = (String) variableMap.get(ActivitiConstants.VAR_TENANT_DOMAIN);
if (TenantUtil.getCurrentDomain().equals(tenantDomain) == false) {
throw new PermissionDeniedException("Process is running in another tenant");
}
}
// MNT-17918 - required for initiator variable already updated as NodeRef type
Object initiator = variableMap.get(WorkflowConstants.PROP_INITIATOR);
String nodeId = ((initiator instanceof ActivitiScriptNode) ? ((ActivitiScriptNode) initiator).getNodeRef().getId() : ((NodeRef) initiator).getId());
if (initiator != null && AuthenticationUtil.getRunAsUser().equals(nodeId)) {
// user is allowed
return variableInstances;
}
String username = AuthenticationUtil.getRunAsUser();
if (authorityService.isAdminAuthority(username)) {
// Admin is allowed to read all processes in the current tenant
return variableInstances;
} else {
// MNT-12382 check for membership in the assigned group
ActivitiScriptNode group = (ActivitiScriptNode) variableMap.get("bpm_groupAssignee");
if (group != null) {
// check that the process is unclaimed
Task task = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(processId).singleResult();
if ((task != null) && (task.getAssignee() == null) && isUserInGroup(username, group.getNodeRef())) {
return variableInstances;
}
}
// If non-admin user, involvement in the task is required (either owner, assignee or externally involved).
HistoricTaskInstanceQuery query = activitiProcessEngine.getHistoryService().createHistoricTaskInstanceQuery().processInstanceId(processId).taskInvolvedUser(AuthenticationUtil.getRunAsUser());
List<HistoricTaskInstance> taskList = query.list();
if (org.apache.commons.collections.CollectionUtils.isEmpty(taskList)) {
throw new PermissionDeniedException("user is not allowed to access information about process " + processId);
}
}
return variableInstances;
}
use of org.activiti.engine.history.HistoricVariableInstance in project alfresco-remote-api by Alfresco.
the class WorkflowRestImpl method getItemFromProcess.
/**
* Get an item from the process package variable
*/
public Item getItemFromProcess(String itemId, String processId) {
NodeRef nodeRef = getNodeRef(itemId);
ActivitiScriptNode packageScriptNode = null;
try {
HistoricVariableInstance variableInstance = activitiProcessEngine.getHistoryService().createHistoricVariableInstanceQuery().processInstanceId(processId).variableName(BPM_PACKAGE).singleResult();
if (variableInstance != null) {
packageScriptNode = (ActivitiScriptNode) variableInstance.getValue();
} else {
throw new EntityNotFoundException(processId);
}
} catch (ActivitiObjectNotFoundException e) {
throw new EntityNotFoundException(processId);
}
Item item = null;
if (packageScriptNode != null) {
List<ChildAssociationRef> documentList = nodeService.getChildAssocs(packageScriptNode.getNodeRef());
for (ChildAssociationRef childAssociationRef : documentList) {
if (childAssociationRef.getChildRef().equals(nodeRef)) {
item = createItemForNodeRef(childAssociationRef.getChildRef());
break;
}
}
}
if (item == null) {
throw new EntityNotFoundException(itemId);
}
return item;
}
use of org.activiti.engine.history.HistoricVariableInstance in project Activiti by Activiti.
the class EmptyProcessTest method testObjectAsStringVariable.
@Deployment(resources = { "process/empty.bpmn20.xml" })
public void testObjectAsStringVariable() throws Exception {
CamelContext ctx = applicationContext.getBean(CamelContext.class);
ProducerTemplate tpl = ctx.createProducerTemplate();
Object expectedObj = new Long(99);
Exchange exchange = ctx.getEndpoint("direct:startEmptyBodyAsString").createExchange();
exchange.getIn().setBody(expectedObj);
tpl.send("direct:startEmptyBodyAsString", exchange);
String instanceId = (String) exchange.getProperty("PROCESS_ID_PROPERTY");
assertProcessEnded(instanceId);
HistoricVariableInstance var = processEngine.getHistoryService().createHistoricVariableInstanceQuery().variableName("camelBody").singleResult();
assertNotNull(var);
assertEquals(expectedObj.toString(), var.getValue().toString());
}
use of org.activiti.engine.history.HistoricVariableInstance in project herd by FINRAOS.
the class HerdCommandInvokerTest method testAssertAsynchronousTaskErrorWrittenToJobEntity.
/**
* Tests the error handling behavior for asynchronous tasks. This test proves 2 behaviors: when a asynchronous task is executed, and an error occurs, any
* variables written by the tasks are persisted, and the error message and stack trace is recorded in the JobEntity which belongs to the execution. Writing
* the exception in JobEntity ensures that we are able to retrieve the exception message in our GetJob API.
* <p/>
* This test must run outside of a transaction since the workflow will be executing asynchronously.
*
* @throws Exception
*/
@Test
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void testAssertAsynchronousTaskErrorWrittenToJobEntity() throws Exception {
// Create a workflow
BpmnModel bpmnModel = new BpmnModel();
Process process = new Process();
process.setId("test");
{
StartEvent element = new StartEvent();
element.setId("start");
process.addFlowElement(element);
}
{
ScriptTask element = new ScriptTask();
element.setId("script1");
element.setScriptFormat("js");
element.setAsynchronous(true);
element.setScript("execution.setVariable('foo', 'bar');");
process.addFlowElement(element);
}
{
ScriptTask element = new ScriptTask();
element.setId("script2");
element.setScriptFormat("js");
element.setScript("throw new Error()");
process.addFlowElement(element);
}
{
EndEvent element = new EndEvent();
element.setId("end");
process.addFlowElement(element);
}
process.addFlowElement(new SequenceFlow("start", "script1"));
process.addFlowElement(new SequenceFlow("script1", "script2"));
process.addFlowElement(new SequenceFlow("script2", "end"));
bpmnModel.addProcess(process);
// Deploy the workflow
activitiRepositoryService.createDeployment().addBpmnModel("bpmn20.xml", bpmnModel).deploy();
// Start the process instance
ProcessInstance processInstance = activitiRuntimeService.startProcessInstanceByKey("test");
try {
/*
* Wait for process instance to run.
* Note that we cannot use the convenience method waitUntilAllProcessCompleted() since the workflow will be in an error state and therefore stay
* active.
*/
long startTime = System.currentTimeMillis();
HistoricVariableInstance persistedVariable = null;
while (persistedVariable == null) {
persistedVariable = activitiHistoryService.createHistoricVariableInstanceQuery().variableName("foo").singleResult();
Thread.sleep(10);
if (System.currentTimeMillis() - startTime > 10000) {
fail("workflow did not reach the desired state within a reasonable time");
}
}
// Make assertions
// Assert variable is persisted
assertEquals("bar", persistedVariable.getValue());
// Assert exception message is logged
assertEquals("ActivitiException: problem evaluating script: Error in <eval> at line number 1 at column number 0", activitiManagementService.createJobQuery().executionId(processInstance.getProcessInstanceId()).singleResult().getExceptionMessage());
} finally {
deleteActivitiDeployments();
}
}
use of org.activiti.engine.history.HistoricVariableInstance in project carbon-business-process by wso2.
the class ProcessInstanceService method startInstance.
@POST
@Path("/")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response startInstance(ProcessInstanceCreateRequest processInstanceCreateRequest) {
if (log.isDebugEnabled()) {
log.debug("ProcessInstanceCreateRequest:" + processInstanceCreateRequest.getProcessDefinitionId());
log.debug(" processInstanceCreateRequest.getVariables().size():" + processInstanceCreateRequest.getVariables().size());
}
if (processInstanceCreateRequest.getProcessDefinitionId() == null && processInstanceCreateRequest.getProcessDefinitionKey() == null && processInstanceCreateRequest.getMessage() == null) {
throw new ActivitiIllegalArgumentException("Either processDefinitionId, processDefinitionKey or message is required.");
}
int paramsSet = ((processInstanceCreateRequest.getProcessDefinitionId() != null) ? 1 : 0) + ((processInstanceCreateRequest.getProcessDefinitionKey() != null) ? 1 : 0) + ((processInstanceCreateRequest.getMessage() != null) ? 1 : 0);
if (paramsSet > 1) {
throw new ActivitiIllegalArgumentException("Only one of processDefinitionId, processDefinitionKey or message should be set.");
}
if (processInstanceCreateRequest.isCustomTenantSet()) {
// Tenant-id can only be used with either key or message
if (processInstanceCreateRequest.getProcessDefinitionId() != null) {
throw new ActivitiIllegalArgumentException("TenantId can only be used with either processDefinitionKey or message.");
}
} else {
// if no tenantId, it must be from definitionId
if (processInstanceCreateRequest.getProcessDefinitionId() == null) {
throw new ActivitiIllegalArgumentException("TenantId should be specified to be used with either " + "processDefinitionKey or message.");
}
}
// Have to add the validation part here
if (!isValidUserToStartProcess(processInstanceCreateRequest)) {
throw new RestApiBasicAuthenticationException("User doesn't have the necessary permission to start the process");
}
if (processInstanceCreateRequest.getSkipInstanceCreation() || processInstanceCreateRequest.getSkipInstanceCreationIfExist()) {
ProcessInstanceQueryRequest processInstanceQueryRequest = processInstanceCreateRequest.cloneInstanceCreationRequest();
Map<String, String> allRequestParams = allRequestParams(uriInfo);
DataResponse dataResponse = getQueryResponse(processInstanceQueryRequest, allRequestParams, uriInfo);
if (log.isDebugEnabled()) {
log.debug("ProcessInstanceCreation check:" + dataResponse.getSize());
}
int dataResponseSize = dataResponse.getSize();
if (dataResponseSize > 0) {
if (processInstanceCreateRequest.getCorrelate()) {
if (dataResponseSize != 1) {
String responseMessage = "Correlation matching failed as there are more than one matching instance with " + "given variables state";
throw new NotFoundException(Response.ok().entity(responseMessage).status(Response.Status.NOT_FOUND).build());
}
if (processInstanceCreateRequest.getMessageName() == null) {
String responseMessage = "Correlation matching failed as messageName property is not specified";
throw new ActivitiIllegalArgumentException(responseMessage);
}
return performCorrelation(processInstanceCreateRequest);
} else {
dataResponse.setMessage("Instance information corresponding to the request");
return Response.ok().entity(dataResponse).build();
}
}
}
RestResponseFactory restResponseFactory = new RestResponseFactory();
Map<String, Object> startVariables = null;
if (processInstanceCreateRequest.getVariables() != null) {
startVariables = new HashMap<>();
for (RestVariable variable : processInstanceCreateRequest.getVariables()) {
if (variable.getName() == null) {
throw new ActivitiIllegalArgumentException("Variable name is required.");
}
startVariables.put(variable.getName(), restResponseFactory.getVariableValue(variable));
}
}
// updated the additional variables
if (processInstanceCreateRequest.getAdditionalVariables() != null) {
if (startVariables == null) {
startVariables = new HashMap<>();
}
for (RestVariable variable : processInstanceCreateRequest.getAdditionalVariables()) {
if (variable.getName() == null) {
throw new ActivitiIllegalArgumentException("Additional Variable name is required.");
}
startVariables.put(variable.getName(), restResponseFactory.getVariableValue(variable));
}
}
RuntimeService runtimeService = BPMNOSGIService.getRuntimeService();
IdentityService identityService = BPMNOSGIService.getIdentityService();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String userName = carbonContext.getUsername();
ProcessInstanceResponse processInstanceResponse;
// Actually start the instance based on key or id
try {
ProcessInstance instance;
identityService.setAuthenticatedUserId(userName);
if (processInstanceCreateRequest.getProcessDefinitionId() != null) {
instance = runtimeService.startProcessInstanceById(processInstanceCreateRequest.getProcessDefinitionId(), processInstanceCreateRequest.getBusinessKey(), startVariables);
} else if (processInstanceCreateRequest.getProcessDefinitionKey() != null) {
if (processInstanceCreateRequest.isCustomTenantSet()) {
instance = runtimeService.startProcessInstanceByKeyAndTenantId(processInstanceCreateRequest.getProcessDefinitionKey(), processInstanceCreateRequest.getBusinessKey(), startVariables, processInstanceCreateRequest.getTenantId());
} else {
instance = runtimeService.startProcessInstanceByKey(processInstanceCreateRequest.getProcessDefinitionKey(), processInstanceCreateRequest.getBusinessKey(), startVariables);
}
} else {
if (processInstanceCreateRequest.isCustomTenantSet()) {
instance = runtimeService.startProcessInstanceByMessageAndTenantId(processInstanceCreateRequest.getMessage(), processInstanceCreateRequest.getBusinessKey(), startVariables, processInstanceCreateRequest.getTenantId());
} else {
instance = runtimeService.startProcessInstanceByMessage(processInstanceCreateRequest.getMessage(), processInstanceCreateRequest.getBusinessKey(), startVariables);
}
}
HistoryService historyService = BPMNOSGIService.getHistoryService();
if (processInstanceCreateRequest.getReturnVariables()) {
Map<String, Object> runtimeVariableMap = null;
List<HistoricVariableInstance> historicVariableList = null;
if (instance.isEnded()) {
historicVariableList = historyService.createHistoricVariableInstanceQuery().processInstanceId(instance.getId()).list();
} else {
runtimeVariableMap = runtimeService.getVariables(instance.getId());
}
processInstanceResponse = restResponseFactory.createProcessInstanceResponse(instance, true, runtimeVariableMap, historicVariableList, uriInfo.getBaseUri().toString());
} else {
processInstanceResponse = restResponseFactory.createProcessInstanceResponse(instance, uriInfo.getBaseUri().toString());
}
} catch (ActivitiObjectNotFoundException aonfe) {
throw new ActivitiIllegalArgumentException(aonfe.getMessage(), aonfe);
} finally {
identityService.setAuthenticatedUserId(null);
}
return Response.ok().status(Response.Status.CREATED).entity(processInstanceResponse).build();
}
Aggregations