Example usage for org.apache.commons.collections4 CollectionUtils isEmpty

List of usage examples for org.apache.commons.collections4 CollectionUtils isEmpty

Introduction

In this page you can find the example usage for org.apache.commons.collections4 CollectionUtils isEmpty.

Prototype

public static boolean isEmpty(final Collection<?> coll) 

Source Link

Document

Null-safe check if the specified collection is empty.

Usage

From source file:org.finra.herd.service.impl.BusinessObjectDataStorageFileServiceImpl.java

/**
 * Validates a list of storage files to be added to the specified storage unit.
 *
 * @param storageFiles the list of storage files
 * @param storageUnitEntity the storage unit entity
 * @param validatePathPrefix the validate path prefix flag
 * @param validateFileExistence the validate file existence flag
 * @param validateFileSize the validate file size flag
 *///from   w  w w . j a va2s . c  om
private void validateStorageFiles(List<StorageFile> storageFiles, StorageUnitEntity storageUnitEntity,
        boolean validatePathPrefix, boolean validateFileExistence, boolean validateFileSize) {
    // Retrieve all storage files already registered for this storage unit loaded in a map for easy access.
    Map<String, StorageFileEntity> storageFileEntities = storageFileHelper
            .getStorageFileEntitiesMap(storageUnitEntity.getStorageFiles());

    // Perform validation of storage files listed in the request per storage directory path and/or validation flags.
    String directoryPath = null;
    String directoryPathWithTrailingSlash = null;
    if (StringUtils.isNotBlank(storageUnitEntity.getDirectoryPath())) {
        // Use the storage directory path from the storage unit.
        directoryPath = storageUnitEntity.getDirectoryPath();

        // Add a trailing slash to the storage directory path if it doesn't already have it.
        directoryPathWithTrailingSlash = StringUtils.appendIfMissing(directoryPath, "/");

        // If a storage directory path exists, then validate that all files being added are contained within that directory.
        for (StorageFile storageFile : storageFiles) {
            Assert.isTrue(storageFile.getFilePath().startsWith(directoryPathWithTrailingSlash),
                    String.format("Storage file path \"%s\" does not match the storage directory path \"%s\".",
                            storageFile.getFilePath(), directoryPathWithTrailingSlash));
        }
    } else if (validatePathPrefix || validateFileExistence) {
        // Use the expected S3 key prefix value as the storage directory path.
        directoryPath = s3KeyPrefixHelper.buildS3KeyPrefix(storageUnitEntity.getStorage(),
                storageUnitEntity.getBusinessObjectData().getBusinessObjectFormat(),
                businessObjectDataHelper.getBusinessObjectDataKey(storageUnitEntity.getBusinessObjectData()));

        // Add a trailing slash to the expected S3 key prefix if it doesn't already have it.
        directoryPathWithTrailingSlash = StringUtils.appendIfMissing(directoryPath, "/");

        // Validate that all files are contained within the expected S3 key prefix.
        for (StorageFile storageFile : storageFiles) {
            Assert.isTrue(storageFile.getFilePath().startsWith(directoryPathWithTrailingSlash), String.format(
                    "Specified storage file path \"%s\" does not match the expected S3 key prefix \"%s\".",
                    storageFile.getFilePath(), directoryPathWithTrailingSlash));
        }
    }

    // Validate that files in the request does not already exist in the database.
    if (StringUtils.isNotBlank(directoryPath)) {
        // Get a list of request storage file paths.
        List<String> requestStorageFilePaths = storageFileHelper.getFilePathsFromStorageFiles(storageFiles);

        // Retrieve all already registered storage files from the storage that start with the directory path.
        List<String> registeredStorageFilePaths = storageFileDao.getStorageFilesByStorageAndFilePathPrefix(
                storageUnitEntity.getStorage().getName(), directoryPathWithTrailingSlash);

        // Check if request contains any of the already registered files.
        registeredStorageFilePaths.retainAll(requestStorageFilePaths);
        if (!CollectionUtils.isEmpty(registeredStorageFilePaths)) {
            // Retrieve the storage file entity for the first "already registered" storage file.
            // Since the discovered storage file path exists in the database, we should not get a null back.
            StorageFileEntity storageFileEntity = storageFileDao.getStorageFileByStorageNameAndFilePath(
                    storageUnitEntity.getStorage().getName(), registeredStorageFilePaths.get(0));

            // Throw an exception reporting the information on the "already registered" storage file.
            throw new AlreadyExistsException(String.format(
                    "S3 file \"%s\" in \"%s\" storage is already registered by the business object data {%s}.",
                    registeredStorageFilePaths.get(0), storageUnitEntity.getStorage().getName(),
                    businessObjectDataHelper.businessObjectDataEntityAltKeyToString(
                            storageFileEntity.getStorageUnit().getBusinessObjectData())));
        }
    } else {
        // Since directory path is not available, we need to validate each storage file specified in the request individually.
        for (StorageFile storageFile : storageFiles) {
            // Ensure that the file is not already registered in this storage by some other business object data.
            StorageFileEntity storageFileEntity = storageFileDao.getStorageFileByStorageNameAndFilePath(
                    storageUnitEntity.getStorage().getName(), storageFile.getFilePath());
            if (storageFileEntity != null) {
                throw new AlreadyExistsException(String.format(
                        "S3 file \"%s\" in \"%s\" storage is already registered by the business object data {%s}.",
                        storageFile.getFilePath(), storageUnitEntity.getStorage().getName(),
                        businessObjectDataHelper.businessObjectDataEntityAltKeyToString(
                                storageFileEntity.getStorageUnit().getBusinessObjectData())));
            }
        }
    }

    // Validate file existence.
    if (validateFileExistence) {
        // Get S3 bucket access parameters and set the key prefix to the directory path with a trailing slash.
        // Please note that since we got here, the directory path can not be empty.
        S3FileTransferRequestParamsDto params = storageHelper
                .getS3BucketAccessParams(storageUnitEntity.getStorage());
        params.setS3KeyPrefix(directoryPathWithTrailingSlash);

        // When listing S3 files, we ignore 0 byte objects that represent S3 directories.
        Map<String, StorageFile> actualS3Keys = storageFileHelper
                .getStorageFilesMapFromS3ObjectSummaries(s3Service.listDirectory(params, true));

        // For the already registered storage files, validate each storage file against S3 keys and metadata reported by S3.
        for (Map.Entry<String, StorageFileEntity> entry : storageFileEntities.entrySet()) {
            storageFileHelper.validateStorageFileEntity(entry.getValue(), params.getS3BucketName(),
                    actualS3Keys, validateFileSize);
        }

        // Validate each storage file listed in the request.
        for (StorageFile storageFile : storageFiles) {
            storageFileHelper.validateStorageFile(storageFile, params.getS3BucketName(), actualS3Keys,
                    validateFileSize);
        }
    }
}

From source file:org.finra.herd.service.impl.BusinessObjectDataStorageFileServiceImpl.java

/**
 * Validates the given request without using any external dependencies (ex. DB). Throws appropriate exceptions when a validation error exists.
 *
 * @param businessObjectDataStorageFilesCreateRequest - request to validate
 *//*w  w w .  j a  v a 2 s. c  o m*/
private void validateBusinessObjectDataStorageFilesCreateRequest(
        BusinessObjectDataStorageFilesCreateRequest businessObjectDataStorageFilesCreateRequest) {
    Assert.hasText(businessObjectDataStorageFilesCreateRequest.getNamespace(),
            "A namespace must be specified.");
    businessObjectDataStorageFilesCreateRequest
            .setNamespace(businessObjectDataStorageFilesCreateRequest.getNamespace().trim());

    Assert.hasText(businessObjectDataStorageFilesCreateRequest.getBusinessObjectDefinitionName(),
            "A business object definition name must be specified.");
    businessObjectDataStorageFilesCreateRequest.setBusinessObjectDefinitionName(
            businessObjectDataStorageFilesCreateRequest.getBusinessObjectDefinitionName().trim());

    Assert.hasText(businessObjectDataStorageFilesCreateRequest.getBusinessObjectFormatUsage(),
            "A business object format usage must be specified.");
    businessObjectDataStorageFilesCreateRequest.setBusinessObjectFormatUsage(
            businessObjectDataStorageFilesCreateRequest.getBusinessObjectFormatUsage().trim());

    Assert.hasText(businessObjectDataStorageFilesCreateRequest.getBusinessObjectFormatFileType(),
            "A business object format file type must be specified.");
    businessObjectDataStorageFilesCreateRequest.setBusinessObjectFormatFileType(
            businessObjectDataStorageFilesCreateRequest.getBusinessObjectFormatFileType().trim());

    Assert.notNull(businessObjectDataStorageFilesCreateRequest.getBusinessObjectFormatVersion(),
            "A business object format version must be specified.");

    Assert.hasText(businessObjectDataStorageFilesCreateRequest.getPartitionValue(),
            "A partition value must be specified.");
    businessObjectDataStorageFilesCreateRequest
            .setPartitionValue(businessObjectDataStorageFilesCreateRequest.getPartitionValue().trim());

    int subPartitionValuesCount = CollectionUtils
            .size(businessObjectDataStorageFilesCreateRequest.getSubPartitionValues());
    Assert.isTrue(subPartitionValuesCount <= BusinessObjectDataEntity.MAX_SUBPARTITIONS,
            String.format("Exceeded maximum number of allowed subpartitions: %d.",
                    BusinessObjectDataEntity.MAX_SUBPARTITIONS));

    for (int i = 0; i < subPartitionValuesCount; i++) {
        Assert.hasText(businessObjectDataStorageFilesCreateRequest.getSubPartitionValues().get(i),
                "A subpartition value must be specified.");
        businessObjectDataStorageFilesCreateRequest.getSubPartitionValues().set(i,
                businessObjectDataStorageFilesCreateRequest.getSubPartitionValues().get(i).trim());
    }

    Assert.notNull(businessObjectDataStorageFilesCreateRequest.getBusinessObjectDataVersion(),
            "A business object data version must be specified.");

    Assert.hasText(businessObjectDataStorageFilesCreateRequest.getStorageName(),
            "A storage name must be specified.");
    businessObjectDataStorageFilesCreateRequest
            .setStorageName(businessObjectDataStorageFilesCreateRequest.getStorageName().trim());

    if (BooleanUtils.isTrue(businessObjectDataStorageFilesCreateRequest.isDiscoverStorageFiles())) {
        // The auto-discovery of storage files is enabled, thus storage files can not be specified.
        Assert.isTrue(CollectionUtils.isEmpty(businessObjectDataStorageFilesCreateRequest.getStorageFiles()),
                "Storage files cannot be specified when discovery of storage files is enabled.");
    } else {
        // Since auto-discovery is disabled, at least one storage file must be specified.
        Assert.notEmpty(businessObjectDataStorageFilesCreateRequest.getStorageFiles(),
                "At least one storage file must be specified when discovery of storage files is not enabled.");

        // Validate a list of storage files.
        storageFileHelper.validateCreateRequestStorageFiles(
                businessObjectDataStorageFilesCreateRequest.getStorageFiles());
    }
}

From source file:org.finra.herd.service.impl.BusinessObjectDataStorageUnitServiceImpl.java

/**
 * Validates the business object definition column create request. This method also trims the request parameters.
 *
 * @param request the business object data storage unit create request
 *///from w w  w . j  a v a2 s .  c  om
protected void validateBusinessObjectDataStorageUnitCreateRequest(
        BusinessObjectDataStorageUnitCreateRequest request) {
    Assert.notNull(request, "A business object data storage unit create request must be specified.");

    storageUnitHelper.validateBusinessObjectDataStorageUnitKey(request.getBusinessObjectDataStorageUnitKey());

    if (BooleanUtils.isTrue(request.isDiscoverStorageFiles())) {
        // The auto-discovery of storage files is enabled, thus a storage directory is required and storage files cannot be specified.
        Assert.isTrue(request.getStorageDirectory() != null,
                "A storage directory must be specified when discovery of storage files is enabled.");
        Assert.isTrue(CollectionUtils.isEmpty(request.getStorageFiles()),
                "Storage files cannot be specified when discovery of storage files is enabled.");
    } else {
        // Since auto-discovery is disabled, a storage directory or at least one storage file are required for each storage unit.
        Assert.isTrue(
                request.getStorageDirectory() != null || CollectionUtils.isNotEmpty(request.getStorageFiles()),
                "A storage directory or at least one storage file must be specified when discovery of storage files is not enabled.");
    }

    // If storageDirectory element is present in the request, we require it to contain a non-empty directoryPath element.
    if (request.getStorageDirectory() != null) {
        Assert.hasText(request.getStorageDirectory().getDirectoryPath(),
                "A storage directory path must be specified.");
        request.getStorageDirectory().setDirectoryPath(request.getStorageDirectory().getDirectoryPath().trim());
    }

    // Validate a list of storage files, if specified.
    if (CollectionUtils.isNotEmpty(request.getStorageFiles())) {
        storageFileHelper.validateCreateRequestStorageFiles(request.getStorageFiles());
    }
}

From source file:org.finra.herd.service.impl.BusinessObjectDefinitionColumnServiceImpl.java

@NamespacePermission(fields = "#request.businessObjectDefinitionColumnKey.namespace", permissions = {
        NamespacePermissionEnum.WRITE_DESCRIPTIVE_CONTENT, NamespacePermissionEnum.WRITE })
@Override/*from   w  ww  .j  a v  a 2  s  .com*/
public BusinessObjectDefinitionColumn createBusinessObjectDefinitionColumn(
        BusinessObjectDefinitionColumnCreateRequest request) {
    // Validate and trim the business object definition column create request.
    validateBusinessObjectDefinitionColumnCreateRequest(request);

    // Get the business object definition key.
    BusinessObjectDefinitionKey businessObjectDefinitionKey = businessObjectDefinitionHelper
            .getBusinessObjectDefinitionKey(request.getBusinessObjectDefinitionColumnKey());

    // Get the business object definition and ensure it exists.
    BusinessObjectDefinitionEntity businessObjectDefinitionEntity = businessObjectDefinitionDaoHelper
            .getBusinessObjectDefinitionEntity(businessObjectDefinitionKey);

    // Ensure a business object definition column with the specified name doesn't already exist for the business object definition.
    if (businessObjectDefinitionColumnDao.getBusinessObjectDefinitionColumnByBusinessObjectDefinitionColumnName(
            businessObjectDefinitionEntity,
            request.getBusinessObjectDefinitionColumnKey().getBusinessObjectDefinitionColumnName()) != null) {
        throw new AlreadyExistsException(String.format(
                "Unable to create business object definition column with name \"%s\" because it already exists for the business object definition {%s}.",
                request.getBusinessObjectDefinitionColumnKey().getBusinessObjectDefinitionColumnName(),
                businessObjectDefinitionHelper
                        .businessObjectDefinitionKeyToString(businessObjectDefinitionKey)));
    }

    // Retrieve schema column entities from all format instances for the business object definition that match the specified schema column name.
    Collection<SchemaColumnEntity> schemaColumnEntities = schemaColumnDao
            .getSchemaColumns(businessObjectDefinitionEntity, request.getSchemaColumnName());

    // Ensure that exists at least one schema column that matches the specified schema column name.
    if (CollectionUtils.isEmpty(schemaColumnEntities)) {
        if (businessObjectDefinitionEntity.getDescriptiveBusinessObjectFormat() == null) {
            throw new ObjectNotFoundException(String.format(
                    "Unable to create business object definition column because there are no format schema "
                            + "columns with name \"%s\" for the business object definition {%s}.",
                    request.getSchemaColumnName(), businessObjectDefinitionHelper
                            .businessObjectDefinitionKeyToString(businessObjectDefinitionKey)));
        } else {
            throw new ObjectNotFoundException(String.format(
                    "Unable to create business object definition column because there are no format schema "
                            + "columns with name \"%s\" in the descriptive business object format for the business object definition {%s}.",
                    request.getSchemaColumnName(), businessObjectDefinitionHelper
                            .businessObjectDefinitionKeyToString(businessObjectDefinitionKey)));
        }
    }

    // Ensure a business object definition column with the specified schema column name doesn't already exist for this business object definition.
    for (SchemaColumnEntity schemaColumnEntity : schemaColumnEntities) {
        if (schemaColumnEntity.getBusinessObjectDefinitionColumn() != null) {
            throw new AlreadyExistsException(String.format(
                    "Unable to create business object definition column because a business object definition column "
                            + "with schema column name \"%s\" already exists for the business object definition {%s}.",
                    request.getSchemaColumnName(), businessObjectDefinitionHelper
                            .businessObjectDefinitionKeyToString(businessObjectDefinitionKey)));
        }
    }

    // Create a business object definition column entity from the request information.
    BusinessObjectDefinitionColumnEntity businessObjectDefinitionColumnEntity = createBusinessObjectDefinitionColumnEntity(
            businessObjectDefinitionEntity, request);

    // Link schema columns with the business object definition column.
    for (SchemaColumnEntity schemaColumnEntity : schemaColumnEntities) {
        schemaColumnEntity.setBusinessObjectDefinitionColumn(businessObjectDefinitionColumnEntity);
    }

    // Persist the change event entity
    businessObjectDefinitionColumnDaoHelper
            .saveBusinessObjectDefinitionColumnChangeEvents(businessObjectDefinitionColumnEntity);

    // Persist the new entity.
    businessObjectDefinitionColumnEntity = businessObjectDefinitionColumnDao
            .saveAndRefresh(businessObjectDefinitionColumnEntity);

    // Notify the search index that a business object definition must be updated.
    LOGGER.info(
            "Modify the business object definition in the search index associated with the business object definition column being created."
                    + " businessObjectDefinitionId=\"{}\", searchIndexUpdateType=\"{}\"",
            businessObjectDefinitionEntity.getId(), SEARCH_INDEX_UPDATE_TYPE_UPDATE);
    searchIndexUpdateHelper.modifyBusinessObjectDefinitionInSearchIndex(businessObjectDefinitionEntity,
            SEARCH_INDEX_UPDATE_TYPE_UPDATE);

    // Create and return the business object definition column object from the persisted entity.
    return createBusinessObjectDefinitionColumnFromEntity(businessObjectDefinitionColumnEntity, true,
            getValidSearchResponseFields(), false);
}

From source file:org.finra.herd.service.impl.BusinessObjectDefinitionServiceImpl.java

@Override
public BusinessObjectDefinitionSearchResponse searchBusinessObjectDefinitions(
        BusinessObjectDefinitionSearchRequest request, Set<String> fields) {
    // Validate the business object definition search fields.
    validateSearchResponseFields(fields);

    List<TagEntity> tagEntities = new ArrayList<>();

    if (!CollectionUtils.isEmpty(request.getBusinessObjectDefinitionSearchFilters())) {
        // Validate the search request.
        validateBusinessObjectDefinitionSearchRequest(request);

        BusinessObjectDefinitionSearchKey businessObjectDefinitionSearchKey = request
                .getBusinessObjectDefinitionSearchFilters().get(0).getBusinessObjectDefinitionSearchKeys()
                .get(0);/*  w w  w.  ja  v  a  2 s.c o  m*/

        TagEntity tagEntity = tagDaoHelper.getTagEntity(businessObjectDefinitionSearchKey.getTagKey());

        // If includeTagHierarchy is true, get list of children tag entities down the hierarchy of the specified tag.
        tagEntities.add(tagEntity);
        if (BooleanUtils.isTrue(businessObjectDefinitionSearchKey.isIncludeTagHierarchy())) {
            tagEntities.addAll(tagDaoHelper.getTagChildrenEntities(tagEntity));
        }
    }

    // Construct business object search response.
    BusinessObjectDefinitionSearchResponse searchResponse = new BusinessObjectDefinitionSearchResponse();
    List<BusinessObjectDefinition> businessObjectDefinitions = new ArrayList<>();
    searchResponse.setBusinessObjectDefinitions(businessObjectDefinitions);

    // Retrieve all unique business object definition entities and construct a list of business object definitions based on the requested fields.
    for (BusinessObjectDefinitionEntity businessObjectDefinition : ImmutableSet
            .copyOf(businessObjectDefinitionDao.getBusinessObjectDefinitions(tagEntities))) {
        businessObjectDefinitions
                .add(createBusinessObjectDefinitionFromEntity(businessObjectDefinition, fields));
    }

    return searchResponse;
}

From source file:org.finra.herd.service.impl.BusinessObjectDefinitionServiceImpl.java

/**
 * Update and persist the business object definition per specified update request.
 *
 * @param businessObjectDefinitionEntity the business object definition entity
 * @param request the business object definition update request
 *//*ww  w.ja v a  2 s .  c  o m*/
private void updateBusinessObjectDefinitionEntity(BusinessObjectDefinitionEntity businessObjectDefinitionEntity,
        BusinessObjectDefinitionUpdateRequest request) {
    // Update the entity with the new description value.
    businessObjectDefinitionEntity.setDescription(request.getDescription());
    businessObjectDefinitionEntity.setDisplayName(request.getDisplayName());

    // Update the attributes.
    // Load all existing attribute entities in a map with a "lowercase" attribute name as the key for case insensitivity.
    Map<String, BusinessObjectDefinitionAttributeEntity> existingAttributeEntities = new HashMap<>();
    for (BusinessObjectDefinitionAttributeEntity attributeEntity : businessObjectDefinitionEntity
            .getAttributes()) {
        String mapKey = attributeEntity.getName().toLowerCase();
        if (existingAttributeEntities.containsKey(mapKey)) {
            throw new IllegalStateException(String.format(
                    "Found duplicate attribute with name \"%s\" for business object definition {namespace: \"%s\", businessObjectDefinitionName: \"%s\"}.",
                    mapKey, businessObjectDefinitionEntity.getNamespace().getCode(),
                    businessObjectDefinitionEntity.getName()));
        }
        existingAttributeEntities.put(mapKey, attributeEntity);
    }

    // Process the list of attributes to determine that business object definition attribute entities should be created, updated, or deleted.
    List<BusinessObjectDefinitionAttributeEntity> createdAttributeEntities = new ArrayList<>();
    List<BusinessObjectDefinitionAttributeEntity> retainedAttributeEntities = new ArrayList<>();
    if (!CollectionUtils.isEmpty(request.getAttributes())) {
        for (Attribute attribute : request.getAttributes()) {
            // Use a "lowercase" attribute name for case insensitivity.
            String lowercaseAttributeName = attribute.getName().toLowerCase();
            if (existingAttributeEntities.containsKey(lowercaseAttributeName)) {
                // Check if the attribute value needs to be updated.
                BusinessObjectDefinitionAttributeEntity attributeEntity = existingAttributeEntities
                        .get(lowercaseAttributeName);
                if (!StringUtils.equals(attribute.getValue(), attributeEntity.getValue())) {
                    // Update the business object attribute entity.
                    attributeEntity.setValue(attribute.getValue());
                }

                // Add this entity to the list of business object definition attribute entities to be retained.
                retainedAttributeEntities.add(attributeEntity);
            } else {
                // Create a new business object attribute entity.
                BusinessObjectDefinitionAttributeEntity attributeEntity = new BusinessObjectDefinitionAttributeEntity();
                businessObjectDefinitionEntity.getAttributes().add(attributeEntity);
                attributeEntity.setBusinessObjectDefinition(businessObjectDefinitionEntity);
                attributeEntity.setName(attribute.getName());
                attributeEntity.setValue(attribute.getValue());

                // Add this entity to the list of the newly created business object definition attribute entities.
                retainedAttributeEntities.add(attributeEntity);
            }
        }
    }

    // Remove any of the currently existing attribute entities that did not get onto the retained entities list.
    businessObjectDefinitionEntity.getAttributes().retainAll(retainedAttributeEntities);

    // Add all of the newly created business object definition attribute entities.
    businessObjectDefinitionEntity.getAttributes().addAll(createdAttributeEntities);

    // Persist the change event entity
    saveBusinessObjectDefinitionChangeEvents(businessObjectDefinitionEntity);

    // Persist the entity.
    businessObjectDefinitionDao.saveAndRefresh(businessObjectDefinitionEntity);
}

From source file:org.finra.herd.service.impl.JobServiceImpl.java

/**
 * Gets a job by the given jobId, and displays verbose information if verbose flag is true. Does namespace permission check if namespace permissions flag is
 * true.//from   w ww. ja v a2 s.  c o  m
 *
 * @param jobId the job ID
 * @param verbose specifies if verbose mode is enabled or not
 * @param checkNamespacePermissions specifies whether to check namespace permissions or not
 *
 * @return the job information
 */
private Job getJob(String jobId, boolean verbose, boolean checkNamespacePermissions) {
    String jobIdLocal = jobId;

    // Validate and trim required elements
    Assert.hasText(jobIdLocal, "A job Id must be specified.");
    jobIdLocal = jobIdLocal.trim();

    // Get process instance from Activiti runtime.
    ProcessInstance processInstance = activitiService.getProcessInstanceById(jobIdLocal);

    // Get historic process instance.
    HistoricProcessInstance historicProcessInstance = activitiService
            .getHistoricProcessInstanceByProcessInstanceId(jobIdLocal);

    /*
     * Check permissions against namespace of the job.
     * Cannot be done through the annotation because the namespace is not part of the request.
     * TODO refactor this so it gets namespace from JobDefinitionEntity instead of parsing process definition key.
     */
    if (checkNamespacePermissions) {
        String processDefinitionKey = null;
        if (processInstance != null) {
            processDefinitionKey = processInstance.getProcessDefinitionKey();
        } else if (historicProcessInstance != null) {
            processDefinitionKey = activitiService
                    .getProcessDefinitionById(historicProcessInstance.getProcessDefinitionId()).getKey();
        }
        if (processDefinitionKey != null) {
            checkPermissions(processDefinitionKey,
                    new NamespacePermissionEnum[] { NamespacePermissionEnum.READ });
        }
    }

    Job job = new Job();
    job.setId(jobIdLocal);

    if (processInstance == null && historicProcessInstance == null) {
        // Process not found
        throw new ObjectNotFoundException(String.format("Job with Id: \"%s\" doesn't exist.", jobIdLocal));
    } else if (processInstance != null) {
        // Process is still running or suspended.
        job.setStatus(processInstance.isSuspended() ? JobStatusEnum.SUSPENDED : JobStatusEnum.RUNNING);

        // Check if there are errors.
        List<org.activiti.engine.runtime.Job> erroredJobs = activitiService
                .getJobsWithExceptionByProcessInstanceId(processInstance.getProcessInstanceId());

        if (!CollectionUtils.isEmpty(erroredJobs)) {
            // Errors found.
            List<WorkflowError> workflowErrors = new ArrayList<>();

            for (org.activiti.engine.runtime.Job erroredJob : erroredJobs) {
                WorkflowError workflowError = new WorkflowError();
                workflowError.setErrorMessage(erroredJob.getExceptionMessage());
                workflowError.setRetriesLeft(erroredJob.getRetries());
                workflowError.setErrorStackTrace(activitiService.getJobExceptionStacktrace(erroredJob.getId()));
                workflowErrors.add(workflowError);
            }
            job.setWorkflowErrors(workflowErrors);
        }

        if (processInstance.getActivityId() != null) {
            // Set current workflow step.
            WorkflowStep currentStep = new WorkflowStep();
            currentStep.setId(processInstance.getActivityId());
            job.setCurrentWorkflowStep(currentStep);
        }

        // Set the workflow variables.
        populateWorkflowParameters(job, processInstance.getProcessVariables());

        // If verbose, set activiti workflow xml.
        if (verbose) {
            populateActivitiXml(job, processInstance.getProcessDefinitionId());
        }
    } else {
        // Process completed
        job.setStatus(JobStatusEnum.COMPLETED);

        // Set the workflow variables.
        populateWorkflowParameters(job, historicProcessInstance.getProcessVariables());

        job.setDeleteReason(historicProcessInstance.getDeleteReason());

        // If verbose, set activiti workflow xml.
        if (verbose) {
            populateActivitiXml(job, historicProcessInstance.getProcessDefinitionId());
        }
    }

    if (historicProcessInstance != null) {
        // If verbose, set completed steps.
        if (verbose) {
            populateCompletedActivitiSteps(job,
                    activitiService.getHistoricActivityInstancesByProcessInstanceId(jobIdLocal));
        }

        // Set the start time always since all jobs will have a start time.
        job.setStartTime(HerdDateUtils.getXMLGregorianCalendarValue(historicProcessInstance.getStartTime()));

        // Set the end time if the historic process instance has it set (the job is completed).
        if (historicProcessInstance.getEndTime() != null) {
            job.setEndTime(HerdDateUtils.getXMLGregorianCalendarValue(historicProcessInstance.getEndTime()));
        }
    }

    return job;
}

From source file:org.finra.herd.service.impl.JobServiceImpl.java

/**
 * Converts the given list of {@link Parameter} into a map.
 *
 * @param parameters list of {@link Parameter}
 *
 * @return map of key-values/*from ww w .j a v a 2  s . co m*/
 */
private Map<String, Object> toMap(List<Parameter> parameters) {
    Map<String, Object> map = new HashMap<>();
    if (!CollectionUtils.isEmpty(parameters)) {
        for (Parameter parameter : parameters) {
            map.put(parameter.getName(), parameter.getValue());
        }
    }
    return map;
}

From source file:org.finra.herd.service.impl.NamespaceIamRoleAuthorizationServiceImpl.java

/**
 * Gets a list of NamespaceIamRoleAuthorizationEntities for the given namespace. Throws a ObjectNotFoundException if the result is empty.
 *
 * @param namespaceEntity The namespace entity
 *
 * @return List of NamespaceIamRoleAuthorizationEntity
 *///from  w w w.j a  va  2  s .c o  m
private List<NamespaceIamRoleAuthorizationEntity> getNamespaeIamRoleAuthorizationEntities(
        NamespaceEntity namespaceEntity) {
    List<NamespaceIamRoleAuthorizationEntity> namespaceIamRoleAuthorizationEntities = namespaceIamRoleAuthorizationDao
            .getNamespaceIamRoleAuthorizations(namespaceEntity);

    if (CollectionUtils.isEmpty(namespaceIamRoleAuthorizationEntities)) {
        throw new ObjectNotFoundException(
                String.format("Namespace IAM role authorizations for namespace \"%s\" do not exist",
                        namespaceEntity.getCode()));
    }
    return namespaceIamRoleAuthorizationEntities;
}

From source file:org.finra.herd.service.impl.UserNamespaceAuthorizationServiceImpl.java

/**
 * Validates a list of namespace permissions.
 *
 * @param namespacePermissions the list of namespace permissions
 *
 * @throws IllegalArgumentException if any validation errors were found
 *///from  www  .ja va2 s. c o  m
public void validateNamespacePermissions(List<NamespacePermissionEnum> namespacePermissions)
        throws IllegalArgumentException {
    Assert.isTrue(!CollectionUtils.isEmpty(namespacePermissions), "Namespace permissions must be specified.");

    // Ensure permission isn't a duplicate by using a hash set with uppercase permission values for case insensitivity.
    Set<NamespacePermissionEnum> validatedNamespacePermissions = new HashSet<>();

    // Validate the permissions.
    for (NamespacePermissionEnum namespacePermission : namespacePermissions) {
        // Fail if duplicate permission value is detected.
        if (validatedNamespacePermissions.contains(namespacePermission)) {
            throw new IllegalArgumentException(String.format("Duplicate namespace permission \"%s\" is found.",
                    namespacePermission.value()));
        }

        validatedNamespacePermissions.add(namespacePermission);
    }
}