org.activiti.engine.impl.interceptor.CommandConfig Java Examples

The following examples show how to use org.activiti.engine.impl.interceptor.CommandConfig. 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: HerdCommandInvokerTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteWithExceptionAndGetJobEntityWithSecurityException()
{
    // Mock dependencies.
    CommandConfig config = mock(CommandConfig.class);
    JobEntity jobEntity = mock(JobEntity.class);
    ExecuteAsyncJobCmd command = new ExecuteAsyncJobCmd(jobEntity);
    doThrow(SecurityException.class).when(jobEntity).getId();

    // Try to call the method under test.
    try
    {
        herdCommandInvoker.execute(config, command);
        fail();
    }
    catch (IllegalStateException e)
    {
        assertEquals(SecurityException.class.getName(), e.getMessage());
    }
}
 
Example #2
Source File: HerdCommandInvokerTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecuteWithExceptionAndGetJobEntityWithNoSuchFieldException()
{
    // Mock dependencies.
    CommandConfig config = mock(CommandConfig.class);
    JobEntity jobEntity = mock(JobEntity.class);
    ExecuteAsyncJobCmd command = new ExecuteAsyncJobCmd(jobEntity);
    doThrow(NoSuchFieldException.class).when(jobEntity).getId();

    // Try to call the method under test.
    try
    {
        herdCommandInvoker.execute(config, command);
        fail();
    }
    catch (IllegalStateException e)
    {
        assertEquals(NoSuchFieldException.class.getName(), e.getMessage());
    }
}
 
Example #3
Source File: SpringTransactionInterceptor.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T execute(final CommandConfig config, final Command<T> command) {
    LOGGER.debug("Running command with propagation {}", config.getTransactionPropagation());

    TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
    transactionTemplate.setPropagationBehavior(getPropagation(config));

    T result = transactionTemplate.execute(new TransactionCallback<T>() {
        @Override
        public T doInTransaction(TransactionStatus status) {
            return next.execute(config, command);
        }
    });

    return result;
}
 
Example #4
Source File: SpringTransactionInterceptor.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
private int getPropagation(CommandConfig config) {
  switch (config.getTransactionPropagation()) {
  case NOT_SUPPORTED:
    return TransactionTemplate.PROPAGATION_NOT_SUPPORTED;
  case REQUIRED:
    return TransactionTemplate.PROPAGATION_REQUIRED;
  case REQUIRES_NEW:
    return TransactionTemplate.PROPAGATION_REQUIRES_NEW;
  default:
    throw new ActivitiIllegalArgumentException("Unsupported transaction propagation: " + config.getTransactionPropagation());
  }
}
 
Example #5
Source File: HerdCommandInvokerTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test(expected = CannotCreateTransactionException.class)
public void testExecuteWithExceptionAndGetCreateTransactionException()
{
    // Mock dependencies.
    CommandConfig config = mock(CommandConfig.class);
    ExecuteAsyncJobCmd command = mock(ExecuteAsyncJobCmd.class);
    doThrow(CannotCreateTransactionException.class).when(command).execute(any());
    herdCommandInvoker.execute(config, command);
}
 
Example #6
Source File: FailedJobListener.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(CommandContext commandContext) {
    CommandConfig commandConfig = commandExecutor.getDefaultConfig().transactionRequiresNew();
    FailedJobCommandFactory failedJobCommandFactory = commandContext.getFailedJobCommandFactory();
    Command<Object> cmd = failedJobCommandFactory.getCommand(jobId, exception);

    LOGGER.trace("Using FailedJobCommandFactory '{}' and command of type '{}'", failedJobCommandFactory.getClass(), cmd.getClass());
    commandExecutor.execute(commandConfig, cmd);
}
 
Example #7
Source File: ManagementServiceImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T executeCommand(CommandConfig config, Command<T> command) {
    if (config == null) {
        throw new ActivitiIllegalArgumentException("The config is null");
    }
    if (command == null) {
        throw new ActivitiIllegalArgumentException("The command is null");
    }
    return commandExecutor.execute(config, command);
}
 
Example #8
Source File: AsyncJobUtil.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public static void handleFailedJob(final JobEntity job, final Throwable exception, final CommandExecutor commandExecutor) {
    commandExecutor.execute(new Command<Void>() {

        @Override
        public Void execute(CommandContext commandContext) {
            CommandConfig commandConfig = commandExecutor.getDefaultConfig().transactionRequiresNew();
            FailedJobCommandFactory failedJobCommandFactory = commandContext.getFailedJobCommandFactory();
            Command<Object> cmd = failedJobCommandFactory.getCommand(job.getId(), exception);

            LOGGER.trace("Using FailedJobCommandFactory '{}' and command of type '{}'", failedJobCommandFactory.getClass(), cmd.getClass());
            commandExecutor.execute(commandConfig, cmd);

            // Dispatch an event, indicating job execution failed in a try-catch block, to prevent the original
            // exception to be swallowed
            if (commandContext.getEventDispatcher().isEnabled()) {
                try {
                    commandContext.getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityExceptionEvent(
                            FlowableEngineEventType.JOB_EXECUTION_FAILURE, job, exception));
                } catch (Throwable ignore) {
                    LOGGER.warn("Exception occurred while dispatching job failure event, ignoring.", ignore);
                }
            }

            return null;
        }

    });
    
    unlockJobIsNeeded(job, commandExecutor);
}
 
Example #9
Source File: SpringTransactionInterceptor.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private int getPropagation(CommandConfig config) {
    switch (config.getTransactionPropagation()) {
    case NOT_SUPPORTED:
        return TransactionTemplate.PROPAGATION_NOT_SUPPORTED;
    case REQUIRED:
        return TransactionTemplate.PROPAGATION_REQUIRED;
    case REQUIRES_NEW:
        return TransactionTemplate.PROPAGATION_REQUIRES_NEW;
    default:
        throw new ActivitiIllegalArgumentException("Unsupported transaction propagation: " + config.getTransactionPropagation());
    }
}
 
Example #10
Source File: RetryInterceptorTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
public void testRetryInterceptor() {
    RetryInterceptor retryInterceptor = new RetryInterceptor();
    retryInterceptor.setNext(new CommandInvoker());
    try {
        retryInterceptor.execute(new CommandConfig(), new CommandThrowingOptimisticLockingException());
        fail("ActivitiException expected.");
    } catch (ActivitiException e) {
        assertTrue(e.getMessage().contains(retryInterceptor.getNumOfRetries() + " retries failed"));
    }
}
 
Example #11
Source File: TotalExecutionTimeCommandInterceptor.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public <T> T execute(CommandConfig config, Command<T> command) {
    ProfileSession currentProfileSession = activitiProfiler.getCurrentProfileSession();

    if (currentProfileSession != null) {

        String className = command.getClass().getName();
        CommandExecutionResult commandExecutionResult = new CommandExecutionResult();
        currentProfileSession.setCurrentCommandExecution(commandExecutionResult);

        commandExecutionResult.setCommandFqn(className);

        long start = System.currentTimeMillis();
        T result = next.execute(config, command);
        long end = System.currentTimeMillis();
        long totalTime = end - start;
        commandExecutionResult.setTotalTimeInMs(totalTime);

        currentProfileSession.addCommandExecution(className, commandExecutionResult);
        currentProfileSession.clearCurrentCommandExecution();

        return result;

    } else {
        return next.execute(config, command);
    }

}
 
Example #12
Source File: FailedJobListener.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Override
public void closeFailure(CommandContext commandContext) {
  if (commandContext.getEventDispatcher().isEnabled()) {
    commandContext.getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityExceptionEvent(
      ActivitiEventType.JOB_EXECUTION_FAILURE, job, commandContext.getException()));
  }
  
  CommandConfig commandConfig = commandExecutor.getDefaultConfig().transactionRequiresNew();
  FailedJobCommandFactory failedJobCommandFactory = commandContext.getFailedJobCommandFactory();
  Command<Object> cmd = failedJobCommandFactory.getCommand(job.getId(), commandContext.getException());

  log.trace("Using FailedJobCommandFactory '" + failedJobCommandFactory.getClass() + "' and command of type '" + cmd.getClass() + "'");
  commandExecutor.execute(commandConfig, cmd);
}
 
Example #13
Source File: DbSchemaDrop.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().dbSchemaDrop();
      return null;
    }
  });
}
 
Example #14
Source File: SpringTransactionInterceptor.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public <T> T execute(final CommandConfig config, final Command<T> command) {
  LOGGER.debug("Running command with propagation {}", config.getTransactionPropagation());

  TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
  transactionTemplate.setPropagationBehavior(getPropagation(config));

  T result = transactionTemplate.execute(new TransactionCallback<T>() {
    public T doInTransaction(TransactionStatus status) {
      return next.execute(config, command);
    }
  });

  return result;
}
 
Example #15
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 #16
Source File: ManagementServiceImpl.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public <T> T executeCommand(CommandConfig config, Command<T> command) {
  if (config == null) {
    throw new ActivitiIllegalArgumentException("The config is null");
  }
  if (command == null) {
    throw new ActivitiIllegalArgumentException("The command is null");
  }
  return commandExecutor.execute(config, command);
}
 
Example #17
Source File: ManagementServiceImpl.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public String databaseSchemaUpgrade(final Connection connection, final String catalog, final String schema) {
  CommandConfig config = commandExecutor.getDefaultConfig().transactionNotSupported();
  return commandExecutor.execute(config, new Command<String>() {
    public String execute(CommandContext commandContext) {
      DbSqlSessionFactory dbSqlSessionFactory = (DbSqlSessionFactory) commandContext.getSessionFactories().get(DbSqlSession.class);
      DbSqlSession dbSqlSession = new DbSqlSession(dbSqlSessionFactory, commandContext.getEntityCache(), connection, catalog, schema);
      commandContext.getSessions().put(DbSqlSession.class, dbSqlSession);
      return dbSqlSession.dbSchemaUpdate();
    }
  });
}
 
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.getSession(DbSqlSession.class);
        session.dbSchemaDrop();
        session.dbSchemaCreate();
        return null;
      }
    });

    Assert.fail(outputMessage.toString());

  } else {
    log.info("database was clean");
  }
}
 
Example #19
Source File: ExecuteAsyncRunnable.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected void handleFailedJob(final Throwable exception) {
  processEngineConfiguration.getCommandExecutor().execute(new Command<Void>() {

    @Override
    public Void execute(CommandContext commandContext) {
      if (job.getProcessDefinitionId() != null && Activiti5Util.isActiviti5ProcessDefinitionId(commandContext, job.getProcessDefinitionId())) {
        Activiti5CompatibilityHandler activiti5CompatibilityHandler = Activiti5Util.getActiviti5CompatibilityHandler(); 
        activiti5CompatibilityHandler.handleFailedJob(job, exception);
        return null;
      }
      
      CommandConfig commandConfig = processEngineConfiguration.getCommandExecutor().getDefaultConfig().transactionRequiresNew();
      FailedJobCommandFactory failedJobCommandFactory = commandContext.getFailedJobCommandFactory();
      Command<Object> cmd = failedJobCommandFactory.getCommand(job.getId(), exception);

      log.trace("Using FailedJobCommandFactory '" + failedJobCommandFactory.getClass() + "' and command of type '" + cmd.getClass() + "'");
      processEngineConfiguration.getCommandExecutor().execute(commandConfig, cmd);

      // Dispatch an event, indicating job execution failed in a
      // try-catch block, to prevent the original exception to be swallowed
      if (commandContext.getEventDispatcher().isEnabled()) {
        try {
          commandContext.getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityExceptionEvent(ActivitiEventType.JOB_EXECUTION_FAILURE, job, exception));
        } catch (Throwable ignore) {
          log.warn("Exception occurred while dispatching job failure event, ignoring.", ignore);
        }
      }

      return null;
    }

  });
}
 
Example #20
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 #21
Source File: DbIdGenerator.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
public void setCommandConfig(CommandConfig commandConfig) {
  this.commandConfig = commandConfig;
}
 
Example #22
Source File: SpringProcessEngineConfiguration.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
@Override
public void initDefaultCommandConfig() {
  if (defaultCommandConfig == null) {
    defaultCommandConfig = new CommandConfig().setContextReusePossible(true);
  }
}
 
Example #23
Source File: HerdCommandInvoker.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T execute(CommandConfig config, Command<T> command)
{
    LOGGER.debug("command=\"{}\"", command.getClass().getName());
    try
    {
        // Perform the normal execution.
        return super.execute(config, command);
    }
    catch (Exception e)
    {
        LOGGER.warn(String.format("HerdCommandInvoker caught an exception."), e);

        /*
         * If the exception is unable to create transaction due to JDBC connection issue,
         * throw out the exception, then let the Activiti engine take care of retries
         */
        if (StringUtils.containsIgnoreCase(ExceptionUtils.getMessage(e), CANNOT_CREATE_TRANSACTION_EXCEPTION))
        {
            LOGGER.warn(String.format("HerdCommandInvoker caught a CannotCreateTransactionException."), e);
            throw e;
        }

        /*
         * Attempt to handle exception based on the command.
         * If we bubble the exception up here, the transaction will be rolled back and all variables which were not committed will not be persisted.
         * The problem with swallowing the exception, however, is that the exception message is not persisted automatically. To get around it, we must save
         * the exception message and stacktrace into a JobEntity which is associated with the current execution.
         */

        if (command instanceof ExecuteAsyncJobCmd)
        {
            /*
             * ExecuteAsyncJobCmd is executed when a task is asynchronous.
             * Save the exception information in the command's JobEntity
             */
            ExecuteAsyncJobCmd executeAsyncJobCmd = (ExecuteAsyncJobCmd) command;
            JobEntity jobEntity = getJobEntity(executeAsyncJobCmd);
            jobEntity.setExceptionMessage(ExceptionUtils.getMessage(e));
            jobEntity.setExceptionStacktrace(ExceptionUtils.getStackTrace(e));
            return null;
        }
        else
        {
            /*
             * We do not know how to handle any other commands, so just bubble it up and let Activiti's default mechanism kick in.
             */
            throw e;
        }
    }
}
 
Example #24
Source File: DbIdGenerator.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public void setCommandConfig(CommandConfig commandConfig) {
    this.commandConfig = commandConfig;
}
 
Example #25
Source File: DbIdGenerator.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public CommandConfig getCommandConfig() {
    return commandConfig;
}
 
Example #26
Source File: CommandExecutorImpl.java    From activiti6-boot2 with Apache License 2.0 4 votes vote down vote up
public CommandExecutorImpl(CommandConfig defaultConfig, CommandInterceptor first) {
  this.defaultConfig = defaultConfig;
  this.first = first;
}
 
Example #27
Source File: ProcessEngineConfigurationImpl.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public void setSchemaCommandConfig(CommandConfig schemaCommandConfig) {
    this.schemaCommandConfig = schemaCommandConfig;
}
 
Example #28
Source File: ProcessEngineConfigurationImpl.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public CommandConfig getSchemaCommandConfig() {
    return schemaCommandConfig;
}
 
Example #29
Source File: ProcessEngineConfigurationImpl.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public void setDefaultCommandConfig(CommandConfig defaultCommandConfig) {
    this.defaultCommandConfig = defaultCommandConfig;
}
 
Example #30
Source File: ProcessEngineConfigurationImpl.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
public CommandConfig getDefaultCommandConfig() {
    return defaultCommandConfig;
}