Example usage for org.springframework.util Assert notEmpty

List of usage examples for org.springframework.util Assert notEmpty

Introduction

In this page you can find the example usage for org.springframework.util Assert notEmpty.

Prototype

public static void notEmpty(@Nullable Map<?, ?> map, Supplier<String> messageSupplier) 

Source Link

Document

Assert that a Map contains entries; that is, it must not be null and must contain at least one entry.

Usage

From source file:org.eclipse.gemini.blueprint.service.exporter.support.OsgiServiceFactoryBean.java

/**
 * Registration method.//from ww  w.  j  a  v a 2 s . c o  m
 * 
 * @param classes
 * @param serviceProperties
 * @return the ServiceRegistration
 */
ServiceRegistration registerService(Class<?>[] classes, final Dictionary serviceProperties) {
    Assert.notEmpty(classes, "at least one class has to be specified for exporting "
            + "(if autoExport is enabled then maybe the object doesn't implement any interface)");

    // create an array of classnames (used for registering the service)
    final String[] names = ClassUtils.toStringArray(classes);
    // sort the names in alphabetical order (eases debugging)
    Arrays.sort(names);

    log.info("Publishing service under classes [" + ObjectUtils.nullSafeToString(names) + "]");

    ServiceFactory serviceFactory = new PublishingServiceFactory(resolver, classes,
            (ExportContextClassLoaderEnum.SERVICE_PROVIDER.equals(contextClassLoader)), classLoader,
            aopClassLoader, bundleContext);

    if (isBeanBundleScoped())
        serviceFactory = new OsgiBundleScope.BundleScopeServiceFactory(serviceFactory);

    if (System.getSecurityManager() != null) {
        AccessControlContext acc = SecurityUtils.getAccFrom(beanFactory);
        final ServiceFactory serviceFactoryFinal = serviceFactory;
        return AccessController.doPrivileged(new PrivilegedAction<ServiceRegistration>() {
            public ServiceRegistration run() {
                return bundleContext.registerService(names, serviceFactoryFinal, serviceProperties);
            }
        }, acc);
    } else {
        return bundleContext.registerService(names, serviceFactory, serviceProperties);
    }
}

From source file:org.finra.dm.service.helper.BusinessObjectDataHelper.java

/**
 * Builds a list of partition values from a "partition value range" partition value filter option. The list of partition values will come from the expected
 * partition values table for values within the specified range. The list will be ordered ascending.
 *
 * @param partitionValueRange the partition value range
 * @param businessObjectFormatEntity the business object format entity
 *
 * @return the unique and sorted partition value list
 *//*from   www . j a  v  a  2s  .c  o  m*/
private List<String> processPartitionValueRangeFilterOption(PartitionValueRange partitionValueRange,
        BusinessObjectFormatEntity businessObjectFormatEntity) {
    List<String> resultPartitionValues = new ArrayList<>();

    Assert.notNull(businessObjectFormatEntity.getPartitionKeyGroup(), String.format(
            "A partition key group, which is required to use partition value ranges, is not specified for the business object format {%s}.",
            dmDaoHelper.businessObjectFormatEntityAltKeyToString(businessObjectFormatEntity)));

    List<ExpectedPartitionValueEntity> expectedPartitionValueEntities = dmDao
            .getExpectedPartitionValuesByGroupAndRange(
                    businessObjectFormatEntity.getPartitionKeyGroup().getPartitionKeyGroupName(),
                    partitionValueRange);

    // Populate the partition values returned from the range query.
    for (ExpectedPartitionValueEntity expectedPartitionValueEntity : expectedPartitionValueEntities) {
        String partitionValue = expectedPartitionValueEntity.getPartitionValue();

        // Validate that expected partition value does not match to one of the partition value tokens.
        Assert.isTrue(
                !partitionValue.equals(BusinessObjectDataService.MAX_PARTITION_VALUE_TOKEN)
                        && !partitionValue.equals(BusinessObjectDataService.MIN_PARTITION_VALUE_TOKEN),
                "A partition value token cannot be specified as one of the expected partition values.");

        resultPartitionValues.add(partitionValue);
    }

    // Validate that our partition value range results in a non-empty partition value list.
    Assert.notEmpty(resultPartitionValues,
            String.format("Partition value range [\"%s\", \"%s\"] contains no valid partition values.",
                    partitionValueRange.getStartPartitionValue(), partitionValueRange.getEndPartitionValue()));

    return resultPartitionValues;
}

From source file:org.finra.dm.service.helper.DmHelper.java

/**
 * Validates an EMR cluster definition configuration.
 *
 * @param emrClusterDefinition the EMR cluster definition configuration
 *
 * @throws IllegalArgumentException if any validation errors were found
 *///from   w ww  .jav a  2 s.  c  om
public void validateEmrClusterDefinitionConfiguration(EmrClusterDefinition emrClusterDefinition)
        throws IllegalArgumentException {
    Assert.notNull(emrClusterDefinition, "An EMR cluster definition configuration must be specified.");

    Assert.isTrue(StringUtils.isNotBlank(emrClusterDefinition.getSubnetId()), "Subnet ID must be specified");
    for (String token : emrClusterDefinition.getSubnetId().split(",")) {
        Assert.isTrue(StringUtils.isNotBlank(token), "No blank is allowed in the list of subnet IDs");
    }

    Assert.notNull(emrClusterDefinition.getInstanceDefinitions(), "Instance definitions must be specified.");

    // Check master instances.
    Assert.notNull(emrClusterDefinition.getInstanceDefinitions().getMasterInstances(),
            "Master instances must be specified.");
    validateMasterInstanceDefinition(emrClusterDefinition.getInstanceDefinitions().getMasterInstances());

    // Check core instances.
    Assert.notNull(emrClusterDefinition.getInstanceDefinitions().getCoreInstances(),
            "Core instances must be specified.");
    validateInstanceDefinition("core", emrClusterDefinition.getInstanceDefinitions().getCoreInstances());

    // Check task instances
    if (emrClusterDefinition.getInstanceDefinitions().getTaskInstances() != null) {
        validateInstanceDefinition("task", emrClusterDefinition.getInstanceDefinitions().getTaskInstances());
    }

    // Check that total number of instances does not exceed the max allowed.
    int maxEmrInstanceCount = configurationHelper.getProperty(ConfigurationValue.MAX_EMR_INSTANCES_COUNT,
            Integer.class);
    if (maxEmrInstanceCount > 0) {
        int instancesRequested = emrClusterDefinition.getInstanceDefinitions().getMasterInstances()
                .getInstanceCount()
                + emrClusterDefinition.getInstanceDefinitions().getCoreInstances().getInstanceCount();
        if (emrClusterDefinition.getInstanceDefinitions().getTaskInstances() != null) {
            instancesRequested += emrClusterDefinition.getInstanceDefinitions().getTaskInstances()
                    .getInstanceCount();
        }

        Assert.isTrue((maxEmrInstanceCount >= instancesRequested),
                "Total number of instances requested can not exceed : " + maxEmrInstanceCount);
    }

    // Validate node tags including checking for required tags and detecting any duplicate node tag names in case sensitive manner.
    Assert.notEmpty(emrClusterDefinition.getNodeTags(), "Node tags must be specified.");
    HashSet<String> nodeTagNameValidationSet = new HashSet<>();
    for (NodeTag nodeTag : emrClusterDefinition.getNodeTags()) {
        Assert.hasText(nodeTag.getTagName(), "A node tag name must be specified.");
        Assert.hasText(nodeTag.getTagValue(), "A node tag value must be specified.");
        Assert.isTrue(!nodeTagNameValidationSet.contains(nodeTag.getTagName()),
                String.format("Duplicate node tag \"%s\" is found.", nodeTag.getTagName()));
        nodeTagNameValidationSet.add(nodeTag.getTagName());
    }

    // Validate the mandatory AWS tags are there
    for (String mandatoryTag : dmStringHelper.splitStringWithDefaultDelimiter(
            configurationHelper.getProperty(ConfigurationValue.MANDATORY_AWS_TAGS))) {
        Assert.isTrue(nodeTagNameValidationSet.contains(mandatoryTag),
                String.format("Mandatory AWS tag not specified: \"%s\"", mandatoryTag));
    }
}

From source file:org.finra.dm.service.helper.Hive13DdlGenerator.java

/**
 * Generates and append to the string builder the create table Hive 13 DDL as per specified parameters.
 */// w w w  . jav a  2s. c o m
private String generateCreateTableDdlHelper(BusinessObjectFormatEntity businessObjectFormatEntity,
        CustomDdlEntity customDdlEntity, Boolean isPartitioned, String tableName,
        Boolean includeDropTableStatement, Boolean includeIfNotExistsOption, Boolean allowMissingData,
        List<List<String>> partitionFilters, Integer businessObjectFormatVersion,
        Integer businessObjectDataVersion, StorageEntity storageEntity, String s3BucketName) {
    // TODO: We might want to consider using a template engine such as Velocity to generate this DDL so we don't wind up just doing string manipulation.

    StringBuilder sb = new StringBuilder();

    // For custom DDL, we would need to substitute the custom DDL tokens with their relative values.
    HashMap<String, String> replacements = new HashMap<>();

    // Validate that partition values passed in the list of partition filters do not contain '/' character.
    if (isPartitioned && !CollectionUtils.isEmpty(partitionFilters)) {
        // Validate that partition values do not contain '/' characters.
        for (List<String> partitionFilter : partitionFilters) {
            for (String partitionValue : partitionFilter) {
                Assert.doesNotContain(partitionValue, "/", String
                        .format("Partition value \"%s\" can not contain a '/' character.", partitionValue));
            }
        }
    }

    // Get business object format model object to directly access schema columns and partitions.
    BusinessObjectFormat businessObjectFormat = businessObjectFormatHelper
            .createBusinessObjectFormatFromEntity(businessObjectFormatEntity);

    // Validate that we have at least one column specified in the business object format schema.
    Assert.notEmpty(businessObjectFormat.getSchema().getColumns(),
            String.format("No schema columns specified for business object format {%s}.",
                    dmDaoHelper.businessObjectFormatEntityAltKeyToString(businessObjectFormatEntity)));

    if (isPartitioned) {
        // Validate that we have at least one partition column specified in the business object format schema.
        Assert.notEmpty(businessObjectFormat.getSchema().getPartitions(),
                String.format("No schema partitions specified for business object format {%s}.",
                        dmDaoHelper.businessObjectFormatEntityAltKeyToString(businessObjectFormatEntity)));

        // Validate that partition column names do not contain '/' characters.
        for (SchemaColumn partitionColumn : businessObjectFormat.getSchema().getPartitions()) {
            Assert.doesNotContain(partitionColumn.getName(), "/", String.format(
                    "Partition column name \"%s\" can not contain a '/' character. Business object format: {%s}",
                    partitionColumn.getName(),
                    dmDaoHelper.businessObjectFormatEntityAltKeyToString(businessObjectFormatEntity)));
        }
    }

    // Add drop table if requested.
    if (includeDropTableStatement != null && includeDropTableStatement) {
        sb.append(String.format("DROP TABLE IF EXISTS `%s`;\n\n", tableName));
    }

    // Depending on the flag, prepare "if not exists" option text or leave it an empty string.
    String ifNotExistsOption = includeIfNotExistsOption != null && includeIfNotExistsOption ? "IF NOT EXISTS "
            : "";

    // Only generate the create table DDL statement, if custom DDL was not specified.
    if (customDdlEntity == null) {
        generateStandardBaseDdl(businessObjectFormatEntity, isPartitioned, tableName, sb, businessObjectFormat,
                ifNotExistsOption);
    } else {
        // Use the custom DDL in place of the create table statement.
        sb.append(String.format("%s\n\n", customDdlEntity.getDdl()));

        // We need to substitute the relative custom DDL token with an actual table name.
        replacements.put(TABLE_NAME_CUSTOM_DDL_TOKEN, tableName);
    }

    // Add alter table statements only if the list of partition filters is not empty - this is applicable to generating DDL for business object data only.
    if (!CollectionUtils.isEmpty(partitionFilters)) {
        processPartitionFiltersForGenerateDdl(businessObjectFormatEntity, customDdlEntity, isPartitioned,
                tableName, allowMissingData, partitionFilters, businessObjectFormatVersion,
                businessObjectDataVersion, storageEntity, s3BucketName, sb, replacements, businessObjectFormat,
                ifNotExistsOption);
    }
    // Add a location statement with a token if this is format dll that does not use custom ddl.
    else if (!isPartitioned && customDdlEntity == null) {
        // Since custom DDL is not specified, there are no partition values, and this table is not partitioned, add a LOCATION clause with a token.
        sb.append(String.format("LOCATION '%s';", NON_PARTITIONED_TABLE_LOCATION_CUSTOM_DDL_TOKEN));
    }

    // Trim to remove unnecessary end-of-line characters, if any, from the end of the generated DDL.
    String resultDdl = sb.toString().trim();

    // For custom DDL, substitute the relative custom DDL tokens with their values.
    if (customDdlEntity != null) {
        for (Map.Entry<String, String> entry : replacements.entrySet()) {
            String token = entry.getKey();
            String value = entry.getValue();
            resultDdl = resultDdl.replaceAll(Pattern.quote(token), value);
        }
    }

    return resultDdl;
}

From source file:org.finra.dm.service.impl.BusinessObjectDataNotificationRegistrationServiceImpl.java

/**
 * Validates the business object data notification actions. This method also trims the notification action parameters.
 *
 * @param jobActions the list of notification job actions
 *///from   w ww  . ja  va2  s.  co m
private void validateNotificationActions(List<JobAction> jobActions) {
    Assert.notEmpty(jobActions, "At least one notification action must be specified.");

    // Ensure job action isn't a duplicate by using a hash set with lowercase job definition key values for case insensitivity.
    Set<JobAction> validatedJobActionsSet = new LinkedHashSet<>();
    for (JobAction jobAction : jobActions) {
        Assert.hasText(jobAction.getNamespace(), "A job action namespace must be specified.");
        jobAction.setNamespace(jobAction.getNamespace().trim());

        Assert.hasText(jobAction.getJobName(), "A job action job name must be specified.");
        jobAction.setJobName(jobAction.getJobName().trim());

        // Create a special version of the job action with the relative job definition key values in lowercase.
        JobAction lowercaseJobDefinitionKey = new JobAction();
        lowercaseJobDefinitionKey.setNamespace(jobAction.getNamespace().toLowerCase());
        lowercaseJobDefinitionKey.setJobName(jobAction.getJobName().toLowerCase());

        if (validatedJobActionsSet.contains(lowercaseJobDefinitionKey)) {
            throw new IllegalArgumentException(
                    String.format("Duplicate job action {namespace: \"%s\", jobName: \"%s\"} found.",
                            jobAction.getNamespace(), jobAction.getJobName()));
        }

        validatedJobActionsSet.add(lowercaseJobDefinitionKey);
    }
}

From source file:org.finra.dm.service.impl.BusinessObjectDataServiceImpl.java

/**
 * Retrieves the DDL to initialize the specified type of the database system to perform queries for a range of requested business object data in the
 * specified storage.//from  ww w. j  a  v a  2 s  .c  o  m
 *
 * @param request the business object data DDL request
 * @param skipRequestValidation specifies whether to skip the request validation and trimming
 *
 * @return the business object data DDL information
 */
protected BusinessObjectDataDdl generateBusinessObjectDataDdlImpl(BusinessObjectDataDdlRequest request,
        boolean skipRequestValidation) {
    // Perform the validation.
    if (!skipRequestValidation) {
        validateBusinessObjectDataDdlRequest(request);
    }

    // If namespace is not specified, get the namespace code by locating the legacy business object definition.
    if (StringUtils.isBlank(request.getNamespace())) {
        request.setNamespace(dmDaoHelper.getNamespaceCode(request.getBusinessObjectDefinitionName()));
    }

    // Get the business object format entity for the specified parameters and make sure it exists.
    // Please note that when format version is not specified, we should get back the latest format version.
    BusinessObjectFormatEntity businessObjectFormatEntity = dmDaoHelper
            .getBusinessObjectFormatEntity(new BusinessObjectFormatKey(request.getNamespace(),
                    request.getBusinessObjectDefinitionName(), request.getBusinessObjectFormatUsage(),
                    request.getBusinessObjectFormatFileType(), request.getBusinessObjectFormatVersion()));

    // Validate that format has schema information.
    Assert.notEmpty(businessObjectFormatEntity.getSchemaColumns(), String.format(
            "Business object format with namespace \"%s\", business object definition name \"%s\", format usage \"%s\", format file type \"%s\","
                    + " and format version \"%s\" doesn't have schema information.",
            businessObjectFormatEntity.getBusinessObjectDefinition().getNamespace().getCode(),
            businessObjectFormatEntity.getBusinessObjectDefinition().getName(),
            businessObjectFormatEntity.getUsage(), businessObjectFormatEntity.getFileType().getCode(),
            businessObjectFormatEntity.getBusinessObjectFormatVersion()));

    // If it was specified, retrieve the custom DDL and ensure it exists.
    CustomDdlEntity customDdlEntity = null;
    if (StringUtils.isNotBlank(request.getCustomDdlName())) {
        CustomDdlKey customDdlKey = new CustomDdlKey(
                businessObjectFormatEntity.getBusinessObjectDefinition().getNamespace().getCode(),
                businessObjectFormatEntity.getBusinessObjectDefinition().getName(),
                businessObjectFormatEntity.getUsage(), businessObjectFormatEntity.getFileType().getCode(),
                businessObjectFormatEntity.getBusinessObjectFormatVersion(), request.getCustomDdlName());
        customDdlEntity = dmDaoHelper.getCustomDdlEntity(customDdlKey);
    }

    // Get the storage entity and validate that it exists.
    StorageEntity storageEntity = dmDaoHelper.getStorageEntity(request.getStorageName());

    // Only S3 storage platform is currently supported.
    Assert.isTrue(storageEntity.getStoragePlatform().getName().equals(StoragePlatformEntity.S3), String.format(
            "Cannot generate DDL for \"%s\" storage platform.", storageEntity.getStoragePlatform().getName()));

    // Get S3 bucket name.  Please note that since this value is required we pass a "true" flag.
    String s3BucketName = dmDaoHelper
            .getStorageAttributeValueByName(StorageAttributeEntity.ATTRIBUTE_BUCKET_NAME, storageEntity, true);

    // Create and initialize a business object data DDL object instance.
    BusinessObjectDataDdl businessObjectDataDdl = createBusinessObjectDataDdl(request);
    businessObjectDataDdl.setDdl(
            ddlGeneratorFactory.getDdlGenerator(request.getOutputFormat()).generateCreateTableDdl(request,
                    businessObjectFormatEntity, customDdlEntity, storageEntity, s3BucketName));

    return businessObjectDataDdl;
}

From source file:org.finra.dm.service.impl.BusinessObjectDataServiceImpl.java

/**
 * Validates a list of partition value filters or a standalone partition filter.  This method makes sure that a partition value filter contains exactly one
 * partition value range or a non-empty partition value list.  This method also makes sure that there is no more than one partition value range specified
 * across all partition value filters.//from  w w w.  ja v a  2  s .  c om
 *
 * @param partitionValueFilters the list of partition value filters to validate
 * @param standalonePartitionValueFilter the standalone partition value filter to validate
 * @param allowPartitionValueTokens specifies whether the partition value filter is allowed to contain partition value tokens
 */
private void validatePartitionValueFilters(List<PartitionValueFilter> partitionValueFilters,
        PartitionValueFilter standalonePartitionValueFilter, boolean allowPartitionValueTokens) {
    // Make sure that request does not contain both a list of partition value filters and a standalone partition value filter.
    Assert.isTrue(partitionValueFilters == null || standalonePartitionValueFilter == null,
            "A list of partition value filters and a standalone partition value filter cannot be both specified.");

    List<PartitionValueFilter> partitionValueFiltersToValidate = new ArrayList<>();

    if (partitionValueFilters != null) {
        partitionValueFiltersToValidate.addAll(partitionValueFilters);
    }

    if (standalonePartitionValueFilter != null) {
        partitionValueFiltersToValidate.add(standalonePartitionValueFilter);
    }

    // Make sure that at least one partition value filter is specified.
    Assert.notEmpty(partitionValueFiltersToValidate, "At least one partition value filter must be specified.");

    // Validate and trim partition value filters.
    int partitionValueRangesCount = 0;
    for (PartitionValueFilter partitionValueFilter : partitionValueFiltersToValidate) {
        // Partition key is required when request contains a partition value filter list.
        if (partitionValueFilters != null) {
            Assert.hasText(partitionValueFilter.getPartitionKey(), "A partition key must be specified.");
        }

        // Trim partition key value.
        if (StringUtils.isNotBlank(partitionValueFilter.getPartitionKey())) {
            partitionValueFilter.setPartitionKey(partitionValueFilter.getPartitionKey().trim());
        }

        PartitionValueRange partitionValueRange = partitionValueFilter.getPartitionValueRange();
        List<String> partitionValues = partitionValueFilter.getPartitionValues();
        LatestBeforePartitionValue latestBeforePartitionValue = partitionValueFilter
                .getLatestBeforePartitionValue();
        LatestAfterPartitionValue latestAfterPartitionValue = partitionValueFilter
                .getLatestAfterPartitionValue();

        // Validate that we have exactly one partition filter option specified.
        List<Boolean> partitionFilterOptions = Arrays.asList(partitionValueRange != null,
                partitionValues != null, latestBeforePartitionValue != null, latestAfterPartitionValue != null);
        Assert.isTrue(Collections.frequency(partitionFilterOptions, Boolean.TRUE) == 1,
                "Exactly one partition value filter option must be specified.");

        if (partitionValueRange != null) {
            // A "partition value range" filter option is specified.

            // Only one partition value range is allowed across all partition value filters.
            partitionValueRangesCount++;
            Assert.isTrue(partitionValueRangesCount < 2, "Cannot specify more than one partition value range.");

            // Validate start partition value for the partition value range.
            Assert.hasText(partitionValueRange.getStartPartitionValue(),
                    "A start partition value for the partition value range must be specified.");
            partitionValueRange.setStartPartitionValue(partitionValueRange.getStartPartitionValue().trim());

            // Validate end partition value for the partition value range.
            Assert.hasText(partitionValueRange.getEndPartitionValue(),
                    "An end partition value for the partition value range must be specified.");
            partitionValueRange.setEndPartitionValue(partitionValueRange.getEndPartitionValue().trim());

            // Validate that partition value tokens are not specified as start and end partition values.
            // This check is required, regardless if partition value tokens are allowed or not.
            Assert.isTrue(
                    !partitionValueRange.getStartPartitionValue().equals(MAX_PARTITION_VALUE_TOKEN)
                            && !partitionValueRange.getStartPartitionValue().equals(MIN_PARTITION_VALUE_TOKEN)
                            && !partitionValueRange.getEndPartitionValue().equals(MAX_PARTITION_VALUE_TOKEN)
                            && !partitionValueRange.getEndPartitionValue().equals(MIN_PARTITION_VALUE_TOKEN),
                    "A partition value token cannot be specified with a partition value range.");

            // Using string compare, validate that start partition value is less than or equal to end partition value.
            Assert.isTrue(
                    partitionValueRange.getStartPartitionValue()
                            .compareTo(partitionValueRange.getEndPartitionValue()) <= 0,
                    String.format(
                            "The start partition value \"%s\" cannot be greater than the end partition value \"%s\".",
                            partitionValueRange.getStartPartitionValue(),
                            partitionValueRange.getEndPartitionValue()));
        } else if (partitionValues != null) {
            // A "partition value list" filter option is specified.

            // Validate that the list contains at least one partition value.
            Assert.isTrue(!partitionValues.isEmpty(), "At least one partition value must be specified.");

            for (int i = 0; i < partitionValues.size(); i++) {
                String partitionValue = partitionValues.get(i);
                Assert.hasText(partitionValue, "A partition value must be specified.");
                partitionValue = partitionValue.trim();

                // When partition value tokens are not allowed, validate that they are not specified as one of partition values.
                if (!allowPartitionValueTokens) {
                    Assert.isTrue(
                            !partitionValue.equals(MAX_PARTITION_VALUE_TOKEN)
                                    && !partitionValue.equals(MIN_PARTITION_VALUE_TOKEN),
                            "A partition value token cannot be specified as one of partition values.");
                }

                partitionValues.set(i, partitionValue);
            }
        } else if (latestBeforePartitionValue != null) {
            // A "latest before partition value" filter option is specified.
            Assert.hasText(latestBeforePartitionValue.getPartitionValue(),
                    "A partition value must be specified.");
            latestBeforePartitionValue.setPartitionValue(latestBeforePartitionValue.getPartitionValue().trim());
        } else {
            // A "latest after partition value" filter option is specified.
            Assert.hasText(latestAfterPartitionValue.getPartitionValue(),
                    "A partition value must be specified.");
            latestAfterPartitionValue.setPartitionValue(latestAfterPartitionValue.getPartitionValue().trim());
        }
    }
}

From source file:org.finra.dm.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
 *///from  w w w.j av a2 s . c  o  m
private void validateBusinessObjectDataStorageFilesCreateRequest(
        BusinessObjectDataStorageFilesCreateRequest businessObjectDataStorageFilesCreateRequest) {
    if (businessObjectDataStorageFilesCreateRequest.getNamespace() != null) {
        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 = dmHelper
            .getCollectionSize(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());

    Assert.notEmpty(businessObjectDataStorageFilesCreateRequest.getStorageFiles(),
            "At least one storage file must be specified.");

    // Validate each storage file in the request.
    Set<String> storageFilePathValidationSet = new HashSet<>();
    for (StorageFile storageFile : businessObjectDataStorageFilesCreateRequest.getStorageFiles()) {
        Assert.hasText(storageFile.getFilePath(), "A file path must be specified.");
        storageFile.setFilePath(storageFile.getFilePath().trim());
        Assert.notNull(storageFile.getFileSizeBytes(), "A file size must be specified.");

        // Ensure row count is positive.
        if (storageFile.getRowCount() != null) {
            Assert.isTrue(storageFile.getRowCount() >= 0,
                    "File \"" + storageFile.getFilePath() + "\" has a row count which is < 0.");
        }

        // Check for duplicates.
        if (storageFilePathValidationSet.contains(storageFile.getFilePath())) {
            throw new IllegalArgumentException(
                    String.format("Duplicate storage file found: %s", storageFile.getFilePath()));
        }
        storageFilePathValidationSet.add(storageFile.getFilePath());
    }
}

From source file:org.finra.dm.service.impl.BusinessObjectFormatServiceImpl.java

/**
 * Retrieves the DDL to initialize the specified type of the database system (e.g. Hive) by creating a table for the requested business object format.
 *
 * @param request the business object format DDL request
 * @param skipRequestValidation specifies whether to skip the request validation and trimming
 *
 * @return the business object format DDL information
 *///from w  ww  .  ja  va 2 s.  c o m
protected BusinessObjectFormatDdl generateBusinessObjectFormatDdlImpl(BusinessObjectFormatDdlRequest request,
        boolean skipRequestValidation) {
    // Perform the validation.
    if (!skipRequestValidation) {
        validateBusinessObjectFormatDdlRequest(request);
    }

    // Get the business object format entity for the specified parameters and make sure it exists.
    // Please note that when format version is not specified, we should get back the latest format version.
    BusinessObjectFormatEntity businessObjectFormatEntity = dmDaoHelper
            .getBusinessObjectFormatEntity(new BusinessObjectFormatKey(request.getNamespace(),
                    request.getBusinessObjectDefinitionName(), request.getBusinessObjectFormatUsage(),
                    request.getBusinessObjectFormatFileType(), request.getBusinessObjectFormatVersion()));

    // Get business object format key.
    BusinessObjectFormatKey businessObjectFormatKey = dmDaoHelper
            .getBusinessObjectFormatKey(businessObjectFormatEntity);

    // Validate that format has schema information.
    Assert.notEmpty(businessObjectFormatEntity.getSchemaColumns(), String.format(
            "Business object format with namespace \"%s\", business object definition name \"%s\", format usage \"%s\", format file type \"%s\","
                    + " and format version \"%s\" doesn't have schema information.",
            businessObjectFormatKey.getNamespace(), businessObjectFormatKey.getBusinessObjectDefinitionName(),
            businessObjectFormatKey.getBusinessObjectFormatUsage(),
            businessObjectFormatKey.getBusinessObjectFormatFileType(),
            businessObjectFormatKey.getBusinessObjectFormatVersion()));

    // If it was specified, retrieve the custom DDL and ensure it exists.
    CustomDdlEntity customDdlEntity = null;
    if (StringUtils.isNotBlank(request.getCustomDdlName())) {
        customDdlEntity = dmDaoHelper
                .getCustomDdlEntity(new CustomDdlKey(businessObjectFormatKey.getNamespace(),
                        businessObjectFormatKey.getBusinessObjectDefinitionName(),
                        businessObjectFormatKey.getBusinessObjectFormatUsage(),
                        businessObjectFormatKey.getBusinessObjectFormatFileType(),
                        businessObjectFormatKey.getBusinessObjectFormatVersion(), request.getCustomDdlName()));
    }

    // Create business object format DDL object instance.
    BusinessObjectFormatDdl businessObjectFormatDdl = new BusinessObjectFormatDdl();
    businessObjectFormatDdl.setNamespace(businessObjectFormatKey.getNamespace());
    businessObjectFormatDdl
            .setBusinessObjectDefinitionName(businessObjectFormatKey.getBusinessObjectDefinitionName());
    businessObjectFormatDdl
            .setBusinessObjectFormatUsage(businessObjectFormatKey.getBusinessObjectFormatUsage());
    businessObjectFormatDdl
            .setBusinessObjectFormatFileType(businessObjectFormatKey.getBusinessObjectFormatFileType());
    businessObjectFormatDdl
            .setBusinessObjectFormatVersion(businessObjectFormatKey.getBusinessObjectFormatVersion());
    businessObjectFormatDdl.setOutputFormat(request.getOutputFormat());
    businessObjectFormatDdl.setTableName(request.getTableName());
    businessObjectFormatDdl.setCustomDdlName(
            customDdlEntity != null ? customDdlEntity.getCustomDdlName() : request.getCustomDdlName());
    businessObjectFormatDdl.setDdl(ddlGeneratorFactory.getDdlGenerator(request.getOutputFormat())
            .generateCreateTableDdl(request, businessObjectFormatEntity, customDdlEntity));

    // Return business object format DDL.
    return businessObjectFormatDdl;
}

From source file:org.finra.dm.service.impl.EmrServiceImpl.java

/**
 * Validates the add groups to EMR cluster master create request. This method also trims request parameters.
 *
 * @param request the request.//from   w  w w .ja  v  a  2s  . c om
 *
 * @throws IllegalArgumentException if any validation errors were found.
 */
private void validateAddSecurityGroupsToClusterMasterRequest(EmrMasterSecurityGroupAddRequest request)
        throws IllegalArgumentException {
    // Validate required elements
    Assert.hasText(request.getNamespace(), "A namespace must be specified.");
    Assert.hasText(request.getEmrClusterDefinitionName(), "An EMR cluster definition name must be specified.");
    Assert.hasText(request.getEmrClusterName(), "An EMR cluster name must be specified.");

    Assert.notEmpty(request.getSecurityGroupIds(), "At least one security group must be specified.");
    for (String securityGroup : request.getSecurityGroupIds()) {
        Assert.hasText(securityGroup, "A security group value must be specified.");
    }

    // Remove leading and trailing spaces.
    request.setNamespace(request.getNamespace().trim());
    request.setEmrClusterDefinitionName(request.getEmrClusterDefinitionName().trim());
    request.setEmrClusterName(request.getEmrClusterName().trim());
    String[] trimmedGroups = new String[request.getSecurityGroupIds().size()];
    trimmedGroups = StringUtils.trimArrayElements(request.getSecurityGroupIds().toArray(trimmedGroups));
    request.setSecurityGroupIds(Arrays.asList(trimmedGroups));
}