org.camunda.bpm.engine.delegate.DelegateExecution Java Examples

The following examples show how to use org.camunda.bpm.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: ChargeCreditCardAdapter.java    From flowing-retail with Apache License 2.0 6 votes vote down vote up
public void execute(DelegateExecution ctx) throws Exception {
  CreateChargeRequest request = new CreateChargeRequest();
  request.amount = (int) ctx.getVariable("remainingAmount");

  CreateChargeResponse response = rest.postForObject( //
      stripeChargeUrl, //
      request, //
      CreateChargeResponse.class);
  
  if (response.errorCode != null && response.errorCode.length() > 0) {
    // raise error to be handled in BPMN model in case there was an error in credit card handling
    ctx.setVariable("creditCardErrorCode", response.errorCode);
    throw new BpmnError("Error_CreditCardError");
  }

  ctx.setVariable("paymentTransactionId", response.transactionId);
}
 
Example #2
Source File: AbstractServiceNodeStartListener.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
protected void logServiceNodeStart(DelegateExecution execution) {
    String nodeId = execution.getCurrentActivityId();
    String procInstanceBizKey = execution.getProcessBusinessKey();

    ServiceNodeStatusRepository serviceNodeStatusRepository = SpringApplicationContextUtil
            .getBean(ServiceNodeStatusRepository.class);

    ServiceNodeStatusEntity entity = serviceNodeStatusRepository
            .findOneByProcInstanceBizKeyAndNodeId(procInstanceBizKey, nodeId);

    if (entity == null) {
        getLogger().warn("{} is null for procInstanceBizKey={},nodeId={}", ServiceNodeStatusEntity.class.getSimpleName(),
                procInstanceBizKey, nodeId);
        throw new IllegalStateException("service node status entity doesnt exist");
    }
    
    Date currTime = new Date();
    entity.setUpdatedBy(WorkflowConstants.DEFAULT_USER);
    entity.setUpdatedTime(currTime);
    entity.setStatus(TraceStatus.InProgress);
    entity.setStartTime(currTime);
    
    serviceNodeStatusRepository.saveAndFlush(entity);
    
}
 
Example #3
Source File: EndEventListener.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void notify(DelegateExecution execution) throws Exception {

    log.info("EndEvent ending, instance {} businessKey {} execution {} activityId {}",
            execution.getProcessInstanceId(), execution.getBusinessKey(), execution.getId(),
            execution.getCurrentActivityId());

    if (execution instanceof ExecutionEntity) {
        ExecutionEntity entity = (ExecutionEntity) execution;
        Object typeProperty = entity.getActivity().getProperty("type");
        if (typeProperty != null && (typeProperty instanceof String)) {
            if ("errorEndEvent".equalsIgnoreCase((String) typeProperty)) {
                log.warn("process {} ,businessKey {} going with error", execution.getProcessInstanceId(),
                        execution.getBusinessKey());

                execution.setVariable(WorkflowConstants.VAR_KEY_PROCESS_WITH_ERROR, true);

            }
        }
    }

}
 
Example #4
Source File: ThrowBpmnErrorDelegate.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public void execute(DelegateExecution execution) throws Exception {
  Integer executionsBeforeError = (Integer) execution.getVariable("executionsBeforeError");
  Integer executions = (Integer) execution.getVariable("executions");
  Boolean exceptionType = (Boolean) execution.getVariable("exceptionType");
  if (executions == null) {
    executions = 0;
  }
  executions++;
  if (executionsBeforeError == null || executionsBeforeError < executions) {
    if (exceptionType != null && exceptionType) {
      throw new MyBusinessException("This is a business exception, which can be caught by a BPMN Error Event.");  
    } else {
      throw new BpmnError("23", "This is a business fault, which can be caught by a BPMN Error Event.");
    }
  } else {
    execution.setVariable("executions", executions);
  }
}
 
Example #5
Source File: ShipGoodsAdapter.java    From flowing-retail with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(DelegateExecution context) throws Exception {
  Order order = orderRepository.findById( //
      (String)context.getVariable("orderId")).get(); 
  String pickId = (String)context.getVariable("pickId"); // TODO read from step before!
  String traceId = context.getProcessBusinessKey();

  messageSender.send(new Message<ShipGoodsCommandPayload>( //
          "ShipGoodsCommand", //
          traceId, //
          new ShipGoodsCommandPayload() //
            .setRefId(order.getId())
            .setPickId(pickId) //
            .setRecipientName(order.getCustomer().getName()) //
            .setRecipientAddress(order.getCustomer().getAddress()))); 
}
 
Example #6
Source File: CancelOrderActivity.java    From Hands-On-RESTful-API-Design-Patterns-and-Best-Practices with MIT License 5 votes vote down vote up
@Override
public void execute(DelegateExecution execution) throws Exception {
	LOG.info("execute {} - {}", ProcessConstants.SERVICE_NAME_ORDER, SERVICE_ACTION);
	BusinessEntity sc = (BusinessEntity) execution.getVariable(ProcessConstants.VAR_SC);
	ServiceResponse response = rpcClient.invokeService(
			ProcessUtil.buildServiceRequest(sc, ProcessConstants.SERVICE_NAME_ORDER, SERVICE_ACTION));
	ProcessUtil.processResponse(execution, response);
}
 
Example #7
Source File: KpiService.java    From camunda-bpm-reactor with Apache License 2.0 5 votes vote down vote up
public void increment(String name, DelegateExecution execution) {
  if (kpis.containsKey(name)) {
    Long value = kpis.get(name);
    kpis.put(name, value + 1);

  } else {
    kpis.put(name, 1L);
  }
}
 
Example #8
Source File: SendShipGoodsAmqpAdapter.java    From camunda-spring-boot-amqp-microservice-cloud-example with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(DelegateExecution ctx) throws Exception {
  String orderId = (String) ctx.getVariable(ProcessConstants.VAR_NAME_orderId);    
  
  String exchange = "shipping";
  String routingKey = "createShipment";
  
  rabbitTemplate.convertAndSend(exchange, routingKey, orderId);
}
 
Example #9
Source File: DelegateExecutionContextTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testDelegateExecutionContextWithExecutionListener() {
  //given
  ProcessDefinition definition = testHelper.deployAndGetDefinition(EXEUCTION_LISTENER_PROCESS);
  // a process instance with a service task and an execution listener
  engineRule.getRuntimeService().startProcessInstanceById(definition.getId());

  //then delegation execution context is no more available
  DelegateExecution execution = DelegateExecutionContext.getCurrentDelegationExecution();
  assertNull(execution);
}
 
Example #10
Source File: DeleteAndInsertVariableDelegate.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void execute(DelegateExecution execution) throws Exception {
  if (execution.getVariable("listVar") != null) {
    execution.removeVariable("listVar");
    execution.setVariable("listVar", "stringValue");
  } else if (execution.getVariable("foo") != null) {
    execution.removeVariable("foo");
    execution.setVariable("foo", "secondValue");
  }
}
 
Example #11
Source File: FluentJavaDelegateMock.java    From camunda-bpm-mockito with Apache License 2.0 5 votes vote down vote up
@Override
public void onExecutionThrowBpmnError(final BpmnError bpmnError) {
  doAnswer(new JavaDelegate() {

    @Override
    public void execute(final DelegateExecution execution) throws Exception {
      throw bpmnError;
    }
  });
}
 
Example #12
Source File: FluentJavaDelegateMock.java    From camunda-bpm-mockito with Apache License 2.0 5 votes vote down vote up
@Override
public void onExecutionThrowException(final Exception exception) {
  doAnswer(new JavaDelegate() {
    @Override
    public void execute(DelegateExecution execution) throws Exception {
      throw exception;
    }
  });
}
 
Example #13
Source File: CloseShoppingCartActivity.java    From Hands-On-RESTful-API-Design-Patterns-and-Best-Practices with MIT License 5 votes vote down vote up
@Override
public void execute(DelegateExecution ctx) throws Exception {
	LOG.info("execute {} - {}", ProcessConstants.SERVICE_NAME_SHOPPINGCART, SERVICE_ACTION);
	BusinessEntity sc = (BusinessEntity) ctx.getVariable(ProcessConstants.VAR_SC);
	ServiceResponse response = shoppingCartManager.closeShoppingCart(sc);
	ProcessUtil.processResponse(ctx, response);
}
 
Example #14
Source File: ReverseStringsFieldInjected.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void execute(DelegateExecution execution) {
  String value1 = (String) text1.getValue(execution);
  execution.setVariable("var1", new StringBuffer(value1).reverse().toString());

  String value2 = (String) text2.getValue(execution);
  execution.setVariable("var2", new StringBuffer(value2).reverse().toString());
}
 
Example #15
Source File: CallActivityTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(DelegateExecution execution) throws Exception {
  TypedValue typedValue = execution.getVariableTyped("var");
  assertThat(typedValue).isNotNull();
  assertThat(typedValue.getType()).isEqualTo(ValueType.STRING);
  assertThat(typedValue.isTransient()).isTrue();
  assertThat(typedValue.getValue()).isEqualTo("value");
}
 
Example #16
Source File: DelegateExecutionContext.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the current delegation execution or null if the
 * execution is not available.
 *
 * @return the current delegation execution or null if not available
 */
public static DelegateExecution getCurrentDelegationExecution() {
  BpmnExecutionContext bpmnExecutionContext = Context.getBpmnExecutionContext();
  ExecutionEntity executionEntity = null;
  if (bpmnExecutionContext != null) {
    executionEntity = bpmnExecutionContext.getExecution();
  }
  return executionEntity;
}
 
Example #17
Source File: UelExpressionCondition.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean evaluate(VariableScope scope, DelegateExecution execution) {
  Object result = expression.getValue(scope, execution);
  ensureNotNull("condition expression returns null", "result", result);
  ensureInstanceOf("condition expression returns non-Boolean", "result", result, Boolean.class);
  return (Boolean) result;
}
 
Example #18
Source File: DefaultHistoryEventProducer.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public HistoryEvent createProcessInstanceEndEvt(DelegateExecution execution) {
  final ExecutionEntity executionEntity = (ExecutionEntity) execution;

  // create event instance
  HistoricProcessInstanceEventEntity evt = loadProcessInstanceEventEntity(executionEntity);

  // initialize event
  initProcessInstanceEvent(evt, executionEntity, HistoryEventTypes.PROCESS_INSTANCE_END);

  determineEndState(executionEntity, evt);

  // set end activity id
  evt.setEndActivityId(executionEntity.getActivityId());
  evt.setEndTime(ClockUtil.getCurrentTime());

  if(evt.getStartTime() != null) {
    evt.setDurationInMillis(evt.getEndTime().getTime()-evt.getStartTime().getTime());
  }

  if (isRootProcessInstance(evt) && isHistoryRemovalTimeStrategyEnd()) {
    Date removalTime = calculateRemovalTime(evt);

    if (removalTime != null) {
      addRemovalTimeToHistoricProcessInstances(evt.getRootProcessInstanceId(), removalTime);

      if (isDmnEnabled()) {
        addRemovalTimeToHistoricDecisions(evt.getRootProcessInstanceId(), removalTime);
      }
    }
  }

  // set delete reason (if applicable).
  if (executionEntity.getDeleteReason() != null) {
    evt.setDeleteReason(executionEntity.getDeleteReason());
  }

  return evt;
}
 
Example #19
Source File: BoundedNumberOfMaxResultsDelegate.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(DelegateExecution execution) throws Exception {
  List<ProcessInstance> processInstances = execution.getProcessEngineServices()
      .getRuntimeService()
      .createProcessInstanceQuery()
      .list();

  assertThat(processInstances.size()).isEqualTo(0);
}
 
Example #20
Source File: LoggerDelegate.java    From camunda-archetypes with Apache License 2.0 5 votes vote down vote up
public void execute(DelegateExecution execution) throws Exception {
  
  LOGGER.info("\n\n  ... LoggerDelegate invoked by "
          + "processDefinitionId=" + execution.getProcessDefinitionId()
          + ", activtyId=" + execution.getCurrentActivityId()
          + ", activtyName='" + execution.getCurrentActivityName() + "'"
          + ", processInstanceId=" + execution.getProcessInstanceId()
          + ", businessKey=" + execution.getProcessBusinessKey()
          + ", executionId=" + execution.getId()
          + " \n\n");
  
}
 
Example #21
Source File: DefaultHistoryEventProducer.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public HistoryEvent createProcessInstanceStartEvt(DelegateExecution execution) {
  final ExecutionEntity executionEntity = (ExecutionEntity) execution;

  // create event instance
  HistoricProcessInstanceEventEntity evt = newProcessInstanceEventEntity(executionEntity);

  // initialize event
  initProcessInstanceEvent(evt, executionEntity, HistoryEventTypes.PROCESS_INSTANCE_START);

  evt.setStartActivityId(executionEntity.getActivityId());
  evt.setStartTime(ClockUtil.getCurrentTime());

  // set super process instance id
  ExecutionEntity superExecution = executionEntity.getSuperExecution();
  if (superExecution != null) {
    evt.setSuperProcessInstanceId(superExecution.getProcessInstanceId());
  }

  //state
  evt.setState(HistoricProcessInstance.STATE_ACTIVE);

  // set start user Id
  evt.setStartUserId(Context.getCommandContext().getAuthenticatedUserId());

  if (isHistoryRemovalTimeStrategyStart()) {
    if (isRootProcessInstance(evt)) {
      Date removalTime = calculateRemovalTime(evt);
      evt.setRemovalTime(removalTime);
    } else {
      provideRemovalTime(evt);
    }
  }

  return evt;
}
 
Example #22
Source File: DelegateTaskFake.java    From camunda-bpm-mockito with Apache License 2.0 5 votes vote down vote up
@Override
public String getTenantId() {
  return valueFromCaseOrProcessExecution(
    DelegateExecution::getTenantId,
    DelegateCaseExecution::getTenantId,
    tenantId
  );
}
 
Example #23
Source File: PaymentReceivedAdapter.java    From flowing-retail with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(DelegateExecution context) throws Exception {
  String refId = (String) context.getVariable("refId");
  String correlationId = (String) context.getVariable("correlationId");
  String traceId = context.getProcessBusinessKey();

  messageSender.send( //
      new Message<PaymentReceivedEventPayload>( //
          "PaymentReceivedEvent", //
          traceId, //
          new PaymentReceivedEventPayload() //
              .setRefId(refId))
  		.setCorrelationid(correlationId));
}
 
Example #24
Source File: UpdateValueDelegate.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void execute(DelegateExecution execution) throws Exception {
  TypedValue typedValue = execution.getVariableTyped("listVar");
  List<JsonSerializable> var = (List<JsonSerializable>) typedValue.getValue();
  JsonSerializable newElement = new JsonSerializable();
  newElement.setStringProperty(STRING_PROPERTY);
  // implicit update of the list, so no execution.setVariable call
  var.add(newElement);

}
 
Example #25
Source File: UndoService.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void execute(DelegateExecution execution) throws Exception {
  String variableName = (String) counterName.getValue(execution);
  Object variable = execution.getVariable(variableName);
  if(variable == null) {
    execution.setVariable(variableName, (Integer) 1);
  }
  else  {
    execution.setVariable(variableName, ((Integer)variable)+1);
  }
}
 
Example #26
Source File: PaymentFailedAdapter.java    From flowing-retail-old with Apache License 2.0 5 votes vote down vote up
public void execute(DelegateExecution execution) throws Exception {
  PaymentEventProducer eventProducer = new PaymentEventProducer();
  
  String transactionId = (String)execution.getVariable("transactionId");
  String refId = (String)execution.getVariable("refId");
  String reason = (String)execution.getVariable("reason");

  eventProducer.publishEventPaymentFailedEvent(transactionId, refId, reason);
}
 
Example #27
Source File: ProcessApplicationEventListenerTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
@Deployment
public void testIntermediateSignalEvent() {

  // given
  final List<String> timerEvents = new ArrayList<String>();

  EmbeddedProcessApplication processApplication = new EmbeddedProcessApplication() {
    public ExecutionListener getExecutionListener() {
      return new ExecutionListener() {
        public void notify(DelegateExecution delegateExecution) {
          String currentActivityId = delegateExecution.getCurrentActivityId();
          String eventName = delegateExecution.getEventName();
          if ("signal".equals(currentActivityId) &&
              (ExecutionListener.EVENTNAME_START.equals(eventName) || ExecutionListener.EVENTNAME_END.equals(eventName))) {
            timerEvents.add(delegateExecution.getEventName());
          }
        }
      };
    }
  };

  // register app so that it is notified about events
  managementService.registerProcessApplication(deploymentId, processApplication.getReference());

  // when
  runtimeService.startProcessInstanceByKey("process");
  runtimeService.signalEventReceived("abort");

  // then
  assertEquals(2, timerEvents.size());

  // "start" event listener
  assertEquals(ExecutionListener.EVENTNAME_START, timerEvents.get(0));

  // "end" event listener
  assertEquals(ExecutionListener.EVENTNAME_END, timerEvents.get(1));
}
 
Example #28
Source File: ProcessApplicationEventListenerDelegate.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void notify(final DelegateExecution execution) throws Exception {
  Callable<Void> notification = new Callable<Void>() {
    public Void call() throws Exception {
      notifyExecutionListener(execution);
      return null;
    }
  };
  performNotification(execution, notification);
}
 
Example #29
Source File: AssertVariableInstancesDelegate.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void execute(DelegateExecution execution) throws Exception {

    // validate integer variable
    Integer expectedIntValue = 1234;
    assertEquals(expectedIntValue, execution.getVariable("anIntegerVariable"));
    assertEquals(expectedIntValue, execution.getVariableTyped("anIntegerVariable").getValue());
    assertEquals(ValueType.INTEGER, execution.getVariableTyped("anIntegerVariable").getType());
    assertNull(execution.getVariableLocal("anIntegerVariable"));
    assertNull(execution.getVariableLocalTyped("anIntegerVariable"));

    // set an additional local variable
    execution.setVariableLocal("aStringVariable", "aStringValue");

    String expectedStringValue = "aStringValue";
    assertEquals(expectedStringValue, execution.getVariable("aStringVariable"));
    assertEquals(expectedStringValue, execution.getVariableTyped("aStringVariable").getValue());
    assertEquals(ValueType.STRING, execution.getVariableTyped("aStringVariable").getType());
    assertEquals(expectedStringValue, execution.getVariableLocal("aStringVariable"));
    assertEquals(expectedStringValue, execution.getVariableLocalTyped("aStringVariable").getValue());
    assertEquals(ValueType.STRING, execution.getVariableLocalTyped("aStringVariable").getType());

    SimpleSerializableBean objectValue = (SimpleSerializableBean) execution.getVariable("anObjectValue");
    assertNotNull(objectValue);
    assertEquals(10, objectValue.getIntProperty());
    ObjectValue variableTyped = execution.getVariableTyped("anObjectValue");
    assertEquals(10, variableTyped.getValue(SimpleSerializableBean.class).getIntProperty());
    assertEquals(Variables.SerializationDataFormats.JAVA.getName(), variableTyped.getSerializationDataFormat());

    objectValue = (SimpleSerializableBean) execution.getVariable("anUntypedObjectValue");
    assertNotNull(objectValue);
    assertEquals(30, objectValue.getIntProperty());
    variableTyped = execution.getVariableTyped("anUntypedObjectValue");
    assertEquals(30, variableTyped.getValue(SimpleSerializableBean.class).getIntProperty());
    assertEquals(Context.getProcessEngineConfiguration().getDefaultSerializationFormat(), variableTyped.getSerializationDataFormat());

  }
 
Example #30
Source File: MultiTenancyDelegateExecutionTest.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected static DelegateExecutionAsserter hasTenantId(final String expectedTenantId) {
  return new DelegateExecutionAsserter() {

    @Override
    public void doAssert(DelegateExecution execution) {
      assertThat(execution.getTenantId(), is(expectedTenantId));
    }
  };
}