Search in sources :

Example 26 with CommandContext

use of org.activiti.engine.impl.interceptor.CommandContext in project Activiti by Activiti.

the class BaseJPARestTestCase method assertAndEnsureCleanDb.

/** 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.getSession(DbSqlSession.class);
                session.dbSchemaDrop();
                session.dbSchemaCreate();
                return null;
            }
        });
        if (exception != null) {
            throw exception;
        } else {
            Assert.fail(outputMessage.toString());
        }
    } else {
        log.info("database was clean");
    }
}
Also used : CommandContext(org.activiti.engine.impl.interceptor.CommandContext) CommandExecutor(org.activiti.engine.impl.interceptor.CommandExecutor) DbSqlSession(org.activiti.engine.impl.db.DbSqlSession)

Example 27 with CommandContext

use of org.activiti.engine.impl.interceptor.CommandContext in project Activiti by Activiti.

the class BpmnDeployer method deploy.

public void deploy(DeploymentEntity deployment, Map<String, Object> deploymentSettings) {
    log.debug("Processing deployment {}", deployment.getName());
    List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
    Map<String, ResourceEntity> resources = deployment.getResources();
    Map<String, BpmnModel> bpmnModelMap = new HashMap<String, BpmnModel>();
    final ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
    for (String resourceName : resources.keySet()) {
        log.info("Processing resource {}", resourceName);
        if (isBpmnResource(resourceName)) {
            ResourceEntity resource = resources.get(resourceName);
            byte[] bytes = resource.getBytes();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            BpmnParse bpmnParse = bpmnParser.createParse().sourceInputStream(inputStream).setSourceSystemId(resourceName).deployment(deployment).name(resourceName);
            if (deploymentSettings != null) {
                // Schema validation if needed
                if (deploymentSettings.containsKey(DeploymentSettings.IS_BPMN20_XSD_VALIDATION_ENABLED)) {
                    bpmnParse.setValidateSchema((Boolean) deploymentSettings.get(DeploymentSettings.IS_BPMN20_XSD_VALIDATION_ENABLED));
                }
                // Process validation if needed
                if (deploymentSettings.containsKey(DeploymentSettings.IS_PROCESS_VALIDATION_ENABLED)) {
                    bpmnParse.setValidateProcess((Boolean) deploymentSettings.get(DeploymentSettings.IS_PROCESS_VALIDATION_ENABLED));
                }
            } else {
                // On redeploy, we assume it is validated at the first deploy
                bpmnParse.setValidateSchema(false);
                bpmnParse.setValidateProcess(false);
            }
            bpmnParse.execute();
            for (ProcessDefinitionEntity processDefinition : bpmnParse.getProcessDefinitions()) {
                processDefinition.setResourceName(resourceName);
                if (deployment.getTenantId() != null) {
                    // process definition inherits the tenant id
                    processDefinition.setTenantId(deployment.getTenantId());
                }
                String diagramResourceName = getDiagramResourceForProcess(resourceName, processDefinition.getKey(), resources);
                // time the process definition is added to the deployment-cache when diagram-generation has failed the first time.
                if (deployment.isNew()) {
                    if (processEngineConfiguration.isCreateDiagramOnDeploy() && diagramResourceName == null && processDefinition.isGraphicalNotationDefined()) {
                        try {
                            byte[] diagramBytes = IoUtil.readInputStream(processEngineConfiguration.getProcessDiagramGenerator().generateDiagram(bpmnParse.getBpmnModel(), "png", processEngineConfiguration.getActivityFontName(), processEngineConfiguration.getLabelFontName(), processEngineConfiguration.getAnnotationFontName(), processEngineConfiguration.getClassLoader()), null);
                            diagramResourceName = getProcessImageResourceName(resourceName, processDefinition.getKey(), "png");
                            createResource(diagramResourceName, diagramBytes, deployment);
                        } catch (Throwable t) {
                            // if anything goes wrong, we don't store the image (the process will still be executable).
                            log.warn("Error while generating process diagram, image will not be stored in repository", t);
                        }
                    }
                }
                processDefinition.setDiagramResourceName(diagramResourceName);
                processDefinitions.add(processDefinition);
                bpmnModelMap.put(processDefinition.getKey(), bpmnParse.getBpmnModel());
            }
        }
    }
    // check if there are process definitions with the same process key to prevent database unique index violation
    List<String> keyList = new ArrayList<String>();
    for (ProcessDefinitionEntity processDefinition : processDefinitions) {
        if (keyList.contains(processDefinition.getKey())) {
            throw new ActivitiException("The deployment contains process definitions with the same key '" + processDefinition.getKey() + "' (process id atrribute), this is not allowed");
        }
        keyList.add(processDefinition.getKey());
    }
    CommandContext commandContext = Context.getCommandContext();
    ProcessDefinitionEntityManager processDefinitionManager = commandContext.getProcessDefinitionEntityManager();
    DbSqlSession dbSqlSession = commandContext.getSession(DbSqlSession.class);
    for (ProcessDefinitionEntity processDefinition : processDefinitions) {
        List<TimerEntity> timers = new ArrayList<TimerEntity>();
        if (deployment.isNew()) {
            int processDefinitionVersion;
            ProcessDefinitionEntity latestProcessDefinition = null;
            if (processDefinition.getTenantId() != null && !ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) {
                latestProcessDefinition = processDefinitionManager.findLatestProcessDefinitionByKeyAndTenantId(processDefinition.getKey(), processDefinition.getTenantId());
            } else {
                latestProcessDefinition = processDefinitionManager.findLatestProcessDefinitionByKey(processDefinition.getKey());
            }
            if (latestProcessDefinition != null) {
                processDefinitionVersion = latestProcessDefinition.getVersion() + 1;
            } else {
                processDefinitionVersion = 1;
            }
            processDefinition.setVersion(processDefinitionVersion);
            processDefinition.setDeploymentId(deployment.getId());
            String nextId = idGenerator.getNextId();
            String processDefinitionId = processDefinition.getKey() + ":" + processDefinition.getVersion() + ":" + // ACT-505
            nextId;
            // ACT-115: maximum id length is 64 charcaters
            if (processDefinitionId.length() > 64) {
                processDefinitionId = nextId;
            }
            processDefinition.setId(processDefinitionId);
            if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
                commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_CREATED, processDefinition));
            }
            removeObsoleteTimers(processDefinition);
            addTimerDeclarations(processDefinition, timers);
            removeExistingMessageEventSubscriptions(processDefinition, latestProcessDefinition);
            addMessageEventSubscriptions(processDefinition);
            removeExistingSignalEventSubScription(processDefinition, latestProcessDefinition);
            addSignalEventSubscriptions(processDefinition);
            dbSqlSession.insert(processDefinition);
            addAuthorizations(processDefinition);
            if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
                commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_INITIALIZED, processDefinition));
            }
            scheduleTimers(timers);
        } else {
            String deploymentId = deployment.getId();
            processDefinition.setDeploymentId(deploymentId);
            ProcessDefinitionEntity persistedProcessDefinition = null;
            if (processDefinition.getTenantId() == null || ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) {
                persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinition.getKey());
            } else {
                persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKeyAndTenantId(deploymentId, processDefinition.getKey(), processDefinition.getTenantId());
            }
            if (persistedProcessDefinition != null) {
                processDefinition.setId(persistedProcessDefinition.getId());
                processDefinition.setVersion(persistedProcessDefinition.getVersion());
                processDefinition.setSuspensionState(persistedProcessDefinition.getSuspensionState());
            }
        }
        // Add to cache
        DeploymentManager deploymentManager = processEngineConfiguration.getDeploymentManager();
        deploymentManager.getProcessDefinitionCache().add(processDefinition.getId(), processDefinition);
        addDefinitionInfoToCache(processDefinition, processEngineConfiguration, commandContext);
        // Add to deployment for further usage
        deployment.addDeployedArtifact(processDefinition);
        createLocalizationValues(processDefinition.getId(), bpmnModelMap.get(processDefinition.getKey()).getProcessById(processDefinition.getKey()));
    }
}
Also used : ActivitiException(org.activiti.engine.ActivitiException) ProcessDefinitionEntityManager(org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntityManager) CommandContext(org.activiti.engine.impl.interceptor.CommandContext) HashMap(java.util.HashMap) TimerEntity(org.activiti.engine.impl.persistence.entity.TimerEntity) DeploymentManager(org.activiti.engine.impl.persistence.deploy.DeploymentManager) ArrayList(java.util.ArrayList) BpmnModel(org.activiti.bpmn.model.BpmnModel) DbSqlSession(org.activiti.engine.impl.db.DbSqlSession) ByteArrayInputStream(java.io.ByteArrayInputStream) ResourceEntity(org.activiti.engine.impl.persistence.entity.ResourceEntity) ProcessDefinitionEntity(org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity) ProcessEngineConfigurationImpl(org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl) BpmnParse(org.activiti.engine.impl.bpmn.parser.BpmnParse)

Example 28 with CommandContext

use of org.activiti.engine.impl.interceptor.CommandContext in project Activiti by Activiti.

the class BpmnDeployer method addMessageEventSubscriptions.

@SuppressWarnings("unchecked")
protected void addMessageEventSubscriptions(ProcessDefinitionEntity processDefinition) {
    CommandContext commandContext = Context.getCommandContext();
    List<EventSubscriptionDeclaration> eventDefinitions = (List<EventSubscriptionDeclaration>) processDefinition.getProperty(BpmnParse.PROPERTYNAME_EVENT_SUBSCRIPTION_DECLARATION);
    if (eventDefinitions != null) {
        Set<String> messageNames = new HashSet<String>();
        for (EventSubscriptionDeclaration eventDefinition : eventDefinitions) {
            if (eventDefinition.getEventType().equals("message") && eventDefinition.isStartEvent()) {
                if (!messageNames.contains(eventDefinition.getEventName())) {
                    messageNames.add(eventDefinition.getEventName());
                } else {
                    throw new ActivitiException("Cannot deploy process definition '" + processDefinition.getResourceName() + "': there are multiple message event subscriptions for the message with name '" + eventDefinition.getEventName() + "'.");
                }
                // look for subscriptions for the same name in db:
                List<EventSubscriptionEntity> subscriptionsForSameMessageName = commandContext.getEventSubscriptionEntityManager().findEventSubscriptionsByName(MessageEventHandler.EVENT_HANDLER_TYPE, eventDefinition.getEventName(), processDefinition.getTenantId());
                // also look for subscriptions created in the session:
                List<MessageEventSubscriptionEntity> cachedSubscriptions = commandContext.getDbSqlSession().findInCache(MessageEventSubscriptionEntity.class);
                for (MessageEventSubscriptionEntity cachedSubscription : cachedSubscriptions) {
                    if (eventDefinition.getEventName().equals(cachedSubscription.getEventName()) && !subscriptionsForSameMessageName.contains(cachedSubscription)) {
                        subscriptionsForSameMessageName.add(cachedSubscription);
                    }
                }
                // remove subscriptions deleted in the same command
                subscriptionsForSameMessageName = commandContext.getDbSqlSession().pruneDeletedEntities(subscriptionsForSameMessageName);
                for (EventSubscriptionEntity eventSubscriptionEntity : subscriptionsForSameMessageName) {
                    // no process instance-id = it's a message start event
                    if (StringUtils.isEmpty(eventSubscriptionEntity.getProcessInstanceId())) {
                        throw new ActivitiException("Cannot deploy process definition '" + processDefinition.getResourceName() + "': there already is a message event subscription for the message with name '" + eventDefinition.getEventName() + "'.");
                    }
                }
                MessageEventSubscriptionEntity newSubscription = new MessageEventSubscriptionEntity();
                newSubscription.setEventName(eventDefinition.getEventName());
                newSubscription.setActivityId(eventDefinition.getActivityId());
                newSubscription.setConfiguration(processDefinition.getId());
                newSubscription.setProcessDefinitionId(processDefinition.getId());
                if (processDefinition.getTenantId() != null) {
                    newSubscription.setTenantId(processDefinition.getTenantId());
                }
                newSubscription.insert();
            }
        }
    }
}
Also used : ActivitiException(org.activiti.engine.ActivitiException) CommandContext(org.activiti.engine.impl.interceptor.CommandContext) List(java.util.List) ArrayList(java.util.ArrayList) EventSubscriptionDeclaration(org.activiti.engine.impl.bpmn.parser.EventSubscriptionDeclaration) MessageEventSubscriptionEntity(org.activiti.engine.impl.persistence.entity.MessageEventSubscriptionEntity) SignalEventSubscriptionEntity(org.activiti.engine.impl.persistence.entity.SignalEventSubscriptionEntity) MessageEventSubscriptionEntity(org.activiti.engine.impl.persistence.entity.MessageEventSubscriptionEntity) EventSubscriptionEntity(org.activiti.engine.impl.persistence.entity.EventSubscriptionEntity) HashSet(java.util.HashSet)

Example 29 with CommandContext

use of org.activiti.engine.impl.interceptor.CommandContext in project Activiti by Activiti.

the class IntermediateThrowSignalEventActivityBehavior method execute.

public void execute(ActivityExecution execution) throws Exception {
    CommandContext commandContext = Context.getCommandContext();
    List<SignalEventSubscriptionEntity> subscriptionEntities = null;
    if (processInstanceScope) {
        subscriptionEntities = commandContext.getEventSubscriptionEntityManager().findSignalEventSubscriptionsByProcessInstanceAndEventName(execution.getProcessInstanceId(), signalDefinition.getEventName());
    } else {
        subscriptionEntities = commandContext.getEventSubscriptionEntityManager().findSignalEventSubscriptionsByEventName(signalDefinition.getEventName(), execution.getTenantId());
    }
    for (SignalEventSubscriptionEntity signalEventSubscriptionEntity : subscriptionEntities) {
        signalEventSubscriptionEntity.eventReceived(null, signalDefinition.isAsync());
    }
    if (execution.getActivity() != null) {
        // dont continue if process has already finished
        leave(execution);
    }
}
Also used : CommandContext(org.activiti.engine.impl.interceptor.CommandContext) SignalEventSubscriptionEntity(org.activiti.engine.impl.persistence.entity.SignalEventSubscriptionEntity)

Example 30 with CommandContext

use of org.activiti.engine.impl.interceptor.CommandContext in project Activiti by Activiti.

the class BpmnDeployer method createLocalizationValues.

protected void createLocalizationValues(String processDefinitionId, Process process) {
    if (process == null)
        return;
    CommandContext commandContext = Context.getCommandContext();
    DynamicBpmnService dynamicBpmnService = commandContext.getProcessEngineConfiguration().getDynamicBpmnService();
    ObjectNode infoNode = dynamicBpmnService.getProcessDefinitionInfo(processDefinitionId);
    boolean localizationValuesChanged = false;
    List<ExtensionElement> localizationElements = process.getExtensionElements().get("localization");
    if (localizationElements != null) {
        for (ExtensionElement localizationElement : localizationElements) {
            if (BpmnXMLConstants.ACTIVITI_EXTENSIONS_PREFIX.equals(localizationElement.getNamespacePrefix())) {
                String locale = localizationElement.getAttributeValue(null, "locale");
                String name = localizationElement.getAttributeValue(null, "name");
                String documentation = null;
                List<ExtensionElement> documentationElements = localizationElement.getChildElements().get("documentation");
                if (documentationElements != null) {
                    for (ExtensionElement documentationElement : documentationElements) {
                        documentation = StringUtils.trimToNull(documentationElement.getElementText());
                        break;
                    }
                }
                String processId = process.getId();
                if (isEqualToCurrentLocalizationValue(locale, processId, "name", name, infoNode) == false) {
                    dynamicBpmnService.changeLocalizationName(locale, processId, name, infoNode);
                    localizationValuesChanged = true;
                }
                if (documentation != null && isEqualToCurrentLocalizationValue(locale, processId, "description", documentation, infoNode) == false) {
                    dynamicBpmnService.changeLocalizationDescription(locale, processId, documentation, infoNode);
                    localizationValuesChanged = true;
                }
                break;
            }
        }
    }
    boolean isFlowElementLocalizationChanged = localizeFlowElements(process.getFlowElements(), infoNode);
    boolean isDataObjectLocalizationChanged = localizeDataObjectElements(process.getDataObjects(), infoNode);
    if (isFlowElementLocalizationChanged || isDataObjectLocalizationChanged) {
        localizationValuesChanged = true;
    }
    if (localizationValuesChanged) {
        dynamicBpmnService.saveProcessDefinitionInfo(processDefinitionId, infoNode);
    }
}
Also used : CommandContext(org.activiti.engine.impl.interceptor.CommandContext) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DynamicBpmnService(org.activiti.engine.DynamicBpmnService) ExtensionElement(org.activiti.bpmn.model.ExtensionElement)

Aggregations

CommandContext (org.activiti.engine.impl.interceptor.CommandContext)72 CommandExecutor (org.activiti.engine.impl.interceptor.CommandExecutor)18 DbSqlSession (org.activiti.engine.impl.db.DbSqlSession)13 SignalEventSubscriptionEntity (org.activiti.engine.impl.persistence.entity.SignalEventSubscriptionEntity)8 Date (java.util.Date)7 ActivitiException (org.activiti.engine.ActivitiException)7 CommandConfig (org.activiti.engine.impl.interceptor.CommandConfig)7 EventSubscriptionEntity (org.activiti.engine.impl.persistence.entity.EventSubscriptionEntity)7 ProcessDefinitionEntity (org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity)7 MessageEventSubscriptionEntity (org.activiti.engine.impl.persistence.entity.MessageEventSubscriptionEntity)6 HashMap (java.util.HashMap)4 TimerEntity (org.activiti.engine.impl.persistence.entity.TimerEntity)4 Job (org.activiti.engine.runtime.Job)4 Deployment (org.activiti.engine.test.Deployment)4 ArrayList (java.util.ArrayList)3 GregorianCalendar (java.util.GregorianCalendar)3 List (java.util.List)3 ExtensionElement (org.activiti.bpmn.model.ExtensionElement)3 DynamicBpmnService (org.activiti.engine.DynamicBpmnService)3 JobEntity (org.activiti.engine.impl.persistence.entity.JobEntity)3