Java Code Examples for org.camunda.bpm.engine.ProcessEngine

The following examples show how to use org.camunda.bpm.engine.ProcessEngine. These examples are extracted from open source projects. 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 Project: camunda-bpm-platform   Source File: AbstractQueryDto.java    License: Apache License 2.0 6 votes vote down vote up
protected void applySortingOptions(T query, ProcessEngine engine) {
  if (sortBy != null) {
    applySortBy(query, sortBy, null, engine);
  }
  if (sortOrder != null) {
    applySortOrder(query, sortOrder);
  }

  if (sortings != null) {
    for (SortingDto sorting : sortings) {
      String sortingOrder = sorting.getSortOrder();
      String sortingBy = sorting.getSortBy();

      if (sortingBy != null) {
        applySortBy(query, sortingBy, sorting.getParameters(), engine);
      }
      if (sortingOrder != null) {
        applySortOrder(query, sortingOrder);
      }
    }
  }
}
 
Example 2
public void testDeployAppWithCustomEngine() {

    TestApplicationWithCustomEngine processApplication = new TestApplicationWithCustomEngine();
    processApplication.deploy();

    ProcessEngine processEngine = BpmPlatform.getProcessEngineService().getProcessEngine("embeddedEngine");
    assertNotNull(processEngine);
    assertEquals("embeddedEngine", processEngine.getName());

    ProcessEngineConfiguration configuration = ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration();

    // assert engine properties specified
    assertTrue(configuration.isJobExecutorDeploymentAware());
    assertTrue(configuration.isJobExecutorPreferTimerJobs());
    assertTrue(configuration.isJobExecutorAcquireByDueDate());
    assertEquals(5, configuration.getJdbcMaxActiveConnections());

    processApplication.undeploy();

  }
 
Example 3
Source Project: camunda-bpm-platform   Source File: SignalEventFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public MigratingBpmnEventTrigger addEventSubProcess(ProcessEngine engine, BpmnModelInstance modelInstance, String parentId, String subProcessId, String startEventId) {
  ModifiableBpmnModelInstance.wrap(modelInstance)
    .addSubProcessTo(parentId)
    .id(subProcessId)
    .triggerByEvent()
    .embeddedSubProcess()
      .startEvent(startEventId).signal(SIGNAL_NAME)
    .subProcessDone()
    .done();

  SignalTrigger trigger = new SignalTrigger();
  trigger.engine = engine;
  trigger.signalName = SIGNAL_NAME;
  trigger.activityId = startEventId;

  return trigger;
}
 
Example 4
@DescribesScenario("subProcessHandler.multiInstancePartial")
@Times(3)
public static ScenarioSetup subProcessHandlerMultiInstancePartial() {
  return new ScenarioSetup() {
    public void execute(ProcessEngine engine, String scenarioName) {
      engine
        .getRuntimeService()
        .startProcessInstanceByKey("SequentialMultiInstanceCompensationSubProcessHandlerScenario", scenarioName);

      // complete two out of three MI tasks
      Task miTask = engine.getTaskService().createTaskQuery()
          .processInstanceBusinessKey(scenarioName).singleResult();
      engine.getTaskService().complete(miTask.getId());

      miTask = engine.getTaskService().createTaskQuery()
          .processInstanceBusinessKey(scenarioName).singleResult();
      engine.getTaskService().complete(miTask.getId());
    }
  };
}
 
Example 5
@Override
protected void applySortBy(HistoricIdentityLinkLogQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
  if (sortBy.equals(SORT_BY_TIME)) {
    query.orderByTime();
  } else if (sortBy.equals(SORT_BY_TYPE)) {
    query.orderByType();
  } else if (sortBy.equals(SORT_BY_USER_ID)) {
    query.orderByUserId();
  } else if (sortBy.equals(SORT_BY_GROUP_ID)) {
    query.orderByGroupId();
  } else if (sortBy.equals(SORT_BY_TASK_ID)) {
    query.orderByTaskId();
  } else if (sortBy.equals(SORT_BY_OPERATION_TYPE)) {
    query.orderByOperationType();
  } else if (sortBy.equals(SORT_BY_ASSIGNER_ID)) {
    query.orderByAssignerId();
  } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) {
    query.orderByProcessDefinitionId();
  } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) {
    query.orderByProcessDefinitionKey();
  } else if (sortBy.equals(SORT_BY_TENANT_ID)) {
    query.orderByTenantId();
  }
}
 
Example 6
@DescribesScenario("init.innerSubProcess")
@ExtendsScenario("init")
@Times(6)
public static ScenarioSetup initNestedSubProcessEnterSubprocess() {
  return new ScenarioSetup() {
    public void execute(ProcessEngine engine, String scenarioName) {
      Task eventSubProcessTask = engine.getTaskService()
        .createTaskQuery()
        .processInstanceBusinessKey(scenarioName)
        .taskDefinitionKey("eventSubProcessTask")
        .singleResult();

      engine.getTaskService().complete(eventSubProcessTask.getId());
    }
  };
}
 
Example 7
@DescribesScenario("initLevel1")
@Times(7)
public static ScenarioSetup initLevelOneEventSubProcess() {
  return new ScenarioSetup() {
    public void execute(ProcessEngine engine, String scenarioName) {
      engine
        .getRuntimeService()
        .startProcessInstanceByKey("NestedNonInterruptingMessageEventSubprocessScenarioNestedSubprocess",
            scenarioName);

      engine.getRuntimeService()
        .createMessageCorrelation("OuterEventSubProcessMessage")
        .processInstanceBusinessKey(scenarioName)
        .correlate();
    }
  };
}
 
Example 8
private void createProcessEngine() {
  StandaloneProcessEngineConfiguration configuration = new StandaloneProcessEngineConfiguration();
  configuration.setDatabaseSchemaUpdate("create-drop")
    .setDataSource(createDatasource())
    .setJobExecutorActivate(false);
  configuration.setExpressionManager(new OSGiExpressionManager());
  ProcessEngineFactory processEngineFactory = new ProcessEngineFactory();
  processEngineFactory.setProcessEngineConfiguration(configuration);
  processEngineFactory
    .setBundle(getBundle("org.camunda.bpm.extension.osgi"));
  try {
    processEngineFactory.init();
    processEngine = processEngineFactory.getObject();
    ctx.registerService(ProcessEngine.class.getName(), processEngine,
      new Hashtable<String, String>());
  } catch (Exception e) {
    fail(e.toString());
  }
}
 
Example 9
Source Project: camunda-bpm-platform   Source File: Scenario.java    License: Apache License 2.0 6 votes vote down vote up
public void create(ProcessEngine engine, Map<String, Scenario> scenarios, String scenarioInstanceName) {
  // recursively set up all extended scenarios first
  if (extendedScenario != null) {
    if (scenarios.containsKey(extendedScenario)) {
      Scenario parentScenario = scenarios.get(extendedScenario);
      parentScenario.create(engine, scenarios, scenarioInstanceName);
    }
    else {
      throw new ProcessEngineException("Extended scenario " + extendedScenario + " not registered");
    }
  }

  if (setup != null) {
    setup.execute(engine, scenarioInstanceName);
  }
}
 
Example 10
@DescribesScenario("subProcessHandler.beforeCompensate")
@Times(3)
public static ScenarioSetup subProcessHandlerBeforeCompensate() {
  return new ScenarioSetup() {
    public void execute(ProcessEngine engine, String scenarioName) {
      engine
        .getRuntimeService()
        .startProcessInstanceByKey("SequentialMultiInstanceCompensationSubProcessHandlerScenario", scenarioName);

      // complete all mi tasks
      Task miTask = engine.getTaskService().createTaskQuery()
          .processInstanceBusinessKey(scenarioName).singleResult();
      engine.getTaskService().complete(miTask.getId());

      miTask = engine.getTaskService().createTaskQuery()
          .processInstanceBusinessKey(scenarioName).singleResult();
      engine.getTaskService().complete(miTask.getId());

      miTask = engine.getTaskService().createTaskQuery()
          .processInstanceBusinessKey(scenarioName).singleResult();
      engine.getTaskService().complete(miTask.getId());
    }
  };
}
 
Example 11
@Test
public void do_not_create_when_already_exist() throws Exception {
  CamundaBpmProperties camundaBpmProperties = new CamundaBpmProperties();
  camundaBpmProperties.getFilter().setCreate("All");
  final CreateFilterConfiguration configuration = new CreateFilterConfiguration();
  ReflectionTestUtils.setField(configuration, "camundaBpmProperties", camundaBpmProperties);
  configuration.init();

  ProcessEngine engine = mock(ProcessEngine.class);
  FilterService filterService = mock(FilterService.class);
  FilterQuery filterQuery = mock(FilterQuery.class);
  Filter filter = mock(Filter.class);

  when(engine.getFilterService()).thenReturn(filterService);
  when(filterService.createFilterQuery()).thenReturn(filterQuery);
  when(filterQuery.filterName(anyString())).thenReturn(filterQuery);
  when(filterQuery.singleResult()).thenReturn(filter);

  configuration.postProcessEngineBuild(engine);

  verify(filterService).createFilterQuery();
  verify(filterQuery).filterName("All");
  verify(filterService, never()).newTaskFilter("All");

}
 
Example 12
@Test
public void shouldCreateHistoryCleanupJobLogs() {

  final ProcessEngineConfigurationImpl standaloneInMemProcessEngineConfiguration =
      (ProcessEngineConfigurationImpl)ProcessEngineConfiguration
          .createStandaloneInMemProcessEngineConfiguration();
  standaloneInMemProcessEngineConfiguration.setHistoryCleanupBatchWindowStartTime("23:00");
  standaloneInMemProcessEngineConfiguration.setHistoryCleanupBatchWindowEndTime("01:00");
  standaloneInMemProcessEngineConfiguration
      .setJdbcUrl("jdbc:h2:mem:camunda" + getClass().getSimpleName() + "testHistoryCleanupJobScheduled");

  ProcessEngine engine = standaloneInMemProcessEngineConfiguration.buildProcessEngine();
  try {
    List<HistoricJobLog> historicJobLogs = engine.getHistoryService()
                                                 .createHistoricJobLogQuery()
                                                 .jobDefinitionType(HistoryCleanupJobHandler.TYPE)
                                                 .list();
    for (HistoricJobLog historicJobLog : historicJobLogs) {
      assertNotNull(historicJobLog.getHostname());
    }
  } finally {
    closeProcessEngine(engine);
  }
}
 
Example 13
@DescribesScenario("init.outerTask")
@ExtendsScenario("init")
@Times(3)
public static ScenarioSetup completeSubprocessTask() {
  return new ScenarioSetup() {
    public void execute(ProcessEngine engine, String scenarioName) {
      Task task = engine
        .getTaskService()
        .createTaskQuery()
        .processInstanceBusinessKey(scenarioName)
        .taskDefinitionKey("outerTask")
        .singleResult();

      engine.getTaskService().complete(task.getId());
    }
  };
}
 
Example 14
private void mockServices(ProcessEngine engine) {
  RepositoryService repoService = mock(RepositoryService.class);
  IdentityService identityService = mock(IdentityService.class);
  TaskService taskService = mock(TaskService.class);
  RuntimeService runtimeService = mock(RuntimeService.class);
  FormService formService = mock(FormService.class);
  HistoryService historyService = mock(HistoryService.class);
  ManagementService managementService = mock(ManagementService.class);
  CaseService caseService = mock(CaseService.class);
  FilterService filterService = mock(FilterService.class);
  ExternalTaskService externalTaskService = mock(ExternalTaskService.class);

  when(engine.getRepositoryService()).thenReturn(repoService);
  when(engine.getIdentityService()).thenReturn(identityService);
  when(engine.getTaskService()).thenReturn(taskService);
  when(engine.getRuntimeService()).thenReturn(runtimeService);
  when(engine.getFormService()).thenReturn(formService);
  when(engine.getHistoryService()).thenReturn(historyService);
  when(engine.getManagementService()).thenReturn(managementService);
  when(engine.getCaseService()).thenReturn(caseService);
  when(engine.getFilterService()).thenReturn(filterService);
  when(engine.getExternalTaskService()).thenReturn(externalTaskService);
}
 
Example 15
Source Project: camunda-bpm-platform   Source File: TestHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static String assertAndEnsureNoProcessApplicationsRegistered(ProcessEngine processEngine) {
  ProcessEngineConfigurationImpl engineConfiguration = (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration();
  ProcessApplicationManager processApplicationManager = engineConfiguration.getProcessApplicationManager();

  if (processApplicationManager.hasRegistrations()) {
    processApplicationManager.clearRegistrations();
    return "There are still process applications registered";
  }
  else {
    return null;
  }

}
 
Example 16
Source Project: camunda-bpm-platform   Source File: TestFixture.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  ProcessEngineConfigurationImpl processEngineConfiguration = (ProcessEngineConfigurationImpl) ProcessEngineConfiguration
    .createProcessEngineConfigurationFromResource("camunda.cfg.xml");
  ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine();

  // register test scenarios
  ScenarioRunner runner = new ScenarioRunner(processEngine, ENGINE_VERSION);

  // cmmn sentries
  runner.setupScenarios(SentryScenario.class);

  // compensation
  runner.setupScenarios(SingleActivityCompensationScenario.class);
  runner.setupScenarios(NestedCompensationScenario.class);
  runner.setupScenarios(SingleActivityConcurrentCompensationScenario.class);
  runner.setupScenarios(ParallelMultiInstanceCompensationScenario.class);
  runner.setupScenarios(SequentialMultiInstanceCompensationScenario.class);
  runner.setupScenarios(NestedMultiInstanceCompensationScenario.class);
  runner.setupScenarios(InterruptingEventSubProcessCompensationScenario.class);
  runner.setupScenarios(NonInterruptingEventSubProcessCompensationScenario.class);
  runner.setupScenarios(InterruptingEventSubProcessNestedCompensationScenario.class);

  // job
  runner.setupScenarios(JobMigrationScenario.class);

  // boundary events
  runner.setupScenarios(NonInterruptingBoundaryEventScenario.class);

  processEngine.close();
}
 
Example 17
private List<String> getUserGroups(String userId, ProcessEngine engine){
    List<String> groupIds = new ArrayList<>();
    // query groups using KeycloakIdentityProvider plugin
    engine.getIdentityService().createGroupQuery().groupMember(userId).list()
    	.forEach( g -> groupIds.add(g.getId()));
    return groupIds;
}
 
Example 18
public static void main(String... args) {
  SpringApplication.run(Application.class, args);

  // do default setup of platform
  ProcessEngine engine = BpmPlatform.getDefaultProcessEngine();
  createDefaultUser(engine);
  //setCamundaEELicenseKey(engine);
}
 
Example 19
@DescribesScenario("init.triggerCompensation")
@ExtendsScenario("init")
@Times(3)
public static ScenarioSetup instantiateAndTriggerCompensation() {
  return new ScenarioSetup() {
    public void execute(ProcessEngine engine, String scenarioName) {
      // throw compensation by executing the cancel end event;
      // the compensation handler for userTask should then be active
      Task beforeCancelTask = engine.getTaskService().createTaskQuery()
          .processInstanceBusinessKey(scenarioName).singleResult();
      engine.getTaskService().complete(beforeCancelTask.getId());
    }
  };
}
 
Example 20
@Test
public void initProcessEngine() throws Exception {
	// create mocks
	Bundle bundle = mock(Bundle.class);
	ProcessEngineConfiguration configuration = mock(ProcessEngineConfiguration.class);
	ProcessEngine engine = mock(ProcessEngine.class);
	// mock behaviour
	when(configuration.buildProcessEngine()).thenReturn(engine);
	ArgumentCaptor<ClassLoader> classLoaderCaptor = ArgumentCaptor
			.forClass(ClassLoader.class);
	// call methods
	factory.setBundle(bundle);
	factory.setProcessEngineConfiguration(configuration);
	factory.init();
	// checks
	verify(configuration).setClassLoader(classLoaderCaptor.capture());
	assertThat(classLoaderCaptor.getValue(),
			is(instanceOf(BundleDelegatingClassLoader.class)));
	BundleDelegatingClassLoader bundleDelCl = (BundleDelegatingClassLoader) classLoaderCaptor
			.getValue();
	assertThat(bundleDelCl.getBundle(), is(bundle));
	verify(configuration).buildProcessEngine();
	assertThat(Thread.currentThread().getContextClassLoader(),
			is(not(instanceOf(ClassLoaderWrapper.class))));
	assertThat(factory.getObject(), is(engine));
	assertThat(factory.getBundle(), is(bundle));
	assertThat(factory.getProcessEngineConfiguration(), is(configuration));
	factory.destroy();
	verify(engine).close();
}
 
Example 21
Source Project: camunda-bpm-platform   Source File: ExecutionQueryDto.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void applySortBy(ExecutionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
  if (sortBy.equals(SORT_BY_INSTANCE_ID_VALUE)) {
    query.orderByProcessInstanceId();
  } else if (sortBy.equals(SORT_BY_DEFINITION_KEY_VALUE)) {
    query.orderByProcessDefinitionKey();
  } else if (sortBy.equals(SORT_BY_DEFINITION_ID_VALUE)) {
    query.orderByProcessDefinitionId();
  } else if (sortBy.equals(SORT_BY_TENANT_ID)) {
    query.orderByTenantId();
  }
}
 
Example 22
protected void setAuthenticatedUser(ProcessEngine engine, String userId, List<String> groupIds, List<String> tenantIds) {
  if (groupIds == null) {
    groupIds = getGroupsOfUser(engine, userId);
  }

  if (tenantIds == null) {
    tenantIds = getTenantsOfUser(engine, userId);
  }

  engine.getIdentityService().setAuthentication(userId, groupIds, tenantIds);
}
 
Example 23
@DescribesScenario("init")
@Times(1)
public static ScenarioSetup initMessage() {
  return new ScenarioSetup() {
    public void execute(ProcessEngine engine, String scenarioName) {
      engine
        .getRuntimeService()
        .startProcessInstanceByKey("NonInterruptingMessageBoundaryEventScenario", scenarioName);

      engine.getRuntimeService().correlateMessage("BoundaryEventMessage", scenarioName);
    }
  };
}
 
Example 24
protected ProcessEngine getProcessEngine(String name) {
  ServiceLoader<ProcessEngineProvider> serviceLoader = ServiceLoader
      .load(ProcessEngineProvider.class);
  Iterator<ProcessEngineProvider> iterator = serviceLoader.iterator();

  if (iterator.hasNext()) {
    ProcessEngineProvider provider = iterator.next();
    return provider.getProcessEngine(name);
  } else {
    throw new ProcessEngineException("No provider found");
  }
}
 
Example 25
Source Project: camunda-bpm-reactor   Source File: CamundaReactorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void get_eventBus_from_engine() {
  final CamundaEventBus eventBus = new CamundaEventBus();
  ProcessEngine engine = new ReactorProcessEngineConfiguration(eventBus).buildProcessEngine();

  try {
    assertThat(CamundaReactor.eventBus(engine)).isEqualTo(eventBus);

  } finally {
    engine.close();
  }
}
 
Example 26
Source Project: camunda-bpm-platform   Source File: TaskRestServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void createTask(TaskDto taskDto) {
  ProcessEngine engine = getProcessEngine();
  TaskService taskService = engine.getTaskService();

  Task newTask = taskService.newTask(taskDto.getId());
  taskDto.updateTask(newTask);

  try {
    taskService.saveTask(newTask);

  } catch (NotValidException e) {
    throw new InvalidRequestException(Status.BAD_REQUEST, e, "Could not save task: " + e.getMessage());
  }

}
 
Example 27
private ProcessEngine mockProcessEngine(String engineName) {
  ProcessEngine engine = mock(ProcessEngine.class);
  when(engine.getName()).thenReturn(engineName);
  mockServices(engine);
  mockProcessEngineConfiguration(engine);
  return engine;
}
 
Example 28
Source Project: camunda-bpm-platform   Source File: PurgeDatabaseTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that the database is clean after the test. This means the test has to remove
 * all resources it entered to the database.
 * If the DB is not clean, it is cleaned by performing a create a drop.
 *
 * @param processEngine the {@link ProcessEngine} to check
 * @param fail if true the method will throw an {@link AssertionError} if the database is not clean
 * @return the database summary if fail is set to false or null if database was clean
 * @throws AssertionError if the database was not clean and fail is set to true
 */
public static void assertAndEnsureCleanDb(ProcessEngine processEngine) {
  ProcessEngineConfigurationImpl processEngineConfiguration = ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration();
  String databaseTablePrefix = processEngineConfiguration.getDatabaseTablePrefix().trim();

  Map<String, Long> tableCounts = processEngine.getManagementService().getTableCount();

  StringBuilder outputMessage = new StringBuilder();
  for (String tableName : tableCounts.keySet()) {
    String tableNameWithoutPrefix = tableName.replace(databaseTablePrefix, "");
    if (!TABLENAMES_EXCLUDED_FROM_DB_CLEAN_CHECK.contains(tableNameWithoutPrefix)) {
      Long count = tableCounts.get(tableName);
      if (count!=0L) {
        outputMessage.append("\t").append(tableName).append(": ").append(count).append(" record(s)\n");
      }
    }
  }

  if (outputMessage.length() > 0) {
    outputMessage.insert(0, "DB NOT CLEAN: \n");
    /** skip drop and recreate if a table prefix is used */
    if (databaseTablePrefix.isEmpty()) {
      processEngineConfiguration
        .getCommandExecutorSchemaOperations()
        .execute(new Command<Object>() {
          public Object execute(CommandContext commandContext) {
            PersistenceSession persistenceSession = commandContext.getSession(PersistenceSession.class);
            persistenceSession.dbSchemaDrop();
            persistenceSession.dbSchemaCreate();
            HistoryLevelSetupCommand.dbCreateHistoryLevel(commandContext);
            return null;
          }
        });
    }
    Assert.fail(outputMessage.toString());
  }
}
 
Example 29
protected FetchAndLockResult tryFetchAndLock(FetchAndLockRequest request) {

    ProcessEngine processEngine = null;
    IdentityService identityService = null;
    FetchAndLockResult result = null;

    try {
      processEngine = getProcessEngine(request);

      identityService = processEngine.getIdentityService();
      identityService.setAuthentication(request.getAuthentication());

      FetchExternalTasksExtendedDto fetchingDto = request.getDto();
      List<LockedExternalTaskDto> lockedTasks = executeFetchAndLock(fetchingDto, processEngine);
      result = FetchAndLockResult.successful(lockedTasks);
    }
    catch (Exception e) {
      result = FetchAndLockResult.failed(e);
    }
    finally {
      if (identityService != null) {
        identityService.clearAuthentication();
      }
    }

    return result;
  }
 
Example 30
public Set<String> getProcessEngineNames() {
  HashSet<String> result = new HashSet<String>();
  for (ProcessEngine engine : processEngines) {
    result.add(engine.getName());
  }
  return result;
}