ProcessEngineEndpoint

ProcessEngineEndpoint

  • 目录
    • 概述
      • 需求:
    • 设计思路
    • 实现思路分析
      • 1.AsyncPropertyValidator
      • 2.AbstractProcessEngineAutoConfiguration
      • 3.AbstractProcessEngineAutoConfiguration
      • 4.ActivitiMethodSecurityAutoConfiguration
      • 5.ActivitiProperties
    • ProcessEngineAutoConfiguration
    • ApplicationDeployedEventProducer:
  • 参考资料和推荐阅读

Survive by day and develop by night.
talk for import biz , show your perfect code,full busy,skip hardness,make a better result,wait for change,challenge Survive.
happy for hardess to solve denpendies.

目录

在这里插入图片描述

概述

ProcessEngineEndpoint的是一个非常常见的需求。

需求:

设计思路

public class ProcessEngineEndpoint {

    private final ProcessEngine processEngine;

    public ProcessEngineEndpoint(ProcessEngine processEngine) {
        this.processEngine = processEngine;
    }

    @ReadOperation
    public Map<String, Object> invoke() {

        Map<String, Object> metrics = new HashMap<String, Object>();

        // Process definitions
        metrics.put("processDefinitionCount",
                    processEngine.getRepositoryService().createProcessDefinitionQuery().count());

        // List of all process definitions
        List<ProcessDefinition> processDefinitions = processEngine.getRepositoryService().createProcessDefinitionQuery().orderByProcessDefinitionKey().asc().list();
        List<String> processDefinitionKeys = new ArrayList<String>();
        for (ProcessDefinition processDefinition : processDefinitions) {
            processDefinitionKeys.add(processDefinition.getKey() + " (v" + processDefinition.getVersion() + ")");
        }
        metrics.put("deployedProcessDefinitions",
                    processDefinitionKeys);

        // Process instances
        Map<String, Object> processInstanceCountMap = new HashMap<String, Object>();
        metrics.put("runningProcessInstanceCount",
                    processInstanceCountMap);
        for (ProcessDefinition processDefinition : processDefinitions) {
            processInstanceCountMap.put(processDefinition.getKey() + " (v" + processDefinition.getVersion() + ")",
                                        processEngine.getRuntimeService().createProcessInstanceQuery().processDefinitionId(processDefinition.getId()).count());
        }
        Map<String, Object> completedProcessInstanceCountMap = new HashMap<String, Object>();
        metrics.put("completedProcessInstanceCount",
                    completedProcessInstanceCountMap);
        for (ProcessDefinition processDefinition : processDefinitions) {
            completedProcessInstanceCountMap.put(processDefinition.getKey() + " (v" + processDefinition.getVersion() + ")",
                                                 processEngine.getHistoryService().createHistoricProcessInstanceQuery().finished().processDefinitionId(processDefinition.getId()).count());
        }

        // Open tasks
        metrics.put("openTaskCount",
                    processEngine.getTaskService().createTaskQuery().count());
        metrics.put("completedTaskCount",
                    processEngine.getHistoryService().createHistoricTaskInstanceQuery().finished().count());

        // Tasks completed today
        metrics.put("completedTaskCountToday",
                    processEngine.getHistoryService().createHistoricTaskInstanceQuery().finished().taskCompletedAfter(
                            new Date(System.currentTimeMillis() - secondsForDays(1))).count());

        // Process steps
        metrics.put("completedActivities",
                    processEngine.getHistoryService().createHistoricActivityInstanceQuery().finished().count());

        // Process definition cache
        DeploymentCache<ProcessDefinitionCacheEntry> deploymentCache = ((ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration()).getProcessDefinitionCache();
        if (deploymentCache instanceof DefaultDeploymentCache) {
            metrics.put("cachedProcessDefinitionCount",
                        ((DefaultDeploymentCache) deploymentCache).size());
        }
        return metrics;
    }

    private long secondsForDays(int days) {
        int hour = 60 * 60 * 1000;
        int day = 24 * hour;
        return days * day;
    }
}

实现思路分析

1.AsyncPropertyValidator

public class AsyncPropertyValidator extends ProcessLevelValidator {

    @Override
    protected void executeValidation(BpmnModel bpmnModel, Process process, List<ValidationError> errors) {
        validateFlowElementsInContainer(process, errors, process);
    }

    protected void validateFlowElementsInContainer(FlowElementsContainer container, List<ValidationError> errors, Process process) {
        for (FlowElement flowElement : container.getFlowElements()) {
            if (flowElement instanceof FlowElementsContainer) {
                FlowElementsContainer subProcess = (FlowElementsContainer) flowElement;
                validateFlowElementsInContainer(subProcess, errors, process);
            }

            if ((flowElement instanceof FlowNode) && ((FlowNode) flowElement).isAsynchronous()) {
                addWarning(errors, Problems.FLOW_ELEMENT_ASYNC_NOT_AVAILABLE, process , flowElement, "Async property is not available when asyncExecutor is disabled.");
            }

            if ((flowElement instanceof Event)) {
                ((Event) flowElement).getEventDefinitions().stream().forEach(event -> {
                    if (event instanceof TimerEventDefinition) {
                        addWarning(errors, Problems.EVENT_TIMER_ASYNC_NOT_AVAILABLE, process, flowElement, "Timer event is not available when asyncExecutor is disabled.");
                    } else if ((event instanceof SignalEventDefinition) && ((SignalEventDefinition) event).isAsync() ) {
                        addWarning(errors, Problems.SIGNAL_ASYNC_NOT_AVAILABLE, process, flowElement, "Async property is not available when asyncExecutor is disabled.");
                    }
                });
            }
        }
    }
}

2.AbstractProcessEngineAutoConfiguration

3.AbstractProcessEngineAutoConfiguration

public abstract class AbstractProcessEngineAutoConfiguration
        extends AbstractProcessEngineConfiguration {

  @Bean
  public SpringAsyncExecutor springAsyncExecutor(TaskExecutor applicationTaskExecutor) {
    return new SpringAsyncExecutor(applicationTaskExecutor, springRejectedJobsHandler());
  }

  @Bean
  public SpringRejectedJobsHandler springRejectedJobsHandler() {
    return new SpringCallerRunsRejectedJobsHandler();
  }

  protected Set<Class<?>> getCustomMybatisMapperClasses(List<String> customMyBatisMappers) {
    Set<Class<?>> mybatisMappers = new HashSet<>();
    for (String customMybatisMapperClassName : customMyBatisMappers) {
      try {
        Class customMybatisClass = Class.forName(customMybatisMapperClassName);
        mybatisMappers.add(customMybatisClass);
      } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException("Class " + customMybatisMapperClassName + " has not been found.", e);
      }
    }
    return mybatisMappers;
  }

  @Bean
  public ProcessEngineFactoryBean processEngine(SpringProcessEngineConfiguration configuration) {
    return super.springProcessEngineBean(configuration);
  }

4.ActivitiMethodSecurityAutoConfiguration

@Configuration
@ConditionalOnProperty(name = "spring.activiti.security.enabled", matchIfMissing = true)
@ConditionalOnClass(GlobalMethodSecurityConfiguration.class)
@ConditionalOnMissingBean(annotation = EnableGlobalMethodSecurity.class)
public class ActivitiMethodSecurityAutoConfiguration {

    @Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true,
                                securedEnabled = true,
                                jsr250Enabled = true)
    public static class ActivitiMethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {

    }
}

5.ActivitiProperties

 private boolean checkProcessDefinitions = true;
  private boolean asyncExecutorActivate = true;
  private String deploymentName = "SpringAutoDeployment";
  private String mailServerHost = "localhost";
  private int mailServerPort = 1025;
  private String mailServerUserName;
  private String mailServerPassword;
  private String mailServerDefaultFrom;
  private boolean mailServerUseSsl;
  private boolean mailServerUseTls;
  private String databaseSchemaUpdate = "true";
  private String databaseSchema;
  private boolean dbHistoryUsed = false;
  private HistoryLevel historyLevel = HistoryLevel.NONE;
  private String processDefinitionLocationPrefix = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "**/processes/";
  private List<String> processDefinitionLocationSuffixes = asList("**.bpmn20.xml", "**.bpmn");
  private List<String> customMybatisMappers;
  private List<String> customMybatisXMLMappers;
  private boolean useStrongUuids = true;
  private boolean copyVariablesToLocalForTasks = true;
  private String deploymentMode = "default";
  private boolean serializePOJOsInVariablesToJson = true;
  private String javaClassFieldForJackson = JsonTypeInfo.Id.CLASS.getDefaultPropertyName();

ProcessEngineAutoConfiguration

@Bean
    @ConditionalOnMissingBean
    public SpringProcessEngineConfiguration springProcessEngineConfiguration(
            DataSource dataSource,
            PlatformTransactionManager transactionManager,
            SpringAsyncExecutor springAsyncExecutor,
            ActivitiProperties activitiProperties,
            ResourceFinder resourceFinder,
            List<ResourceFinderDescriptor> resourceFinderDescriptors,
            ApplicationUpgradeContextService applicationUpgradeContextService,
            @Autowired(required = false) List<ProcessEngineConfigurationConfigurer> processEngineConfigurationConfigurers,
            @Autowired(required = false) List<ProcessEngineConfigurator> processEngineConfigurators) throws IOException {

        SpringProcessEngineConfiguration conf = new SpringProcessEngineConfiguration(applicationUpgradeContextService);
        conf.setConfigurators(processEngineConfigurators);


        configureResources(resourceFinder, resourceFinderDescriptors, conf);

        conf.setDataSource(dataSource);
        conf.setTransactionManager(transactionManager);

        conf.setAsyncExecutor(springAsyncExecutor);
        conf.setDeploymentName(activitiProperties.getDeploymentName());
        conf.setDatabaseSchema(activitiProperties.getDatabaseSchema());
        conf.setDatabaseSchemaUpdate(activitiProperties.getDatabaseSchemaUpdate());
        conf.setDbHistoryUsed(activitiProperties.isDbHistoryUsed());
        conf.setAsyncExecutorActivate(activitiProperties.isAsyncExecutorActivate());
        addAsyncPropertyValidator(activitiProperties,
                conf);
        conf.setMailServerHost(activitiProperties.getMailServerHost());
        conf.setMailServerPort(activitiProperties.getMailServerPort());
        conf.setMailServerUsername(activitiProperties.getMailServerUserName());
        conf.setMailServerPassword(activitiProperties.getMailServerPassword());
        conf.setMailServerDefaultFrom(activitiProperties.getMailServerDefaultFrom());
        conf.setMailServerUseSSL(activitiProperties.isMailServerUseSsl());
        conf.setMailServerUseTLS(activitiProperties.isMailServerUseTls());

        if (userGroupManager != null) {
            conf.setUserGroupManager(userGroupManager);
        }

        conf.setHistoryLevel(activitiProperties.getHistoryLevel());
        conf.setCopyVariablesToLocalForTasks(activitiProperties.isCopyVariablesToLocalForTasks());
        conf.setSerializePOJOsInVariablesToJson(activitiProperties.isSerializePOJOsInVariablesToJson());
        conf.setJavaClassFieldForJackson(activitiProperties.getJavaClassFieldForJackson());

        if (activitiProperties.getCustomMybatisMappers() != null) {
            conf.setCustomMybatisMappers(getCustomMybatisMapperClasses(activitiProperties.getCustomMybatisMappers()));
        }

        if (activitiProperties.getCustomMybatisXMLMappers() != null) {
            conf.setCustomMybatisXMLMappers(new HashSet<>(activitiProperties.getCustomMybatisXMLMappers()));
        }

        if (activitiProperties.getCustomMybatisXMLMappers() != null) {
            conf.setCustomMybatisXMLMappers(new HashSet<>(activitiProperties.getCustomMybatisXMLMappers()));
        }

        if (activitiProperties.isUseStrongUuids()) {
            conf.setIdGenerator(new StrongUuidGenerator());
        }

        if (activitiProperties.getDeploymentMode() != null) {
            conf.setDeploymentMode(activitiProperties.getDeploymentMode());
        }

        if (processEngineConfigurationConfigurers != null) {
            for (ProcessEngineConfigurationConfigurer processEngineConfigurationConfigurer : processEngineConfigurationConfigurers) {
                processEngineConfigurationConfigurer.configure(conf);
            }
        }
        springAsyncExecutor.applyConfig(conf);
        return conf;
    }

ApplicationDeployedEventProducer:

 private RepositoryService repositoryService;
    private APIDeploymentConverter deploymentConverter;
    private List<ProcessRuntimeEventListener<ApplicationDeployedEvent>> listeners;
    private ApplicationEventPublisher eventPublisher;
    private static final String APPLICATION_DEPLOYMENT_NAME= "SpringAutoDeployment";

    public ApplicationDeployedEventProducer(RepositoryService repositoryService,
            APIDeploymentConverter deploymentConverter,
            List<ProcessRuntimeEventListener<ApplicationDeployedEvent>> listeners,
            ApplicationEventPublisher eventPublisher) {
        this.repositoryService = repositoryService;
        this.deploymentConverter = deploymentConverter;
        this.listeners = listeners;
        this.eventPublisher = eventPublisher;
    }

    @Override
    public void doStart() {
        List<ApplicationDeployedEvent> applicationDeployedEvents = getApplicationDeployedEvents();
        for (ProcessRuntimeEventListener<ApplicationDeployedEvent> listener : listeners) {
            applicationDeployedEvents.forEach(listener::onEvent);
        }
        if (!applicationDeployedEvents.isEmpty()) {
            eventPublisher.publishEvent(new ApplicationDeployedEvents(applicationDeployedEvents));
        }
    }

    private List<ApplicationDeployedEvent> getApplicationDeployedEvents() {
        List<Deployment> deployments = deploymentConverter.from(repositoryService
                        .createDeploymentQuery()
                        .deploymentName(APPLICATION_DEPLOYMENT_NAME)
                        .list());

        List<ApplicationDeployedEvent> applicationDeployedEvents = new ArrayList<>();
        for (Deployment deployment : deployments) {
            ApplicationDeployedEventImpl applicationDeployedEvent = new ApplicationDeployedEventImpl(deployment);
            applicationDeployedEvents.add(applicationDeployedEvent);
        }
        return applicationDeployedEvents;
    }

参考资料和推荐阅读

  1. 暂无

欢迎阅读,各位老铁,如果对你有帮助,点个赞加个关注呗!~

你可能感兴趣的:(【工作流】,java,开发语言)