Search in sources :

Example 1 with TimerEntity

use of org.activiti.engine.impl.persistence.entity.TimerEntity in project Activiti by Activiti.

the class JobQueryTest method createJobWithoutExceptionMsg.

private void createJobWithoutExceptionMsg() {
    CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutor();
    commandExecutor.execute(new Command<Void>() {

        public Void execute(CommandContext commandContext) {
            JobEntityManager jobManager = commandContext.getJobEntityManager();
            timerEntity = new TimerEntity();
            timerEntity.setLockOwner(UUID.randomUUID().toString());
            timerEntity.setDuedate(new Date());
            timerEntity.setRetries(0);
            StringWriter stringWriter = new StringWriter();
            NullPointerException exception = new NullPointerException();
            exception.printStackTrace(new PrintWriter(stringWriter));
            timerEntity.setExceptionStacktrace(stringWriter.toString());
            jobManager.insert(timerEntity);
            assertNotNull(timerEntity.getId());
            return null;
        }
    });
}
Also used : JobEntityManager(org.activiti.engine.impl.persistence.entity.JobEntityManager) CommandContext(org.activiti.engine.impl.interceptor.CommandContext) StringWriter(java.io.StringWriter) TimerEntity(org.activiti.engine.impl.persistence.entity.TimerEntity) CommandExecutor(org.activiti.engine.impl.interceptor.CommandExecutor) Date(java.util.Date) PrintWriter(java.io.PrintWriter)

Example 2 with TimerEntity

use of org.activiti.engine.impl.persistence.entity.TimerEntity 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 3 with TimerEntity

use of org.activiti.engine.impl.persistence.entity.TimerEntity in project Activiti by Activiti.

the class BpmnDeployer method addTimerDeclarations.

@SuppressWarnings("unchecked")
protected void addTimerDeclarations(ProcessDefinitionEntity processDefinition, List<TimerEntity> timers) {
    List<TimerDeclarationImpl> timerDeclarations = (List<TimerDeclarationImpl>) processDefinition.getProperty(BpmnParse.PROPERTYNAME_START_TIMER);
    if (timerDeclarations != null) {
        for (TimerDeclarationImpl timerDeclaration : timerDeclarations) {
            TimerEntity timer = timerDeclaration.prepareTimerEntity(null);
            if (timer != null) {
                timer.setProcessDefinitionId(processDefinition.getId());
                // Inherit timer (if appliccable)
                if (processDefinition.getTenantId() != null) {
                    timer.setTenantId(processDefinition.getTenantId());
                }
                timers.add(timer);
            }
        }
    }
}
Also used : TimerDeclarationImpl(org.activiti.engine.impl.jobexecutor.TimerDeclarationImpl) TimerEntity(org.activiti.engine.impl.persistence.entity.TimerEntity) List(java.util.List) ArrayList(java.util.ArrayList)

Example 4 with TimerEntity

use of org.activiti.engine.impl.persistence.entity.TimerEntity in project Activiti by Activiti.

the class JobExecutorTestCase method createTweetTimer.

protected TimerEntity createTweetTimer(String msg, Date duedate) {
    TimerEntity timer = new TimerEntity();
    timer.setJobHandlerType("tweet");
    timer.setJobHandlerConfiguration(msg);
    timer.setDuedate(duedate);
    return timer;
}
Also used : TimerEntity(org.activiti.engine.impl.persistence.entity.TimerEntity)

Example 5 with TimerEntity

use of org.activiti.engine.impl.persistence.entity.TimerEntity in project Activiti by Activiti.

the class SimulationAcquireJobsRunnable method run.

public synchronized void run() {
    //		    if (log.isLoggable(Level.INFO)) {
    //		      log.info(jobExecutor.getName() + " starting to acquire jobs");
    //		    }
    final CommandExecutor commandExecutor = jobExecutor.getCommandExecutor();
    // while is not needed - repetition is done by event scheduling 
    //		    while (!isInterrupted) {
    isWaiting.set(false);
    int maxJobsPerAcquisition = jobExecutor.getMaxJobsPerAcquisition();
    try {
        AcquiredJobs acquiredJobs = commandExecutor.execute(jobExecutor.getAcquireJobsCmd());
        for (List<String> jobIds : acquiredJobs.getJobIdBatches()) {
            jobExecutor.executeJobs(jobIds);
        }
        // if all jobs were executed
        millisToWait = jobExecutor.getWaitTimeInMillis();
        int jobsAcquired = acquiredJobs.getJobIdBatches().size();
        if (jobsAcquired < maxJobsPerAcquisition) {
            isJobAdded = false;
            // check if the next timer should fire before the normal sleep time is over
            Date duedate = new Date(SimulationRunContext.getClock().getCurrentTime().getTime() + millisToWait);
            List<TimerEntity> nextTimers = commandExecutor.execute(new GetUnlockedTimersByDuedateCmd(duedate, new Page(0, 1)));
            if (!nextTimers.isEmpty()) {
                long millisTillNextTimer = nextTimers.get(0).getDuedate().getTime() - SimulationRunContext.getClock().getCurrentTime().getTime();
                if (millisTillNextTimer < millisToWait && millisTillNextTimer != 0) {
                    millisToWait = millisTillNextTimer;
                }
            }
        } else {
            millisToWait = 0;
        }
    } catch (ActivitiOptimisticLockingException optimisticLockingException) {
        // See https://activiti.atlassian.net/browse/ACT-1390
        log.trace("Optimistic locking exception during job acquisition. If you have multiple job executors running against the same database, " + "this exception means that this thread tried to acquire a job, which already was acquired by another job executor acquisition 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 (Exception e) {
        log.error("exception during job acquisition: " + e.getMessage(), e);
        millisToWait = jobExecutor.getWaitTimeInMillis();
    }
    if ((millisToWait > 0) && (!isJobAdded)) {
        try {
            log.trace("job acquisition thread sleeping for " + millisToWait + " millis");
            synchronized (MONITOR) {
                if (!isInterrupted) {
                    isWaiting.set(true);
                    SimulationEvent event = new SimulationEvent.Builder(SimulationEvent.TYPE_ACQUIRE_JOB_NOTIFICATION_EVENT).simulationTime(SimulationRunContext.getClock().getCurrentTime().getTime() + millisToWait).property(this).build();
                    SimulationRunContext.getEventCalendar().addEvent(event);
                // do not need to wait. - event scheduling is enough
                //MONITOR.wait(millisToWait);
                }
            }
            log.trace("job acquisition thread woke up");
        } finally {
        //		          isWaiting.set(false);
        }
    } else {
        // schedule run now
        SimulationEvent event = new SimulationEvent.Builder(SimulationEvent.TYPE_ACQUIRE_JOB_NOTIFICATION_EVENT).simulationTime(SimulationRunContext.getClock().getCurrentTime().getTime()).property(this).build();
        SimulationRunContext.getEventCalendar().addEvent(event);
    }
//		    }
//		    if (log.isLoggable(Level.INFO)) {
//		      log.info(jobExecutor.getName() + " stopped job acquisition");
//		    }
}
Also used : TimerEntity(org.activiti.engine.impl.persistence.entity.TimerEntity) CommandExecutor(org.activiti.engine.impl.interceptor.CommandExecutor) ActivitiOptimisticLockingException(org.activiti.engine.ActivitiOptimisticLockingException) Page(org.activiti.engine.impl.Page) Date(java.util.Date) ActivitiOptimisticLockingException(org.activiti.engine.ActivitiOptimisticLockingException) SimulationEvent(org.activiti.crystalball.simulator.SimulationEvent)

Aggregations

TimerEntity (org.activiti.engine.impl.persistence.entity.TimerEntity)15 Date (java.util.Date)5 CommandExecutor (org.activiti.engine.impl.interceptor.CommandExecutor)5 Deployment (org.activiti.engine.test.Deployment)5 ArrayList (java.util.ArrayList)4 Calendar (java.util.Calendar)4 CommandContext (org.activiti.engine.impl.interceptor.CommandContext)4 ProcessDefinitionEntity (org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity)4 ProcessInstance (org.activiti.engine.runtime.ProcessInstance)4 ActivitiActivityCancelledEvent (org.activiti.engine.delegate.event.ActivitiActivityCancelledEvent)3 ActivitiEvent (org.activiti.engine.delegate.event.ActivitiEvent)3 Job (org.activiti.engine.runtime.Job)3 ActivitiException (org.activiti.engine.ActivitiException)2 Page (org.activiti.engine.impl.Page)2 DeploymentManager (org.activiti.engine.impl.persistence.deploy.DeploymentManager)2 JobEntityManager (org.activiti.engine.impl.persistence.entity.JobEntityManager)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 HashMap (java.util.HashMap)1