Search in sources :

Example 31 with JobDefinitionEntity

use of org.finra.herd.model.jpa.JobDefinitionEntity in project herd by FINRAOS.

the class JobServiceImpl method getJobs.

@Override
public JobSummaries getJobs(String namespace, String jobName, JobStatusEnum jobStatus, DateTime startTime, DateTime endTime) throws Exception {
    // Trim the parameters.
    String namespaceTrimmed = namespace == null ? null : namespace.trim();
    String jobNameTrimmed = jobName == null ? null : jobName.trim();
    // Construct the list of job summaries to return.
    JobSummaries jobSummaries = new JobSummaries();
    /*
         * Get the namespaces which the current user is authorized to READ.
         * If a specific namespace was requested, and the current user is authorized to read the namespace, include ONLY the requested namespace.
         * If a specific namespace was requested, but the current user is not authorized to read the namespace, clear all namespaces.
         * Otherwise, include all authorized namespaces.
         *
         * This ensures that only authorized namespaces are queried from the database and that
         * an unauthorized user cannot determine if he specified an existing namespace or not.
         */
    Set<String> authorizedNamespaces = namespaceSecurityHelper.getAuthorizedNamespaces(NamespacePermissionEnum.READ);
    if (StringUtils.isNotBlank(namespaceTrimmed)) {
        NamespaceEntity namespaceEntity = namespaceDao.getNamespaceByCd(namespaceTrimmed);
        if (namespaceEntity != null && authorizedNamespaces.contains(namespaceEntity.getCode())) {
            authorizedNamespaces.clear();
            authorizedNamespaces.add(namespaceEntity.getCode());
        } else {
            authorizedNamespaces.clear();
        }
    }
    // Continue the processing only when the list of authorized namespaces is not empty.
    if (!authorizedNamespaces.isEmpty()) {
        // Build a set of Activiti process definition keys for each job definition that was filtered.
        Set<String> processDefinitionIds = new HashSet<>();
        for (JobDefinitionEntity jobDefinitionEntity : jobDefinitionDao.getJobDefinitionsByFilter(authorizedNamespaces, jobNameTrimmed)) {
            processDefinitionIds.add(jobDefinitionEntity.getActivitiId());
        }
        // Continue the processing only when the list of filtered job definitions is not empty.
        if (!processDefinitionIds.isEmpty()) {
            /*
                 * Keep a mapping of definition ID to its key.
                 * Activiti API does not provide an easy way to get the key without doing extra queries for each definition.
                 */
            Map<String, String> processDefinitionIdToKeyMap = new HashMap<>();
            for (ProcessDefinition processDefinition : activitiService.getProcessDefinitionsByIds(processDefinitionIds)) {
                processDefinitionIdToKeyMap.put(processDefinition.getId(), processDefinition.getKey());
            }
            List<HistoricProcessInstance> historicProcessInstances = getHistoricProcessInstances(processDefinitionIdToKeyMap.values(), jobStatus, startTime, endTime);
            // Get a set of all runtime suspended process instance ids.
            Set<String> suspendedProcessInstanceIds = getSuspendedProcessInstanceIds();
            // Compile the Regex pattern.
            Pattern pattern = jobDefinitionHelper.getNamespaceAndJobNameRegexPattern();
            // Loop over the process instances and build a list of job summaries to return.
            for (HistoricProcessInstance historicProcessInstance : historicProcessInstances) {
                // Exclude all process instances started using older versions of the process definition.
                if (processDefinitionIdToKeyMap.containsKey(historicProcessInstance.getProcessDefinitionId())) {
                    // Set a flag if this job is SUSPENDED.
                    boolean suspended = suspendedProcessInstanceIds.contains(historicProcessInstance.getId());
                    // getHistoricProcessInstances() returns both RUNNING and SUSPENDED process instances.
                    if (!(JobStatusEnum.SUSPENDED.equals(jobStatus) && !suspended) && !(JobStatusEnum.RUNNING.equals(jobStatus) && suspended)) {
                        // Create a new job summary.
                        JobSummary jobSummary = new JobSummary();
                        jobSummary.setId(historicProcessInstance.getId());
                        // Get the job definition key.
                        JobDefinitionAlternateKeyDto jobDefinitionKey = jobDefinitionHelper.getJobDefinitionKey(processDefinitionIdToKeyMap.get(historicProcessInstance.getProcessDefinitionId()), pattern);
                        // Set the namespace and job name on the job summary.
                        jobSummary.setNamespace(jobDefinitionKey.getNamespace());
                        jobSummary.setJobName(jobDefinitionKey.getJobName());
                        // Set the start time always since all jobs will have a start time.
                        jobSummary.setStartTime(HerdDateUtils.getXMLGregorianCalendarValue(historicProcessInstance.getStartTime()));
                        if (historicProcessInstance.getEndTime() == null) {
                            // Since there is no end time, the job is running or suspended.
                            jobSummary.setStatus(suspended ? JobStatusEnum.SUSPENDED : JobStatusEnum.RUNNING);
                            // If the end time is null, then determine the status based on the presence of any exceptions.
                            jobSummary.setTotalExceptions(activitiService.getJobsWithExceptionCountByProcessInstanceId(historicProcessInstance.getId()));
                        } else {
                            // If the end time is set, then the job has finished so set the end time and the status to completed.
                            jobSummary.setEndTime(HerdDateUtils.getXMLGregorianCalendarValue(historicProcessInstance.getEndTime()));
                            jobSummary.setStatus(JobStatusEnum.COMPLETED);
                        }
                        // Add the new summary to the list.
                        jobSummaries.getJobSummaries().add(jobSummary);
                    }
                }
            }
        }
    }
    // Return the list of job summaries.
    return jobSummaries;
}
Also used : Pattern(java.util.regex.Pattern) NamespaceEntity(org.finra.herd.model.jpa.NamespaceEntity) HashMap(java.util.HashMap) HistoricProcessInstance(org.activiti.engine.history.HistoricProcessInstance) JobSummaries(org.finra.herd.model.api.xml.JobSummaries) ProcessDefinition(org.activiti.engine.repository.ProcessDefinition) JobSummary(org.finra.herd.model.api.xml.JobSummary) JobDefinitionEntity(org.finra.herd.model.jpa.JobDefinitionEntity) JobDefinitionAlternateKeyDto(org.finra.herd.model.dto.JobDefinitionAlternateKeyDto) HashSet(java.util.HashSet)

Example 32 with JobDefinitionEntity

use of org.finra.herd.model.jpa.JobDefinitionEntity in project herd by FINRAOS.

the class BaseJavaDelegateTest method testExecute.

@Test
public void testExecute() throws Exception {
    // Set up expected values.
    String jobDefinitionNamespace = "jobDefinitionNamespace";
    String jobDefinitionName = "jobDefinitionName";
    String processDefinitionId = "processDefinitionId";
    String processDefinitionKey = String.format("%s.%s", jobDefinitionNamespace, jobDefinitionName);
    String updatedBy = "updatedBy";
    JobDefinitionEntity jobDefinitionEntity = new JobDefinitionEntity();
    jobDefinitionEntity.setUpdatedBy(updatedBy);
    // Mock dependency methods.
    when(delegateExecution.getProcessDefinitionId()).thenReturn(processDefinitionId);
    ProcessDefinition processDefinition = mock(ProcessDefinition.class);
    when(processDefinition.getKey()).thenReturn(processDefinitionKey);
    when(activitiService.getProcessDefinitionById(any())).thenReturn(processDefinition);
    when(jobDefinitionDaoHelper.getJobDefinitionEntity(any(), any())).thenReturn(jobDefinitionEntity);
    // Execute test method.
    baseJavaDelegate.execute(delegateExecution);
    // Verify dependencies were invoked correctly.
    InOrder inOrder = inOrder(configurationDaoHelper, activitiService, jobDefinitionDaoHelper, userNamespaceAuthorizationHelper, activitiRuntimeHelper);
    inOrder.verify(configurationDaoHelper).checkNotAllowedMethod(baseJavaDelegate.getClass().getCanonicalName());
    inOrder.verify(activitiService).getProcessDefinitionById(processDefinitionId);
    inOrder.verify(jobDefinitionDaoHelper).getJobDefinitionEntity(jobDefinitionNamespace, jobDefinitionName);
    inOrder.verify(userNamespaceAuthorizationHelper).buildNamespaceAuthorizations(applicationUserUserIdEq(updatedBy));
    inOrder.verify(activitiRuntimeHelper).setTaskSuccessInWorkflow(delegateExecution);
    inOrder.verifyNoMoreInteractions();
    verifyNoMoreInteractions(configurationDaoHelper, activitiService, jobDefinitionDaoHelper, userNamespaceAuthorizationHelper, activitiRuntimeHelper);
    // Assert that security context is cleared at the end of execute.
    assertNull(SecurityContextHolder.getContext().getAuthentication());
}
Also used : JobDefinitionEntity(org.finra.herd.model.jpa.JobDefinitionEntity) InOrder(org.mockito.InOrder) ProcessDefinition(org.activiti.engine.repository.ProcessDefinition) AbstractServiceTest(org.finra.herd.service.AbstractServiceTest) Test(org.junit.Test)

Example 33 with JobDefinitionEntity

use of org.finra.herd.model.jpa.JobDefinitionEntity in project herd by FINRAOS.

the class JobDefinitionServiceImpl method createOrUpdateJobDefinitionEntity.

/**
 * Creates a new job definition entity from the request information.
 *
 * @param jobDefinitionEntity an optional existing job definition entity to update. If null, then a new one will be created.
 * @param namespaceEntity the namespace entity.
 * @param jobName the job name.
 * @param description the job definition description.
 * @param activitiId the Activiti Id.
 * @param parameters the job definition parameters.
 *
 * @return the newly created or existing updated job definition entity.
 */
private JobDefinitionEntity createOrUpdateJobDefinitionEntity(JobDefinitionEntity jobDefinitionEntity, NamespaceEntity namespaceEntity, String jobName, String description, String activitiId, List<Parameter> parameters, S3PropertiesLocation s3PropertiesLocation) {
    JobDefinitionEntity jobDefinitionEntityLocal = jobDefinitionEntity;
    // If a job definition entity doesn't yet exist, create a new one.
    if (jobDefinitionEntityLocal == null) {
        jobDefinitionEntityLocal = new JobDefinitionEntity();
    }
    // Create a new entity.
    jobDefinitionEntityLocal.setName(jobName);
    jobDefinitionEntityLocal.setNamespace(namespaceEntity);
    jobDefinitionEntityLocal.setDescription(description);
    jobDefinitionEntityLocal.setActivitiId(activitiId);
    // Set or clear S3 properties location
    String bucketName = null;
    String key = null;
    if (s3PropertiesLocation != null) {
        bucketName = s3PropertiesLocation.getBucketName();
        key = s3PropertiesLocation.getKey();
    }
    jobDefinitionEntityLocal.setS3BucketName(bucketName);
    jobDefinitionEntityLocal.setS3ObjectKey(key);
    // Create the parameters.
    List<JobDefinitionParameterEntity> parameterEntities = new ArrayList<>();
    // As per generated JobDefinitionCreateRequest class, getParameters() never returns null.
    if (!CollectionUtils.isEmpty(parameters)) {
        for (Parameter parameter : parameters) {
            JobDefinitionParameterEntity parameterEntity = new JobDefinitionParameterEntity();
            parameterEntities.add(parameterEntity);
            parameterEntity.setName(parameter.getName());
            parameterEntity.setValue(parameter.getValue());
        }
    }
    // Set the new list of parameters on the entity.
    jobDefinitionEntityLocal.setParameters(parameterEntities);
    return jobDefinitionEntityLocal;
}
Also used : JobDefinitionEntity(org.finra.herd.model.jpa.JobDefinitionEntity) JobDefinitionParameterEntity(org.finra.herd.model.jpa.JobDefinitionParameterEntity) ArrayList(java.util.ArrayList) Parameter(org.finra.herd.model.api.xml.Parameter)

Example 34 with JobDefinitionEntity

use of org.finra.herd.model.jpa.JobDefinitionEntity in project herd by FINRAOS.

the class JobDefinitionServiceImpl method updateJobDefinition.

@NamespacePermission(fields = "#namespace", permissions = NamespacePermissionEnum.WRITE)
@Override
public JobDefinition updateJobDefinition(String namespace, String jobName, JobDefinitionUpdateRequest request, boolean enforceAsync) throws Exception {
    // Validate the job definition alternate key.
    String namespaceLocal = alternateKeyHelper.validateStringParameter("namespace", namespace);
    String jobNameLocal = alternateKeyHelper.validateStringParameter("job name", jobName);
    // Validate and trim the Activiti job XML.
    Assert.hasText(request.getActivitiJobXml(), "An Activiti job XML must be specified.");
    request.setActivitiJobXml(request.getActivitiJobXml().trim());
    // Perform the job definition validation.
    validateJobDefinition(namespaceLocal, jobNameLocal, request.getActivitiJobXml(), request.getParameters(), request.getS3PropertiesLocation());
    if (enforceAsync) {
        assertFirstTaskIsAsync(activitiHelper.constructBpmnModelFromXmlAndValidate(request.getActivitiJobXml()));
    }
    // Get the namespace and ensure it exists.
    NamespaceEntity namespaceEntity = namespaceDaoHelper.getNamespaceEntity(namespaceLocal);
    // Retrieve and ensure that a job definition exists.
    JobDefinitionEntity jobDefinitionEntity = jobDefinitionDaoHelper.getJobDefinitionEntity(namespaceLocal, jobNameLocal);
    // Create the new process definition.
    ProcessDefinition processDefinition = createProcessDefinition(namespaceLocal, jobNameLocal, request.getActivitiJobXml());
    // Create a job definition entity from the request information.
    jobDefinitionEntity = createOrUpdateJobDefinitionEntity(jobDefinitionEntity, namespaceEntity, jobNameLocal, request.getDescription(), processDefinition.getId(), request.getParameters(), request.getS3PropertiesLocation());
    // Persist the entity.
    jobDefinitionEntity = jobDefinitionDao.saveAndRefresh(jobDefinitionEntity);
    // Create and return the job definition object from the persisted entity.
    return createJobDefinitionFromEntity(jobDefinitionEntity);
}
Also used : JobDefinitionEntity(org.finra.herd.model.jpa.JobDefinitionEntity) NamespaceEntity(org.finra.herd.model.jpa.NamespaceEntity) ProcessDefinition(org.activiti.engine.repository.ProcessDefinition) NamespacePermission(org.finra.herd.model.annotation.NamespacePermission)

Example 35 with JobDefinitionEntity

use of org.finra.herd.model.jpa.JobDefinitionEntity in project herd by FINRAOS.

the class JobDefinitionServiceImpl method getJobDefinition.

@NamespacePermission(fields = "#namespace", permissions = NamespacePermissionEnum.READ)
@Override
public JobDefinition getJobDefinition(String namespace, String jobName) throws Exception {
    // Validate the job definition alternate key.
    String namespaceLocal = alternateKeyHelper.validateStringParameter("namespace", namespace);
    String jobNameLocal = alternateKeyHelper.validateStringParameter("job name", jobName);
    // Retrieve and ensure that a job definition exists.
    JobDefinitionEntity jobDefinitionEntity = jobDefinitionDaoHelper.getJobDefinitionEntity(namespaceLocal, jobNameLocal);
    // Create and return the job definition object from the persisted entity.
    return createJobDefinitionFromEntity(jobDefinitionEntity);
}
Also used : JobDefinitionEntity(org.finra.herd.model.jpa.JobDefinitionEntity) NamespacePermission(org.finra.herd.model.annotation.NamespacePermission)

Aggregations

JobDefinitionEntity (org.finra.herd.model.jpa.JobDefinitionEntity)36 NamespaceEntity (org.finra.herd.model.jpa.NamespaceEntity)18 Test (org.junit.Test)17 ArrayList (java.util.ArrayList)12 ProcessDefinition (org.activiti.engine.repository.ProcessDefinition)11 HistoricProcessInstance (org.activiti.engine.history.HistoricProcessInstance)7 Collection (java.util.Collection)6 HashSet (java.util.HashSet)6 JobDefinition (org.finra.herd.model.api.xml.JobDefinition)5 JobStatusEnum (org.finra.herd.model.api.xml.JobStatusEnum)5 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)4 Predicate (javax.persistence.criteria.Predicate)4 NamespacePermission (org.finra.herd.model.annotation.NamespacePermission)4 JobAction (org.finra.herd.model.api.xml.JobAction)4 JobDefinitionCreateRequest (org.finra.herd.model.api.xml.JobDefinitionCreateRequest)4 JobSummaries (org.finra.herd.model.api.xml.JobSummaries)4 JobSummary (org.finra.herd.model.api.xml.JobSummary)4 NotificationActionEntity (org.finra.herd.model.jpa.NotificationActionEntity)4 NotificationJobActionEntity (org.finra.herd.model.jpa.NotificationJobActionEntity)4 Date (java.util.Date)3