Java源码示例:org.activiti.engine.impl.interceptor.Command

示例1
@Bean
CommandLineRunner customMybatisXmlMapper(final ManagementService managementService) {
    return new CommandLineRunner() {
        @Override
        public void run(String... args) throws Exception {
            String processDefinitionDeploymentId = managementService.executeCommand(new Command<String>() {
                @Override
                public String execute(CommandContext commandContext) {
                    return (String) commandContext
                            .getDbSqlSession()
                            .selectOne("selectProcessDefinitionDeploymentIdByKey", "waiter");
                }
            });

            logger.info("Process definition deployment id = {}", processDefinitionDeploymentId);
        }
    };
}
 
示例2
public void run() {
  
  if (job == null) {
    job = processEngineConfiguration.getCommandExecutor().execute(new Command<JobEntity>() {
      @Override
      public JobEntity execute(CommandContext commandContext) {
        return commandContext.getJobEntityManager().findById(jobId);
      }
    });
  }
  
  if (isHandledByActiviti5Engine()) {
    return;
  }
  
  boolean lockNotNeededOrSuccess = lockJobIfNeeded();

  if (lockNotNeededOrSuccess) {
    executeJob();
    unlockJobIfNeeded();
  }

}
 
示例3
public ProcessDefinitionInfoCacheObject get(final String processDefinitionId) {
  ProcessDefinitionInfoCacheObject infoCacheObject = null;
  Command<ProcessDefinitionInfoCacheObject> cacheCommand = new Command<ProcessDefinitionInfoCacheObject>() {

    @Override
    public ProcessDefinitionInfoCacheObject execute(CommandContext commandContext) {
      return retrieveProcessDefinitionInfoCacheObject(processDefinitionId, commandContext);
    }
  };
  
  if (Context.getCommandContext() != null) {
    infoCacheObject = retrieveProcessDefinitionInfoCacheObject(processDefinitionId, Context.getCommandContext());
  } else {
    infoCacheObject = commandExecutor.execute(cacheCommand);
  } 
  
  return infoCacheObject;
}
 
示例4
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;

    }
  });

}
 
示例5
private void createJobWithoutExceptionStacktrace() {
  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);
      
      jobEntity.setExceptionMessage("I'm supposed to fail");
      
      commandContext.getJobEntityManager().insert(jobEntity);

      assertNotNull(jobEntity.getId());

      return null;

    }
  });

}
 
示例6
public void testMetaData() {
  ((ProcessEngineImpl) processEngine).getProcessEngineConfiguration().getCommandExecutor().execute(new Command<Object>() {
    public Object execute(CommandContext commandContext) {
      // PRINT THE TABLE NAMES TO CHECK IF WE CAN USE METADATA INSTEAD
      // THIS IS INTENDED FOR TEST THAT SHOULD RUN ON OUR QA
      // INFRASTRUCTURE TO SEE IF METADATA
      // CAN BE USED INSTEAD OF PERFORMING A QUERY THAT MIGHT FAIL
      try {
        SqlSession sqlSession = commandContext.getDbSqlSession().getSqlSession();
        ResultSet tables = sqlSession.getConnection().getMetaData().getTables(null, null, null, null);
        while (tables.next()) {
          ResultSetMetaData resultSetMetaData = tables.getMetaData();
          int columnCount = resultSetMetaData.getColumnCount();
          for (int i = 1; i <= columnCount; i++) {
            log.info("result set column {}|{}|{}|{}", i, resultSetMetaData.getColumnName(i), resultSetMetaData.getColumnLabel(i), tables.getString(i));
          }
          log.info("-------------------------------------------------------");
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      return null;
    }
  });
}
 
示例7
private List<String> getExecutionIdsForMessageEventSubscription(final String messageName) {
  return managementService.executeCommand(new Command<List<String>>() {
    public List<String> execute(CommandContext commandContext) {
      EventSubscriptionQueryImpl query = new EventSubscriptionQueryImpl(commandContext);
      query.eventType("message");
      query.eventName(messageName);
      query.orderByCreated().desc();
      List<EventSubscriptionEntity> eventSubscriptions = query.list();
      
      List<String> executionIds = new ArrayList<String>();
      for (EventSubscriptionEntity eventSubscription : eventSubscriptions) {
        executionIds.add(eventSubscription.getExecutionId());
      }
      return executionIds;
    }
  });
}
 
示例8
private List<String> getExecutionIdsForMessageEventSubscription(final String messageName) {
  return managementService.executeCommand(new Command<List<String>>() {
    public List<String> execute(CommandContext commandContext) {
      EventSubscriptionQueryImpl query = new EventSubscriptionQueryImpl(commandContext);
      query.eventType("message");
      query.eventName(messageName);
      query.tenantId(TENANT_ID);
      query.orderByCreated().desc();
      List<EventSubscriptionEntity> eventSubscriptions = query.list();
      
      List<String> executionIds = new ArrayList<String>();
      for (EventSubscriptionEntity eventSubscription : eventSubscriptions) {
        executionIds.add(eventSubscription.getExecutionId());
      }
      return executionIds;
    }
  });
}
 
示例9
private List<EventSubscriptionEntity> getAllEventSubscriptions() {
  return managementService.executeCommand(new Command<List<EventSubscriptionEntity>>() {
    public List<EventSubscriptionEntity> execute(CommandContext commandContext) {
      EventSubscriptionQueryImpl query = new EventSubscriptionQueryImpl(commandContext);
      query.tenantId(TENANT_ID);
      query.orderByCreated().desc();
      
      List<EventSubscriptionEntity> eventSubscriptionEntities = query.list();
      for (EventSubscriptionEntity entity : eventSubscriptionEntities) {
        assertEquals("message", entity.getEventType());
        assertNotNull(entity.getProcessDefinitionId());
      }
      return eventSubscriptionEntities;
    }
  });
}
 
示例10
public void testSelectTaskList() {
  // Create test data
  for (int i = 0; i < 5; i++) {
    createTask(i + "", null, null, 0);
  }

  List<CustomTask> tasks = managementService.executeCommand(new Command<List<CustomTask>>() {

    @SuppressWarnings("unchecked")
    @Override
    public List<CustomTask> execute(CommandContext commandContext) {
      return (List<CustomTask>) commandContext.getDbSqlSession().selectList("selectCustomTaskList");
    }
  });

  assertEquals(5, tasks.size());

  // Cleanup
  deleteCustomTasks(tasks);
}
 
示例11
private List<String> getExecutionIdsForMessageEventSubscription(final String messageName) {
  return managementService.executeCommand(new Command<List<String>>() {
    public List<String> execute(CommandContext commandContext) {
      EventSubscriptionQueryImpl query = new EventSubscriptionQueryImpl(commandContext);
      query.eventType("message");
      query.eventName(messageName);
      query.orderByCreated().desc();
      List<EventSubscriptionEntity> eventSubscriptions = query.list();
      
      List<String> executionIds = new ArrayList<String>();
      for (EventSubscriptionEntity eventSubscription : eventSubscriptions) {
        executionIds.add(eventSubscription.getExecutionId());
      }
      return executionIds;
    }
  });
}
 
示例12
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;

        }
    });

}
 
示例13
public void testJobCommandsWithMessage() {
    ProcessEngineConfigurationImpl activiti5ProcessEngineConfig = (ProcessEngineConfigurationImpl) processEngineConfiguration.getFlowable5CompatibilityHandler().getRawProcessConfiguration();
    CommandExecutor commandExecutor = activiti5ProcessEngineConfig.getCommandExecutor();

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

        public String execute(CommandContext commandContext) {
            JobEntity message = createTweetMessage("i'm coding a test");
            commandContext.getJobEntityManager().send(message);
            return message.getId();
        }
    });

    Job job = managementService.createJobQuery().singleResult();
    assertNotNull(job);
    assertEquals(jobId, job.getId());

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

    activiti5ProcessEngineConfig.getManagementService().executeJob(job.getId());

    assertEquals("i'm coding a test", tweetHandler.getMessages().get(0));
    assertEquals(1, tweetHandler.getMessages().size());
}
 
示例14
public void testSelectTaskList() {
    // Create test data
    for (int i = 0; i < 5; i++) {
        createTask(String.valueOf(i), null, null, 0);
    }

    org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl activiti5ProcessEngineConfig = (org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl) processEngineConfiguration.getFlowable5CompatibilityHandler()
            .getRawProcessConfiguration();

    List<CustomTask> tasks = activiti5ProcessEngineConfig.getManagementService().executeCommand(new Command<List<CustomTask>>() {

        @SuppressWarnings("unchecked")
        @Override
        public List<CustomTask> execute(CommandContext commandContext) {
            return (List<CustomTask>) commandContext.getDbSqlSession().selectList("selectCustomTaskList");
        }
    });

    assertEquals(5, tasks.size());

    // Cleanup
    deleteCustomTasks(tasks);
}
 
示例15
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());
}
 
示例16
@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;
}
 
示例17
@Override
public ProcessDefinitionCacheEntry resolveProcessDefinition(final ProcessDefinition processDefinition) {
    try {
        final ProcessEngineConfigurationImpl processEngineConfig = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration();
        ProcessDefinitionCacheEntry cacheEntry = processEngineConfig.getCommandExecutor().execute(new Command<ProcessDefinitionCacheEntry>() {

            @Override
            public ProcessDefinitionCacheEntry execute(CommandContext commandContext) {
                return commandContext.getProcessEngineConfiguration().getDeploymentManager().resolveProcessDefinition(processDefinition);
            }
        });

        return cacheEntry;

    } catch (org.activiti.engine.ActivitiException e) {
        handleActivitiException(e);
        return null;
    }
}
 
示例18
@Override
public void signalEventReceived(final SignalEventSubscriptionEntity signalEventSubscriptionEntity, final Object payload, final boolean async) {
    final ProcessEngineConfigurationImpl processEngineConfig = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration();
    processEngineConfig.getCommandExecutor().execute(new Command<Void>() {

        @Override
        public Void execute(CommandContext commandContext) {
            org.activiti.engine.impl.persistence.entity.SignalEventSubscriptionEntity activiti5SignalEvent = new org.activiti.engine.impl.persistence.entity.SignalEventSubscriptionEntity();
            activiti5SignalEvent.setId(signalEventSubscriptionEntity.getId());
            activiti5SignalEvent.setExecutionId(signalEventSubscriptionEntity.getExecutionId());
            activiti5SignalEvent.setActivityId(signalEventSubscriptionEntity.getActivityId());
            activiti5SignalEvent.setEventName(signalEventSubscriptionEntity.getEventName());
            activiti5SignalEvent.setEventType(signalEventSubscriptionEntity.getEventType());
            activiti5SignalEvent.setConfiguration(signalEventSubscriptionEntity.getConfiguration());
            activiti5SignalEvent.setProcessDefinitionId(signalEventSubscriptionEntity.getProcessDefinitionId());
            activiti5SignalEvent.setProcessInstanceId(signalEventSubscriptionEntity.getProcessInstanceId());
            activiti5SignalEvent.setTenantId(signalEventSubscriptionEntity.getTenantId());
            activiti5SignalEvent.setRevision(signalEventSubscriptionEntity.getRevision());
            activiti5SignalEvent.eventReceived(payload, async);
            return null;
        }
    });

}
 
示例19
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;
}
 
示例20
/**
 * 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");
  }
}
 
示例21
@Test
public void executeCustomMybatisXmlQuery() throws Exception {
    AnnotationConfigApplicationContext applicationContext = this.context(Application.class);
    ManagementService managementService = applicationContext.getBean(ManagementService.class);
    String processDefinitionDeploymentId = managementService.executeCommand(new Command<String>() {
        @Override
        public String execute(CommandContext commandContext) {
            return (String) commandContext.getDbSqlSession().selectOne("selectProcessDefinitionDeploymentIdByKey", "waiter");
        }
    });
    Assert.assertNotNull("the processDefinitionDeploymentId should not be null!", processDefinitionDeploymentId);
}
 
示例22
/**
 * 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");
  }
}
 
示例23
protected boolean isHandledByActiviti5Engine() {
  boolean isActiviti5ProcessDefinition = Activiti5Util.isActiviti5ProcessDefinitionId(processEngineConfiguration, job.getProcessDefinitionId());
  if (isActiviti5ProcessDefinition) {
    return processEngineConfiguration.getCommandExecutor().execute(new Command<Boolean>() {
      @Override
      public Boolean execute(CommandContext commandContext) {
        commandContext.getProcessEngineConfiguration().getActiviti5CompatibilityHandler().executeJobWithLockAndRetry(job);
        return true;
      }
    });
  }
  return false;
}
 
示例24
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;
    }

  });
}
 
示例25
public DeploymentBuilder createDeployment() {
  return commandExecutor.execute(new Command<DeploymentBuilder>() {
    @Override
    public DeploymentBuilder execute(CommandContext commandContext) {
      return new DeploymentBuilderImpl(RepositoryServiceImpl.this);
    }
  });
}
 
示例26
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();
    }
  });
}
 
示例27
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);
}
 
示例28
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;
    }
  });
}
 
示例29
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;
    }
  });
}
 
示例30
@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);
}