Java Code Examples for org.activiti.engine.impl.interceptor.CommandExecutor#execute()

The following examples show how to use org.activiti.engine.impl.interceptor.CommandExecutor#execute() . 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: JobQueryTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
private void createJobWithoutExceptionStacktrace() {
    CommandExecutor commandExecutor = (CommandExecutor) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawCommandExecutor();
    commandExecutor.execute(new Command<Void>() {
        public Void execute(CommandContext commandContext) {
            JobEntityManager jobManager = commandContext.getJobEntityManager();

            jobEntity = new JobEntity();
            jobEntity.setJobType(Job.JOB_TYPE_MESSAGE);
            jobEntity.setRevision(1);
            jobEntity.setLockOwner(UUID.randomUUID().toString());
            jobEntity.setRetries(0);
            jobEntity.setExceptionMessage("I'm supposed to fail");

            jobManager.insert(jobEntity);

            assertNotNull(jobEntity.getId());

            return null;

        }
    });

}
 
Example 2
Source File: JobQueryTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
private void createJobWithoutExceptionMsg() {
  CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutor();
  commandExecutor.execute(new Command<Void>() {
    public Void execute(CommandContext commandContext) {
      jobEntity = commandContext.getJobEntityManager().create();
      jobEntity.setJobType(Job.JOB_TYPE_MESSAGE);
      jobEntity.setLockOwner(UUID.randomUUID().toString());
      jobEntity.setRetries(0);
      
      StringWriter stringWriter = new StringWriter();
      NullPointerException exception = new NullPointerException();
      exception.printStackTrace(new PrintWriter(stringWriter));
      jobEntity.setExceptionStacktrace(stringWriter.toString());

      commandContext.getJobEntityManager().insert(jobEntity);

      assertNotNull(jobEntity.getId());

      return null;

    }
  });

}
 
Example 3
Source File: AsyncJobUtil.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected static void unlockJobIsNeeded(final JobEntity job, final CommandExecutor commandExecutor) {
    try {
        if (job.isExclusive()) {
            commandExecutor.execute(new UnlockExclusiveJobCmd(job));
        }

    } catch (ActivitiOptimisticLockingException optimisticLockingException) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Optimistic locking exception while unlocking the job. If you have multiple async executors running against the same database, " +
                    "this exception means that this thread tried to acquire an exclusive job, which already was changed by another async executor thread." +
                    "This is expected behavior in a clustered environment. " +
                    "You can ignore this message if you indeed have multiple job executor acquisition threads running against the same database. " +
                    "Exception message: {}", optimisticLockingException.getMessage());
        }
    } catch (Throwable t) {
        LOGGER.error("Error while unlocking exclusive job {}", job.getId(), t);
    }
}
 
Example 4
Source File: ProcessInstanceMigrationTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { TEST_PROCESS_CALL_ACTIVITY })
public void testSetProcessDefinitionVersionWithCallActivity() {
  // start process instance
  ProcessInstance pi = runtimeService.startProcessInstanceByKey("parentProcess");

  // check that receive task has been reached
  Execution execution = runtimeService.createExecutionQuery().activityId("waitState1").processDefinitionKey("childProcess").singleResult();
  assertNotNull(execution);

  // deploy new version of the process definition
  org.activiti.engine.repository.Deployment deployment = repositoryService.createDeployment().addClasspathResource(TEST_PROCESS_CALL_ACTIVITY).deploy();
  assertEquals(2, repositoryService.createProcessDefinitionQuery().processDefinitionKey("parentProcess").count());

  // migrate process instance to new process definition version
  CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutor();
  commandExecutor.execute(new SetProcessDefinitionVersionCmd(pi.getId(), 2));

  // signal process instance
  runtimeService.trigger(execution.getId());

  // should be finished now
  assertEquals(0, runtimeService.createProcessInstanceQuery().processInstanceId(pi.getId()).count());

  // undeploy "manually" deployed process definition
  repositoryService.deleteDeployment(deployment.getId(), true);
}
 
Example 5
Source File: CommandContextTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
public void testCommandContextGetCurrentAfterException() {
    try {
        CommandExecutor commandExecutor = (CommandExecutor) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawCommandExecutor();
        commandExecutor.execute(new Command<Object>() {
            public Object execute(CommandContext commandContext) {
                throw new IllegalStateException("here i come!");
            }
        });

        fail("expected exception");
    } catch (IllegalStateException e) {
        // OK
    }

    assertNull(Context.getCommandContext());
}
 
Example 6
Source File: ProcessInstanceMigrationTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { TEST_PROCESS })
public void testSetProcessDefinitionVersionActivityMissing() {
  // start process instance
  ProcessInstance pi = runtimeService.startProcessInstanceByKey("receiveTask");

  // check that receive task has been reached
  Execution execution = runtimeService.createExecutionQuery().activityId("waitState1").singleResult();
  assertNotNull(execution);

  // deploy new version of the process definition
  org.activiti.engine.repository.Deployment deployment = repositoryService.createDeployment().addClasspathResource(TEST_PROCESS_ACTIVITY_MISSING).deploy();
  assertEquals(2, repositoryService.createProcessDefinitionQuery().count());

  // migrate process instance to new process definition version
  CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutor();
  SetProcessDefinitionVersionCmd setProcessDefinitionVersionCmd = new SetProcessDefinitionVersionCmd(pi.getId(), 2);
  try {
    commandExecutor.execute(setProcessDefinitionVersionCmd);
    fail("ActivitiException expected");
  } catch (ActivitiException ae) {
    assertTextPresent("The new process definition (key = 'receiveTask') does not contain the current activity (id = 'waitState1') of the process instance (id = '", ae.getMessage());
  }

  // undeploy "manually" deployed process definition
  repositoryService.deleteDeployment(deployment.getId(), true);
}
 
Example 7
Source File: ProcessInstanceSuspensionTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void makeSureJobDue(final Job job) {
    CommandExecutor commandExecutor = (CommandExecutor) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawCommandExecutor();
    commandExecutor.execute(new Command<Void>() {
        public Void execute(CommandContext commandContext) {
            Date currentTime = processEngineConfiguration.getClock().getCurrentTime();
            commandContext.getTimerJobEntityManager()
                    .findJobById(job.getId())
                    .setDuedate(new Date(currentTime.getTime() - 10000));
            return null;
        }

    });
}
 
Example 8
Source File: JobExecutorTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void testBasicJobExecutorOperation() throws Exception {
  CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutor();
  commandExecutor.execute(new Command<Void>() {
    public Void execute(CommandContext commandContext) {
      JobManager jobManager = commandContext.getJobManager();
      jobManager.execute(createTweetMessage("message-one"));
      jobManager.execute(createTweetMessage("message-two"));
      jobManager.execute(createTweetMessage("message-three"));
      jobManager.execute(createTweetMessage("message-four"));

      TimerJobEntityManager timerJobManager = commandContext.getTimerJobEntityManager();
      timerJobManager.insert(createTweetTimer("timer-one", new Date()));
      timerJobManager.insert(createTweetTimer("timer-one", new Date()));
      timerJobManager.insert(createTweetTimer("timer-two", new Date()));
      return null;
    }
  });

  GregorianCalendar currentCal = new GregorianCalendar();
  currentCal.add(Calendar.MINUTE, 1);
  processEngineConfiguration.getClock().setCurrentTime(currentCal.getTime());

  waitForJobExecutorToProcessAllJobs(8000L, 200L);

  Set<String> messages = new HashSet<String>(tweetHandler.getMessages());
  Set<String> expectedMessages = new HashSet<String>();
  expectedMessages.add("message-one");
  expectedMessages.add("message-two");
  expectedMessages.add("message-three");
  expectedMessages.add("message-four");
  expectedMessages.add("timer-one");
  expectedMessages.add("timer-two");

  assertEquals(new TreeSet<String>(expectedMessages), new TreeSet<String>(messages));
}
 
Example 9
Source File: JobQueryTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private void deleteJobInDatabase() {
    CommandExecutor commandExecutor = (CommandExecutor) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawCommandExecutor();
    commandExecutor.execute(new Command<Void>() {
        public Void execute(CommandContext commandContext) {

            jobEntity.delete();
            return null;
        }
    });
}
 
Example 10
Source File: BaseSpringRestTestCase.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
/**
 * Each test is assumed to clean up all DB content it entered. After a test method executed, this method scans all tables to see if the DB is completely clean. It throws AssertionFailed in case the
 * DB is not clean. If the DB is not clean, it is cleaned by performing a create a drop.
 */
protected void assertAndEnsureCleanDb() throws Throwable {
  log.debug("verifying that db is clean after test");
  Map<String, Long> tableCounts = managementService.getTableCount();
  StringBuilder outputMessage = new StringBuilder();
  for (String tableName : tableCounts.keySet()) {
    String tableNameWithoutPrefix = tableName.replace(processEngineConfiguration.getDatabaseTablePrefix(), "");
    if (!TABLENAMES_EXCLUDED_FROM_DB_CLEAN_CHECK.contains(tableNameWithoutPrefix)) {
      Long count = tableCounts.get(tableName);
      if (count != 0L) {
        outputMessage.append("  " + tableName + ": " + count + " record(s) ");
      }
    }
  }
  if (outputMessage.length() > 0) {
    outputMessage.insert(0, "DB NOT CLEAN: \n");
    log.error(EMPTY_LINE);
    log.error(outputMessage.toString());

    log.info("dropping and recreating db");

    CommandExecutor commandExecutor = ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getCommandExecutor();
    commandExecutor.execute(new Command<Object>() {
      public Object execute(CommandContext commandContext) {
        DbSqlSession session = commandContext.getDbSqlSession();
        session.dbSchemaDrop();
        session.dbSchemaCreate();
        return null;
      }
    });

    if (exception != null) {
      throw exception;
    } else {
      Assert.fail(outputMessage.toString());
    }
  } else {
    log.info("database was clean");
  }
}
 
Example 11
Source File: EventSubscriptionQueryTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public void testQueryByActivityId() {

        CommandExecutor commandExecutor = (CommandExecutor) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawCommandExecutor();
        commandExecutor.execute(new Command<Void>() {
            public Void execute(CommandContext commandContext) {

                MessageEventSubscriptionEntity messageEventSubscriptionEntity1 = new MessageEventSubscriptionEntity();
                messageEventSubscriptionEntity1.setEventName("messageName");
                messageEventSubscriptionEntity1.setActivityId("someActivity");
                messageEventSubscriptionEntity1.insert();

                MessageEventSubscriptionEntity messageEventSubscriptionEntity2 = new MessageEventSubscriptionEntity();
                messageEventSubscriptionEntity2.setEventName("messageName");
                messageEventSubscriptionEntity2.setActivityId("someActivity");
                messageEventSubscriptionEntity2.insert();

                SignalEventSubscriptionEntity signalEventSubscriptionEntity3 = new SignalEventSubscriptionEntity();
                signalEventSubscriptionEntity3.setEventName("messageName2");
                signalEventSubscriptionEntity3.setActivityId("someOtherActivity");
                signalEventSubscriptionEntity3.insert();

                return null;
            }
        });

        List<EventSubscriptionEntity> list = newEventSubscriptionQuery()
                .activityId("someOtherActivity")
                .list();
        assertEquals(1, list.size());

        list = newEventSubscriptionQuery()
                .activityId("someActivity")
                .eventType("message")
                .list();
        assertEquals(2, list.size());

        cleanDb();

    }
 
Example 12
Source File: BpmnDeploymentTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void testDiagramCreationDisabled() {
  // disable diagram generation
  processEngineConfiguration.setCreateDiagramOnDeploy(false);

  try {
    repositoryService.createDeployment().addClasspathResource("org/activiti/engine/test/bpmn/parse/BpmnParseTest.testParseDiagramInterchangeElements.bpmn20.xml").deploy();

    // Graphical information is not yet exposed publicly, so we need to
    // do some plumbing
    CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutor();
    ProcessDefinition processDefinition = commandExecutor.execute(new Command<ProcessDefinition>() {
      public ProcessDefinition execute(CommandContext commandContext) {
        return Context.getProcessEngineConfiguration().getDeploymentManager().findDeployedLatestProcessDefinitionByKey("myProcess");
      }
    });

    assertNotNull(processDefinition);
    BpmnModel processModel = repositoryService.getBpmnModel(processDefinition.getId());
    assertEquals(14, processModel.getMainProcess().getFlowElements().size());
    assertEquals(7, processModel.getMainProcess().findFlowElementsOfType(SequenceFlow.class).size());

    // Check that no diagram has been created
    List<String> resourceNames = repositoryService.getDeploymentResourceNames(processDefinition.getDeploymentId());
    assertEquals(1, resourceNames.size());

    repositoryService.deleteDeployment(repositoryService.createDeploymentQuery().singleResult().getId(), true);
  } finally {
    processEngineConfiguration.setCreateDiagramOnDeploy(true);
  }
}
 
Example 13
Source File: BaseJPARestTestCase.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
/**
 * Each test is assumed to clean up all DB content it entered. After a test method executed, this method scans all tables to see if the DB is completely clean. It throws AssertionFailed in case the
 * DB is not clean. If the DB is not clean, it is cleaned by performing a create a drop.
 */
protected void assertAndEnsureCleanDb() throws Throwable {
  log.debug("verifying that db is clean after test");
  Map<String, Long> tableCounts = managementService.getTableCount();
  StringBuilder outputMessage = new StringBuilder();
  for (String tableName : tableCounts.keySet()) {
    String tableNameWithoutPrefix = tableName.replace(processEngineConfiguration.getDatabaseTablePrefix(), "");
    if (!TABLENAMES_EXCLUDED_FROM_DB_CLEAN_CHECK.contains(tableNameWithoutPrefix)) {
      Long count = tableCounts.get(tableName);
      if (count != 0L) {
        outputMessage.append("  " + tableName + ": " + count + " record(s) ");
      }
    }
  }
  if (outputMessage.length() > 0) {
    outputMessage.insert(0, "DB NOT CLEAN: \n");
    log.error(EMPTY_LINE);
    log.error(outputMessage.toString());

    log.info("dropping and recreating db");

    CommandExecutor commandExecutor = ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getCommandExecutor();
    commandExecutor.execute(new Command<Object>() {
      public Object execute(CommandContext commandContext) {
        DbSqlSession session = commandContext.getDbSqlSession();
        session.dbSchemaDrop();
        session.dbSchemaCreate();
        return null;
      }
    });

    if (exception != null) {
      throw exception;
    } else {
      Assert.fail(outputMessage.toString());
    }
  } else {
    log.info("database was clean");
  }
}
 
Example 14
Source File: ProcessInstanceMigrationTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void testSetProcessDefinitionVersionNonExistingPI() {
  CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutor();
  try {
    commandExecutor.execute(new SetProcessDefinitionVersionCmd("42", 23));
    fail("ActivitiException expected");
  } catch (ActivitiObjectNotFoundException ae) {
    assertTextPresent("No process instance found for id = '42'.", ae.getMessage());
    assertEquals(ProcessInstance.class, ae.getObjectClass());
  }
}
 
Example 15
Source File: EventSubscriptionQueryTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void cleanDb() {
    CommandExecutor commandExecutor = (CommandExecutor) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawCommandExecutor();
    commandExecutor.execute(new Command<Void>() {
        public Void execute(CommandContext commandContext) {
            final List<EventSubscriptionEntity> subscriptions = new EventSubscriptionQueryImpl(commandContext).list();
            for (EventSubscriptionEntity eventSubscriptionEntity : subscriptions) {
                eventSubscriptionEntity.delete();
            }
            return null;
        }
    });

}
 
Example 16
Source File: ManagementServiceTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Deployment(resources = { "org/activiti5/engine/test/api/mgmt/timerOnTask.bpmn20.xml" })
public void testDeleteJobThatWasAlreadyAcquired() {
  Clock clock = processEngineConfiguration.getClock();
  processEngineConfiguration.resetClock();
  
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("timerOnTask");
  Job timerJob = managementService.createTimerJobQuery().processInstanceId(processInstance.getId()).singleResult();
  
  // We need to move time at least one hour to make the timer executable
  clock.setCurrentTime(new Date(processEngineConfiguration.getClock().getCurrentTime().getTime() + 7200000L));
  processEngineConfiguration.setClock(clock);

  // Acquire job by running the acquire command manually
  AcquireTimerJobsCmd acquireJobsCmd = new AcquireTimerJobsCmd(processEngineConfiguration.getAsyncExecutor());
  CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutor();
  commandExecutor.execute(acquireJobsCmd);
  
  // Try to delete the job. This should fail.
  try {
    managementService.deleteJob(timerJob.getId());
    fail();
  } catch (ActivitiException e) {
    // Exception is expected
  }
  
  // Clean up
  managementService.moveTimerToExecutableJob(timerJob.getId());
  managementService.executeJob(timerJob.getId());
  
  processEngineConfiguration.resetClock();
}
 
Example 17
Source File: DbSchemaUpdate.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  ProcessEngineImpl processEngine = (ProcessEngineImpl) ProcessEngines.getDefaultProcessEngine();
  CommandExecutor commandExecutor = processEngine.getProcessEngineConfiguration().getCommandExecutor();
  CommandConfig config = new CommandConfig().transactionNotSupported();
  commandExecutor.execute(config, new Command<Object>() {
    public Object execute(CommandContext commandContext) {
      commandContext.getDbSqlSession().dbSchemaUpdate();
      return null;
    }
  });
}
 
Example 18
Source File: AbstractMuleTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
/**
 * Each test is assumed to clean up all DB content it entered. After a test method executed, this method scans all tables to see if the DB is completely clean. It throws AssertionFailed in case the
 * DB is not clean. If the DB is not clean, it is cleaned by performing a create a drop.
 */
protected void assertAndEnsureCleanDb(ProcessEngine processEngine) throws Exception {
  log.debug("verifying that db is clean after test");
  Map<String, Long> tableCounts = processEngine.getManagementService().getTableCount();
  StringBuilder outputMessage = new StringBuilder();
  for (String tableName : tableCounts.keySet()) {
    String tableNameWithoutPrefix = tableName.replace(processEngine.getProcessEngineConfiguration().getDatabaseTablePrefix(), "");
    if (!TABLENAMES_EXCLUDED_FROM_DB_CLEAN_CHECK.contains(tableNameWithoutPrefix)) {
      Long count = tableCounts.get(tableName);
      if (count != 0L) {
        outputMessage.append("  " + tableName + ": " + count + " record(s) ");
      }
    }
  }
  if (outputMessage.length() > 0) {
    outputMessage.insert(0, "DB NOT CLEAN: \n");
    log.error(EMPTY_LINE);
    log.error(outputMessage.toString());

    log.info("dropping and recreating db");

    CommandExecutor commandExecutor = ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getCommandExecutor();
    CommandConfig config = new CommandConfig().transactionNotSupported();
    commandExecutor.execute(config, new Command<Object>() {
      public Object execute(CommandContext commandContext) {
        DbSqlSession session = commandContext.getDbSqlSession();
        session.dbSchemaDrop();
        session.dbSchemaCreate();
        return null;
      }
    });

    Assert.fail(outputMessage.toString());

  } else {
    log.info("database was clean");
  }
}
 
Example 19
Source File: StartTimerEventTest.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
private void cleanDB() {
  String jobId = managementService.createTimerJobQuery().singleResult().getId();
  CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutor();
  commandExecutor.execute(new CancelJobsCmd(jobId));
}
 
Example 20
Source File: JobExecutorCmdHappyTest.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public void testJobCommandsWithTimer() {
    ProcessEngineConfigurationImpl activiti5ProcessEngineConfig = (ProcessEngineConfigurationImpl) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawProcessConfiguration();

    // clock gets automatically reset in LogTestCase.runTest
    Clock clock = processEngineConfiguration.getClock();
    clock.setCurrentTime(new Date(SOME_TIME));
    processEngineConfiguration.setClock(clock);

    AsyncExecutor asyncExecutor = processEngineConfiguration.getAsyncExecutor();
    CommandExecutor commandExecutor = (CommandExecutor) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawCommandExecutor();

    String jobId = commandExecutor.execute(new Command<String>() {

        public String execute(CommandContext commandContext) {
            TimerJobEntity timer = createTweetTimer("i'm coding a test", new Date(SOME_TIME + (10 * SECOND)));
            commandContext.getJobEntityManager().schedule(timer);
            return timer.getId();
        }
    });

    AcquiredTimerJobEntities acquiredJobs = processEngineConfiguration.getCommandExecutor().execute(new AcquireTimerJobsCmd(asyncExecutor));
    assertEquals(0, acquiredJobs.size());

    clock.setCurrentTime(new Date(SOME_TIME + (20 * SECOND)));
    processEngineConfiguration.setClock(clock);

    acquiredJobs = processEngineConfiguration.getCommandExecutor().execute(new AcquireTimerJobsCmd(asyncExecutor));
    assertEquals(1, acquiredJobs.size());

    Job job = acquiredJobs.getJobs().iterator().next();

    assertEquals(jobId, job.getId());

    assertEquals(0, tweetHandler.getMessages().size());

    managementService.moveTimerToExecutableJob(jobId);
    JobEntity jobEntity = (JobEntity) activiti5ProcessEngineConfig.getManagementService().createJobQuery().singleResult();
    activiti5ProcessEngineConfig.getCommandExecutor().execute(new ExecuteAsyncJobCmd(jobEntity));

    assertEquals("i'm coding a test", tweetHandler.getMessages().get(0));
    assertEquals(1, tweetHandler.getMessages().size());

    processEngineConfiguration.resetClock();
}