org.activiti.engine.delegate.DelegateExecution Java Examples

The following examples show how to use org.activiti.engine.delegate.DelegateExecution. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TerminateEndEventActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected void dispatchExecutionCancelled(DelegateExecution execution, FlowElement terminateEndEvent) {

    ExecutionEntityManager executionEntityManager = Context.getCommandContext().getExecutionEntityManager();

    // subprocesses
    for (DelegateExecution subExecution : executionEntityManager.findChildExecutionsByParentExecutionId(execution.getId())) {
      dispatchExecutionCancelled(subExecution, terminateEndEvent);
    }

    // call activities
    ExecutionEntity subProcessInstance = Context.getCommandContext().getExecutionEntityManager().findSubProcessInstanceBySuperExecutionId(execution.getId());
    if (subProcessInstance != null) {
      dispatchExecutionCancelled(subProcessInstance, terminateEndEvent);
    }

    // activity with message/signal boundary events
    FlowElement currentFlowElement = execution.getCurrentFlowElement();
    if (currentFlowElement instanceof FlowNode) {
      dispatchActivityCancelled(execution, terminateEndEvent);
    }
  }
 
Example #2
Source File: IntermediateCatchEventActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected EventGateway getPrecedingEventBasedGateway(DelegateExecution execution) {
  FlowElement currentFlowElement = execution.getCurrentFlowElement();
  if (currentFlowElement instanceof IntermediateCatchEvent) {
    IntermediateCatchEvent intermediateCatchEvent = (IntermediateCatchEvent) currentFlowElement;
    List<SequenceFlow> incomingSequenceFlow = intermediateCatchEvent.getIncomingFlows();
    
    // If behind an event based gateway, there is only one incoming sequence flow that originates from said gateway
    if (incomingSequenceFlow != null && incomingSequenceFlow.size() == 1) {
      SequenceFlow sequenceFlow = incomingSequenceFlow.get(0);
      FlowElement sourceFlowElement = sequenceFlow.getSourceFlowElement();
      if (sourceFlowElement instanceof EventGateway) {
        return (EventGateway) sourceFlowElement;
      }
    }
    
  }
  return null;
}
 
Example #3
Source File: ExecuteJdbc.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
public void executeImpl(DelegateExecution execution) throws Exception
{
    // Construct request from parameters
    String contentTypeString = activitiHelper.getRequiredExpressionVariableAsString(contentType, execution, "ContentType");
    String requestString = activitiHelper.getRequiredExpressionVariableAsString(jdbcExecutionRequest, execution, "JdbcExecutionRequest").trim();
    String receiveTaskIdString = activitiHelper.getExpressionVariableAsString(receiveTaskId, execution);

    JdbcExecutionRequest jdbcExecutionRequestObject = getRequestObject(contentTypeString, requestString, JdbcExecutionRequest.class);

    if (receiveTaskIdString == null)
    {
        executeSync(execution, null, jdbcExecutionRequestObject);
    }
    else
    {
        executeAsync(execution, jdbcExecutionRequestObject, receiveTaskIdString);
    }
}
 
Example #4
Source File: CMSClientTest.java    From oneops with Apache License 2.0 6 votes vote down vote up
@Test(priority=10)
public void commitAndDeployTest() throws GeneralSecurityException{
	
	DelegateExecution delegateExecution = mock(DelegateExecution.class);
	CmsRelease cmsRelease = mock(CmsRelease.class);
	when(cmsRelease.getReleaseId()).thenReturn(TEST_CI_ID / 2);
	
	CmsCISimple cmsCISimpleEnv = mock(CmsCISimple.class);
	when(cmsCISimpleEnv.getCiId()).thenReturn(TEST_CI_ID);
	
	when(delegateExecution.getVariable("release")).thenReturn(cmsRelease);
	when(delegateExecution.getVariable("env")).thenReturn(cmsCISimpleEnv);
		
	cc.setRestTemplate(mockHttpClientPostCommitAndDeploy);
	try {
		cc.commitAndDeployRelease(delegateExecution);
	} catch (GeneralSecurityException e) {
		throw e;
	}
}
 
Example #5
Source File: CreateUserAndMembershipTestDelegate.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {

  IdentityService identityService = Context.getProcessEngineConfiguration().getIdentityService();
  
  String username = "Kermit";
  User user = identityService.newUser(username);
  user.setPassword("123");
  user.setFirstName("Manually");
  user.setLastName("created");
  identityService.saveUser(user);
  
  // Add admin group
  Group group = identityService.newGroup("admin");
  identityService.saveGroup(group);

  identityService.createMembership(username, "admin");
}
 
Example #6
Source File: ScriptExecutionListener.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected Map<String, Object> getInputMap(DelegateExecution execution,
            String runAsUser) 
{
    Map<String, Object> scriptModel =  super.getInputMap(execution, runAsUser);

    ExecutionListenerExecution listenerExecution = (ExecutionListenerExecution) execution;

    // Add deleted/cancelled flags
    boolean cancelled = false;
    boolean deleted = false;
    
    if (ActivitiConstants.DELETE_REASON_DELETED.equals(listenerExecution.getDeleteReason()))
    {
        deleted = true;
    } 
    else if (ActivitiConstants.DELETE_REASON_CANCELLED.equals(listenerExecution.getDeleteReason()))
    {
        cancelled = true;
    }
    scriptModel.put(DELETED_FLAG, deleted);
    scriptModel.put(CANCELLED_FLAG, cancelled);
    
    return scriptModel;
}
 
Example #7
Source File: ScriptExecutionListener.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Override
 public void notify(DelegateExecution execution) {
   
	if (script == null) {
		throw new IllegalArgumentException("The field 'script' should be set on the ExecutionListener");
	}

	if (language == null) {
		throw new IllegalArgumentException("The field 'language' should be set on the ExecutionListener");
	}

	ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();

	Object result = scriptingEngines.evaluate(script.getExpressionText(), language.getExpressionText(), execution);

	if (resultVariable != null) {
	  execution.setVariable(resultVariable.getExpressionText(), result);
	}
}
 
Example #8
Source File: VariableSetter.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
public void execute(DelegateExecution execution) {
  try {
    SimpleDateFormat sdf =  new SimpleDateFormat("dd/MM/yyyy hh:mm:ss SSS");
    // We set the time to check of the updated time is picked up in the history
    Date updatedDate = sdf.parse("01/01/2001 01:23:46 000");
    Context.getProcessEngineConfiguration().getClock().setCurrentTime(updatedDate);
    
    
    execution.setVariable("aVariable", "updated value");
    execution.setVariable("bVariable", 123);
    execution.setVariable("cVariable", 12345L);
    execution.setVariable("dVariable", 1234.567);
    execution.setVariable("eVariable", (short)12);
    
    Date theDate =sdf.parse("01/01/2001 01:23:45 678");
    execution.setVariable("fVariable", theDate);
    
    execution.setVariable("gVariable", new SerializableVariable("hello hello"));
    execution.setVariable("hVariable", ";-)".getBytes());
  } catch (Exception e) {
    throw new ActivitiException(e.getMessage(), e);
  }
}
 
Example #9
Source File: ExecutionTreeUtil.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
public static ExecutionTree buildExecutionTree(DelegateExecution executionEntity) {
  
  // Find highest parent
  ExecutionEntity parentExecution = (ExecutionEntity) executionEntity;
  while (parentExecution.getParentId() != null || parentExecution.getSuperExecutionId() != null) {
    if (parentExecution.getParentId() != null) {
      parentExecution = parentExecution.getParent();
    } else {
      parentExecution = parentExecution.getSuperExecution();
    }
  }
  
  // Collect all child executions now we have the parent
  List<ExecutionEntity> allExecutions = new ArrayList<ExecutionEntity>();
  allExecutions.add(parentExecution);
  collectChildExecutions(parentExecution, allExecutions);
  return buildExecutionTree(allExecutions);
}
 
Example #10
Source File: TerminateEndEventActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected void terminateMultiInstanceRoot(DelegateExecution execution, CommandContext commandContext,
    ExecutionEntityManager executionEntityManager) {

  // When terminateMultiInstance is 'true', we look for the multi instance root and delete it from there.
  ExecutionEntity miRootExecutionEntity = executionEntityManager.findFirstMultiInstanceRoot((ExecutionEntity) execution);
  if (miRootExecutionEntity != null) {

    // Create sibling execution to continue process instance execution before deletion
    ExecutionEntity siblingExecution = executionEntityManager.createChildExecution(miRootExecutionEntity.getParent());
    siblingExecution.setCurrentFlowElement(miRootExecutionEntity.getCurrentFlowElement());

    deleteExecutionEntities(executionEntityManager, miRootExecutionEntity, createDeleteReason(miRootExecutionEntity.getActivityId()));

    Context.getAgenda().planTakeOutgoingSequenceFlowsOperation(siblingExecution, true);
  } else {
    defaultTerminateEndEventBehaviour(execution, commandContext, executionEntityManager);
  }
}
 
Example #11
Source File: ActivitiHelperTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetExpressionVariableAsIntegerRequiredBlankValue()
{
    // Mock dependencies.
    Expression expression = mock(Expression.class);
    DelegateExecution execution = mock(DelegateExecution.class);
    when(expression.getValue(execution)).thenReturn(BLANK_TEXT);

    // Try to call the method under test.
    try
    {
        activitiHelper.getExpressionVariableAsInteger(expression, execution, VARIABLE_NAME, VARIABLE_REQUIRED);
        fail();
    }
    catch (IllegalArgumentException e)
    {
        assertEquals(String.format("\"%s\" must be specified.", VARIABLE_NAME), e.getMessage());
    }
}
 
Example #12
Source File: CMSClient.java    From oneops with Apache License 2.0 5 votes vote down vote up
/**
 * Update wo state.
 *
 * @param exec     the exec
 * @param wo       the wo
 * @param newState the new state
 */
public void updateWoState(DelegateExecution exec, CmsWorkOrderSimple wo, String newState) {
    CmsDeployment dpmt = (CmsDeployment) exec.getVariable(DPMT);
    updateWoState(wo, newState, dpmt, exec.getId(),
            (String)exec.getVariable("error-message"),
            d -> {
                exec.setVariable(DPMT, dpmt);
            });
}
 
Example #13
Source File: CandidateGroupGetter.java    From activiti-learn with Apache License 2.0 5 votes vote down vote up
/**
 * 动态设置 candidateGroups 只能返回 Collection<String>
 *
 * @param execution
 * @return
 */
public Collection<String> get(DelegateExecution execution) {
  System.out.println("========================================");
  System.out.println("CandidateGroupGetter: used in candidateGroups expression");
  System.out.println("parameter execution: " + execution);
  System.out.println("parameter execution.getCurrentActivityId: " + execution.getCurrentActivityId());
  System.out.println("parameter execution.getCurrentActivityName: " + execution.getCurrentActivityName());
  System.out.println();

  return Arrays.asList("groupId1", "groupId2");

}
 
Example #14
Source File: EventSubProcessMessageStartEventActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void execute(DelegateExecution execution) {
  StartEvent startEvent = (StartEvent) execution.getCurrentFlowElement();
  EventSubProcess eventSubProcess = (EventSubProcess) startEvent.getSubProcess();

  execution.setScope(true);

  // initialize the template-defined data objects as variables
  Map<String, Object> dataObjectVars = processDataObjects(eventSubProcess.getDataObjects());
  if (dataObjectVars != null) {
    execution.setVariablesLocal(dataObjectVars);
  }
}
 
Example #15
Source File: SequentialMultiInstanceBehavior.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
/**
 * Handles the sequential case of spawning the instances. Will only create one instance, since at most one instance can be active.
 */
protected int createInstances(DelegateExecution multiInstanceExecution) {
  
  int nrOfInstances = resolveNrOfInstances(multiInstanceExecution);
  if (nrOfInstances == 0) {
    return nrOfInstances;
  } else if (nrOfInstances < 0) {
    throw new ActivitiIllegalArgumentException("Invalid number of instances: must be a non-negative integer value" + ", but was " + nrOfInstances);
  }
  
  // Create child execution that will execute the inner behavior
  ExecutionEntity childExecution = Context.getCommandContext().getExecutionEntityManager()
      .createChildExecution((ExecutionEntity) multiInstanceExecution);
  childExecution.setCurrentFlowElement(multiInstanceExecution.getCurrentFlowElement());
  multiInstanceExecution.setMultiInstanceRoot(true);
  multiInstanceExecution.setActive(false);
  
  // Set Multi-instance variables
  setLoopVariable(multiInstanceExecution, NUMBER_OF_INSTANCES, nrOfInstances);
  setLoopVariable(multiInstanceExecution, NUMBER_OF_COMPLETED_INSTANCES, 0);
  setLoopVariable(multiInstanceExecution, NUMBER_OF_ACTIVE_INSTANCES, 1);
  setLoopVariable(childExecution, getCollectionElementIndexVariable(), 0);
  logLoopDetails(multiInstanceExecution, "initialized", 0, 0, 1, nrOfInstances);

  if (nrOfInstances > 0) {
    executeOriginalBehavior(childExecution, 0);
  }
  return nrOfInstances;
}
 
Example #16
Source File: CountingServiceTaskTestDelegate.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {
  Integer counter = (Integer) execution.getVariable("counter");
  counter = counter + 1;
  execution.setVariable("counter", counter);

  if (CALL_COUNT.get() % 1000 == 0) {
    System.out.println("Call count: " + CALL_COUNT);
  }

  CALL_COUNT.incrementAndGet();
}
 
Example #17
Source File: TerminateEndEventActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void execute(DelegateExecution delegateExecution) {
  ActivityExecution execution = (ActivityExecution) delegateExecution;
  ActivityImpl terminateEndEventActivity = (ActivityImpl) execution.getActivity();
  
  if (terminateAll) {
    ActivityExecution processInstanceExecution = findRootProcessInstanceExecution((ExecutionEntity) execution);
    terminateProcessInstanceExecution(execution, terminateEndEventActivity, processInstanceExecution);
  } else {
    ActivityExecution scopeExecution = ScopeUtil.findScopeExecution(execution);
    if (scopeExecution != null) {
      terminateExecution(execution, terminateEndEventActivity, scopeExecution);
    } 
  }
  
}
 
Example #18
Source File: MultiInstanceDelegate.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void execute(DelegateExecution execution) {
  Integer result = (Integer) execution.getVariable("result");
  
  Integer item = (Integer) execution.getVariable("item");
  if (item != null) {
    result = result * item;
  } else {
    result = result * 2;
  }
  execution.setVariable("result", result);
}
 
Example #19
Source File: GetVariablesDelegate.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void execute(DelegateExecution execution) {
  Object nrOfCompletedInstances = execution.getVariable("nrOfCompletedInstances");    
  Integer variable = SetVariablesDelegate.variablesMap.get(nrOfCompletedInstances);
  Object variableLocal = execution.getVariable("variable");
  if(!variableLocal.equals(variable)) {
    throw new ActivitiIllegalArgumentException("wrong variable passed in to compensation handler");
  }
}
 
Example #20
Source File: CancelNominatedInviteDelegate.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void execute(DelegateExecution execution) throws Exception
{
    Map<String, Object> executionVariables = execution.getVariables();
    String currentInviteId = ActivitiConstants.ENGINE_ID + "$" + execution.getProcessInstanceId();

    // Get the invitee user name and site short name variables off the execution context
    String invitee = (String) executionVariables.get(wfVarInviteeUserName);
    String siteName = (String) executionVariables.get(wfVarResourceName);
    String inviteId = (String) executionVariables.get(wfVarWorkflowInstanceId);

    invitationService.cancelInvitation(siteName, invitee, inviteId, currentInviteId);
}
 
Example #21
Source File: TerminateEndEventActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(DelegateExecution execution) {

  CommandContext commandContext = Context.getCommandContext();
  ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();

  if (terminateAll) {
    terminateAllBehaviour(execution, commandContext, executionEntityManager);
  } else if (terminateMultiInstance) {
    terminateMultiInstanceRoot(execution, commandContext, executionEntityManager);
  } else {
    defaultTerminateEndEventBehaviour(execution, commandContext, executionEntityManager);
  }
}
 
Example #22
Source File: MailActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected void handleException(DelegateExecution execution, String msg, Exception e, boolean doIgnoreException, String exceptionVariable) {
  if (doIgnoreException) {
    LOG.info("Ignoring email send error: " + msg, e);
    if (exceptionVariable != null && exceptionVariable.length() > 0) {
      execution.setVariable(exceptionVariable, msg);
    }
  } else {
    if (e instanceof ActivitiException) {
      throw (ActivitiException) e;
    } else {
      throw new ActivitiException(msg, e);
    }
  }
}
 
Example #23
Source File: ActivityStartListener.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void notify(DelegateExecution execution) {
	
	Integer loopCounter = (Integer) execution.getVariable("loopCounter");
	if (loopCounter != null) {
	
   Integer counter = (Integer) execution.getVariable("executionListenerCounter");
   if (counter == null) {
     counter = 0;
   }
   execution.setVariable("executionListenerCounter", ++counter);
   
	}
}
 
Example #24
Source File: ExecuteJdbc.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the task synchronously. overrideActivitiId is provided to customize the name of the variable to set during the execution of the task. This is
 * important when the task is running asynchronously because execution.getCurrentActivitiId() will report the ID the task that the workflow is currently in,
 * and not the ID of the task that was originally executed.
 *
 * @param execution The execution.
 * @param overrideActivitiId Optionally overrides the task id which to use to generate variable names.
 * @param jdbcExecutionRequest The request.
 *
 * @throws Exception When any exception occurs during the execution of the task.
 */
private void executeSync(DelegateExecution execution, String overrideActivitiId, JdbcExecutionRequest jdbcExecutionRequest) throws Exception
{
    String executionId = execution.getId();
    String activitiId = execution.getCurrentActivityId();
    if (overrideActivitiId != null)
    {
        activitiId = overrideActivitiId;
    }

    // Execute the request. May throw exception here in case of validation or system errors.
    // Thrown exceptions should be caught by parent implementation.
    JdbcExecutionResponse jdbcExecutionResponse = jdbcService.executeJdbc(jdbcExecutionRequest);

    // Set the response
    setJsonResponseAsWorkflowVariable(jdbcExecutionResponse, executionId, activitiId);

    /*
     * Special handling of error condition.
     * Any one of the requested SQL statements could've failed without throwing an exception.
     * If any of the statements are in ERROR, throw an exception.
     * This ensures that the workflow response variable is still available to the users.
     */
    for (JdbcStatement jdbcStatement : jdbcExecutionResponse.getStatements())
    {
        if (JdbcStatementStatus.ERROR.equals(jdbcStatement.getStatus()))
        {
            throw new IllegalArgumentException("There are failed executions. See JSON response for details.");
        }
    }
}
 
Example #25
Source File: ClassDelegate.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
public void completing(DelegateExecution execution, DelegateExecution subProcessInstance) throws Exception {
	if (activityBehaviorInstance == null) {
    activityBehaviorInstance = getActivityBehaviorInstance((ActivityExecution) execution);
  }
  
  if (activityBehaviorInstance instanceof SubProcessActivityBehavior) {
    ((SubProcessActivityBehavior) activityBehaviorInstance).completing(execution, subProcessInstance);
  } else {
    throw new ActivitiException("completing() can only be called on a " + SubProcessActivityBehavior.class.getName() + " instance");
  }
}
 
Example #26
Source File: ListenerNotificationHelper.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected void planTransactionDependentTaskListener(DelegateExecution execution, TransactionDependentTaskListener taskListener, ActivitiListener activitiListener) {
  Map<String, Object> executionVariablesToUse = execution.getVariables();
  CustomPropertiesResolver customPropertiesResolver = createCustomPropertiesResolver(activitiListener);
  Map<String, Object> customPropertiesMapToUse = invokeCustomPropertiesResolver(execution, customPropertiesResolver);
  
  TransactionDependentTaskListenerExecutionScope scope = new TransactionDependentTaskListenerExecutionScope(
      execution.getProcessInstanceId(), execution.getId(), (Task) execution.getCurrentFlowElement(), executionVariablesToUse, customPropertiesMapToUse);
  addTransactionListener(activitiListener, new ExecuteTaskListenerTransactionListener(taskListener, scope));
}
 
Example #27
Source File: ActivitiHelperTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetRequiredExpressionVariableAsString()
{
    // Mock dependencies.
    Expression expression = mock(Expression.class);
    DelegateExecution execution = mock(DelegateExecution.class);
    when(expression.getValue(execution)).thenReturn(STRING_VALUE);

    // Call the method under test.
    String result = activitiHelper.getRequiredExpressionVariableAsString(expression, execution, VARIABLE_NAME);

    // Validate the result.
    assertEquals(STRING_VALUE, result);
}
 
Example #28
Source File: AddEmrShellStep.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public void executeImpl(DelegateExecution execution) throws Exception
{
    // Create the request.
    EmrShellStepAddRequest request = new EmrShellStepAddRequest();
    
    populateCommonParams(request, execution);
    
    request.setScriptLocation(getScriptLocation(execution));
    request.setScriptArguments(getScriptArguments(execution));
    
    addEmrStepAndSetWorkflowVariables(request, execution);
}
 
Example #29
Source File: SendModeratedInviteDelegate.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void execute(DelegateExecution execution) throws Exception
{
    String invitationId = ActivitiConstants.ENGINE_ID + "$" + execution.getProcessInstanceId();
    Map<String, Object> variables = execution.getVariables();
    invitationService.sendModeratedInvitation(invitationId, emailTemplatePath, EMAIL_SUBJECT_KEY, variables);
}
 
Example #30
Source File: ScriptCondition.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public boolean evaluate(String sequenceFlowId, DelegateExecution execution) {
  ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();

  Object result = scriptingEngines.evaluate(expression, language, execution);
  if (result == null) {
    throw new ActivitiException("condition script returns null: " + expression);
  }
  if (!(result instanceof Boolean)) {
    throw new ActivitiException("condition script returns non-Boolean: " + result + " (" + result.getClass().getName() + ")");
  }
  return (Boolean) result;
}