Example usage for com.amazonaws.services.securitytoken.model Credentials getSessionToken

List of usage examples for com.amazonaws.services.securitytoken.model Credentials getSessionToken

Introduction

In this page you can find the example usage for com.amazonaws.services.securitytoken.model Credentials getSessionToken.

Prototype


public String getSessionToken() 

Source Link

Document

The token that users must pass to the service API to use the temporary credentials.

Usage

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

License:Apache License

/**
 * {@inheritDoc}/*w  w  w.j av  a 2  s. c  o m*/
 */
@Override
public UploadSingleCredentialExtensionResponse extendUploadSingleCredentials(String namespace,
        String businessObjectDefinitionName, String businessObjectFormatUsage,
        String businessObjectFormatFileType, Integer businessObjectFormatVersion, String partitionValue,
        Integer businessObjectDataVersion) {
    // Create the business object data key.
    BusinessObjectDataKey businessObjectDataKey = new BusinessObjectDataKey(namespace,
            businessObjectDefinitionName, businessObjectFormatUsage, businessObjectFormatFileType,
            businessObjectFormatVersion, partitionValue, null, businessObjectDataVersion);

    // Get the business object data for the key.
    BusinessObjectDataEntity businessObjectDataEntity = dmDaoHelper
            .getBusinessObjectDataEntity(businessObjectDataKey);

    // Ensure the status of the business object data is "uploading" in order to extend credentials.
    if (!(businessObjectDataEntity.getStatus().getCode().equals(BusinessObjectDataStatusEntity.UPLOADING))) {
        throw new IllegalArgumentException(String.format(String.format(
                "Business object data {%s} has a status of \"%s\" and must be \"%s\" to extend "
                        + "credentials.",
                dmHelper.businessObjectDataKeyToString(businessObjectDataKey),
                businessObjectDataEntity.getStatus().getCode(), BusinessObjectDataStatusEntity.UPLOADING)));
    }

    // Get the S3 managed "loading dock" storage entity and make sure it exists.
    StorageEntity storageEntity = dmDaoHelper.getStorageEntity(StorageEntity.MANAGED_LOADING_DOCK_STORAGE);

    // Get S3 bucket name for the storage. Please note that since those values are required we pass a "true" flag.
    String s3BucketName = dmDaoHelper
            .getStorageAttributeValueByName(StorageAttributeEntity.ATTRIBUTE_BUCKET_NAME, storageEntity, true);

    // Get the storage unit entity for this business object data in the S3 managed "loading dock" storage and make sure it exists.
    StorageUnitEntity storageUnitEntity = dmDaoHelper.getStorageUnitEntity(businessObjectDataEntity,
            StorageEntity.MANAGED_LOADING_DOCK_STORAGE);

    // Validate that the storage unit contains exactly one storage file.
    assertHasOneStorageFile(storageUnitEntity);

    // Get the storage file entity.
    StorageFileEntity storageFileEntity = storageUnitEntity.getStorageFiles().iterator().next();

    // Get the storage file path.
    String storageFilePath = storageFileEntity.getPath();

    // Get decrypted AWS ARN of the role that is required to provide access to S3_MANAGED_LOADING_DOCK storage.
    String awsRoleArn = dmStringHelper
            .getRequiredConfigurationValue(ConfigurationValue.AWS_LOADING_DOCK_UPLOADER_ROLE_ARN);

    // Get expiration interval for the pre-signed URL to be generated.
    Integer awsRoleDurationSeconds = configurationHelper
            .getProperty(ConfigurationValue.AWS_LOADING_DOCK_UPLOADER_ROLE_DURATION_SECS, Integer.class);

    // Get decrypted AWS KMS Loading Dock Key ID value.
    String awsKmsKeyId = dmStringHelper
            .getRequiredConfigurationValue(ConfigurationValue.AWS_KMS_LOADING_DOCK_KEY_ID);

    // Get the temporary security credentials to access S3_MANAGED_STORAGE.
    Credentials assumedSessionCredentials = stsDao.getTemporarySecurityCredentials(awsHelper.getAwsParamsDto(),
            String.valueOf(businessObjectDataEntity.getId()), awsRoleArn, awsRoleDurationSeconds,
            createUploaderPolicy(s3BucketName, storageFilePath, awsKmsKeyId));

    // Create the response.
    UploadSingleCredentialExtensionResponse response = new UploadSingleCredentialExtensionResponse();
    response.setAwsAccessKey(assumedSessionCredentials.getAccessKeyId());
    response.setAwsSecretKey(assumedSessionCredentials.getSecretAccessKey());
    response.setAwsSessionToken(assumedSessionCredentials.getSessionToken());
    response.setAwsSessionExpirationTime(
            DmDateUtils.getXMLGregorianCalendarValue(assumedSessionCredentials.getExpiration()));

    return response;
}

From source file:org.finra.herd.dao.helper.EmrHelper.java

License:Apache License

private void updateAwsParamsForCrossAccountAccess(AwsParamsDto awsParamsDto, String accountId) {
    // Retrieve the role ARN and make sure it exists.
    TrustingAccountEntity trustingAccountEntity = trustingAccountDaoHelper
            .getTrustingAccountEntity(accountId.trim());
    String roleArn = trustingAccountEntity.getRoleArn();

    // Assume the role. Set the duration of the role session to 3600 seconds (1 hour).
    Credentials credentials = stsDao.getTemporarySecurityCredentials(awsParamsDto, UUID.randomUUID().toString(),
            roleArn, 3600, null);/*from w w  w  .j  av a2 s. c o m*/

    // Update the AWS parameters DTO with the temporary credentials.
    awsParamsDto.setAwsAccessKeyId(credentials.getAccessKeyId());
    awsParamsDto.setAwsSecretKey(credentials.getSecretAccessKey());
    awsParamsDto.setSessionToken(credentials.getSessionToken());
}

From source file:org.finra.herd.service.helper.StorageHelper.java

License:Apache License

/**
 * Returns a new {@link S3FileTransferRequestParamsDto} with temporary credentials as per specified AWS role and session name.
 *
 * @param roleArn the ARN of the role/*from   ww w.jav  a  2  s .co m*/
 * @param sessionName the session name
 *
 * @return the {@link S3FileTransferRequestParamsDto} object
 */
public S3FileTransferRequestParamsDto getS3FileTransferRequestParamsDtoByRole(String roleArn,
        String sessionName) {
    // Get the S3 file transfer request parameters DTO with proxy host and port populated from the configuration.
    S3FileTransferRequestParamsDto params = getS3FileTransferRequestParamsDto();

    // Assume the specified role. Set the duration of the role session to 3600 seconds (1 hour).
    Credentials credentials = stsDao.getTemporarySecurityCredentials(params, sessionName, roleArn, 3600, null);

    // Update the AWS parameters DTO with the temporary credentials.
    params.setAwsAccessKeyId(credentials.getAccessKeyId());
    params.setAwsSecretKey(credentials.getSecretAccessKey());
    params.setSessionToken(credentials.getSessionToken());

    return params;
}

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

License:Apache License

/**
 * Creates and returns a set of AWS credentials which can be used to access the S3 object indicated by the given business object data and storage.
 *
 * @param businessObjectDataKey Business object data key
 * @param createNewVersion true to create credentials for the next version up from the latest business object data, otherwise, uses specified data version
 * in data key./*  ww w.  j a v  a 2 s  . c o m*/
 * @param storageName Name of storage to access
 * @param isUpload true if this credential is to upload, false to download
 *
 * @return Credentials which has the permissions to perform the specified actions at the specified storage.
 */
private AwsCredential getBusinessObjectDataS3Credential(BusinessObjectDataKey businessObjectDataKey,
        Boolean createNewVersion, String storageName, boolean isUpload) {
    Assert.isTrue(StringUtils.isNotBlank(storageName), "storageName must be specified");
    Assert.isTrue(businessObjectDataKey.getBusinessObjectDataVersion() != null || createNewVersion != null,
            "One of businessObjectDataVersion or createNewVersion must be specified.");
    Assert.isTrue(
            businessObjectDataKey.getBusinessObjectDataVersion() == null
                    || !Boolean.TRUE.equals(createNewVersion),
            "createNewVersion must be false or unspecified when businessObjectDataVersion is specified.");

    /*
     * Choose configurations based on whether this is an upload or download operation.
     */
    ConfigurationValue roleArnConfigurationValue;
    ConfigurationValue defaultSessionDurationConfigurationValue;
    ConfigurationValue sessionDurationConfigurationValue;
    S3Actions[] s3Actions;
    KmsActions[] kmsActions;

    if (isUpload) {
        roleArnConfigurationValue = ConfigurationValue.S3_ATTRIBUTE_NAME_UPLOAD_ROLE_ARN;
        defaultSessionDurationConfigurationValue = ConfigurationValue.AWS_S3_DEFAULT_UPLOAD_SESSION_DURATION_SECS;
        sessionDurationConfigurationValue = ConfigurationValue.S3_ATTRIBUTE_NAME_UPLOAD_SESSION_DURATION_SECS;
        s3Actions = new S3Actions[] { S3Actions.PutObject, S3Actions.DeleteObject };
        kmsActions = new KmsActions[] { KmsActions.GENERATE_DATA_KEY, KmsActions.DECRYPT };
    } else {
        roleArnConfigurationValue = ConfigurationValue.S3_ATTRIBUTE_NAME_DOWNLOAD_ROLE_ARN;
        defaultSessionDurationConfigurationValue = ConfigurationValue.AWS_S3_DEFAULT_DOWNLOAD_SESSION_DURATION_SECS;
        sessionDurationConfigurationValue = ConfigurationValue.S3_ATTRIBUTE_NAME_DOWNLOAD_SESSION_DURATION_SECS;
        s3Actions = new S3Actions[] { S3Actions.GetObject };
        kmsActions = new KmsActions[] { KmsActions.DECRYPT };
    }

    StorageEntity storageEntity = storageDaoHelper.getStorageEntity(storageName.trim());
    String roleArn = storageDaoHelper.getStorageAttributeValueByName(
            configurationHelper.getProperty(roleArnConfigurationValue), storageEntity, true);
    Integer durationSeconds = storageDaoHelper.getStorageAttributeIntegerValueByName(
            configurationHelper.getProperty(sessionDurationConfigurationValue), storageEntity,
            configurationHelper.getProperty(defaultSessionDurationConfigurationValue, Integer.class));
    String bucketName = storageDaoHelper.getStorageAttributeValueByName(
            configurationHelper.getProperty(ConfigurationValue.S3_ATTRIBUTE_NAME_BUCKET_NAME), storageEntity,
            true);

    S3KeyPrefixInformation s3KeyPrefixInformation = getS3KeyPrefixImpl(businessObjectDataKey, null,
            createNewVersion);
    /*
     * Policy is different based on whether this is meant for downloading or uploading.
     * However, both uploader and downloader requires a ListBucket at the bucket level.
     */
    AwsPolicyBuilder awsPolicyBuilder = new AwsPolicyBuilder()
            .withS3Prefix(bucketName, s3KeyPrefixInformation.getS3KeyPrefix(), s3Actions)
            .withS3(bucketName, null, S3Actions.ListObjects);

    /*
     * Only add KMS policies if the storage specifies a KMS ID
     */
    String kmsKeyId = getStorageKmsKeyId(storageEntity);
    if (kmsKeyId != null) {
        awsPolicyBuilder.withKms(kmsKeyId.trim(), kmsActions);
    }

    Credentials credentials = stsDao.getTemporarySecurityCredentials(awsHelper.getAwsParamsDto(),
            businessObjectDataKey.getNamespace(), roleArn, durationSeconds, awsPolicyBuilder.build());

    AwsCredential awsCredential = new AwsCredential();
    awsCredential.setAwsAccessKey(credentials.getAccessKeyId());
    awsCredential.setAwsSecretKey(credentials.getSecretAccessKey());
    awsCredential.setAwsSessionToken(credentials.getSessionToken());
    awsCredential.setAwsSessionExpirationTime(
            HerdDateUtils.getXMLGregorianCalendarValue(credentials.getExpiration()));
    return awsCredential;
}

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

License:Apache License

/**
 * Creates and returns a set of AWS credentials which can be used to access the S3 object indicated by the given business object data and storage.
 *
 * @param businessObjectDataKey Business object data key
 * @param createNewVersion true to create credentials for the next version up from the latest business object data, otherwise, uses specified data version
 * in data key./*from w  w  w .j ava2  s .c om*/
 * @param storageName Name of storage to access
 * @param isUpload true if this credential is to upload, false to download
 *
 * @return Credentials which has the permissions to perform the specified actions at the specified storage.
 */
private AwsCredential getBusinessObjectDataS3Credential(BusinessObjectDataKey businessObjectDataKey,
        Boolean createNewVersion, String storageName, boolean isUpload) {
    Assert.isTrue(StringUtils.isNotBlank(storageName), "storageName must be specified");
    Assert.isTrue(businessObjectDataKey.getBusinessObjectDataVersion() != null || createNewVersion != null,
            "One of businessObjectDataVersion or createNewVersion must be specified.");
    Assert.isTrue(
            businessObjectDataKey.getBusinessObjectDataVersion() == null
                    || !Boolean.TRUE.equals(createNewVersion),
            "createNewVersion must be false or unspecified when businessObjectDataVersion is specified.");

    /*
     * Choose configurations based on whether this is an upload or download operation.
     */
    ConfigurationValue roleArnConfigurationValue;
    ConfigurationValue defaultSessionDurationConfigurationValue;
    ConfigurationValue sessionDurationConfigurationValue;
    S3Actions[] s3Actions;
    KmsActions[] kmsActions;

    if (isUpload) {
        roleArnConfigurationValue = ConfigurationValue.S3_ATTRIBUTE_NAME_UPLOAD_ROLE_ARN;
        defaultSessionDurationConfigurationValue = ConfigurationValue.AWS_S3_DEFAULT_UPLOAD_SESSION_DURATION_SECS;
        sessionDurationConfigurationValue = ConfigurationValue.S3_ATTRIBUTE_NAME_UPLOAD_SESSION_DURATION_SECS;
        s3Actions = new S3Actions[] { S3Actions.PutObject, S3Actions.DeleteObject };
        kmsActions = new KmsActions[] { KmsActions.GENERATE_DATA_KEY, KmsActions.DECRYPT };
    } else {
        roleArnConfigurationValue = ConfigurationValue.S3_ATTRIBUTE_NAME_DOWNLOAD_ROLE_ARN;
        defaultSessionDurationConfigurationValue = ConfigurationValue.AWS_S3_DEFAULT_DOWNLOAD_SESSION_DURATION_SECS;
        sessionDurationConfigurationValue = ConfigurationValue.S3_ATTRIBUTE_NAME_DOWNLOAD_SESSION_DURATION_SECS;
        s3Actions = new S3Actions[] { S3Actions.GetObject };
        kmsActions = new KmsActions[] { KmsActions.DECRYPT };
    }

    StorageEntity storageEntity = storageDaoHelper.getStorageEntity(storageName.trim());
    String roleArn = storageHelper.getStorageAttributeValueByName(
            configurationHelper.getProperty(roleArnConfigurationValue), storageEntity, true);
    Integer durationSeconds = storageHelper.getStorageAttributeIntegerValueByName(
            configurationHelper.getProperty(sessionDurationConfigurationValue), storageEntity,
            configurationHelper.getProperty(defaultSessionDurationConfigurationValue, Integer.class));
    String bucketName = storageHelper.getStorageAttributeValueByName(
            configurationHelper.getProperty(ConfigurationValue.S3_ATTRIBUTE_NAME_BUCKET_NAME), storageEntity,
            true);

    S3KeyPrefixInformation s3KeyPrefixInformation = getS3KeyPrefixImpl(businessObjectDataKey, null, storageName,
            createNewVersion);
    /*
     * Policy is different based on whether this is meant for downloading or uploading.
     * However, both uploader and downloader requires a ListBucket at the bucket level.
     */
    AwsPolicyBuilder awsPolicyBuilder = new AwsPolicyBuilder()
            .withS3Prefix(bucketName, s3KeyPrefixInformation.getS3KeyPrefix(), s3Actions)
            .withS3(bucketName, null, S3Actions.ListObjects);

    /*
     * Only add KMS policies if the storage specifies a KMS ID
     */
    String kmsKeyId = getStorageKmsKeyId(storageEntity);
    if (kmsKeyId != null) {
        awsPolicyBuilder.withKms(kmsKeyId.trim(), kmsActions);
    }

    Credentials credentials = stsDao.getTemporarySecurityCredentials(awsHelper.getAwsParamsDto(),
            UUID.randomUUID().toString(), roleArn, durationSeconds, awsPolicyBuilder.build());

    AwsCredential awsCredential = new AwsCredential();
    awsCredential.setAwsAccessKey(credentials.getAccessKeyId());
    awsCredential.setAwsSecretKey(credentials.getSecretAccessKey());
    awsCredential.setAwsSessionToken(credentials.getSessionToken());
    awsCredential.setAwsSessionExpirationTime(
            HerdDateUtils.getXMLGregorianCalendarValue(credentials.getExpiration()));
    return awsCredential;
}

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

License:Apache License

@PublishNotificationMessages
@NamespacePermission(fields = { "#uploadSingleInitiationRequest?.sourceBusinessObjectFormatKey?.namespace",
        "#uploadSingleInitiationRequest?.targetBusinessObjectFormatKey?.namespace" }, permissions = NamespacePermissionEnum.WRITE)
@Override// w ww  .  j a  va  2  s  .  c o m
public UploadSingleInitiationResponse initiateUploadSingle(
        UploadSingleInitiationRequest uploadSingleInitiationRequest) {
    // Validate and trim the request parameters.
    validateUploadSingleInitiationRequest(uploadSingleInitiationRequest);

    // Get the business object format for the specified parameters and make sure it exists.
    BusinessObjectFormatEntity sourceBusinessObjectFormatEntity = businessObjectFormatDaoHelper
            .getBusinessObjectFormatEntity(uploadSingleInitiationRequest.getSourceBusinessObjectFormatKey());

    // Get the target business object format entity for the specified parameters and make sure it exists.
    BusinessObjectFormatEntity targetBusinessObjectFormatEntity = businessObjectFormatDaoHelper
            .getBusinessObjectFormatEntity(uploadSingleInitiationRequest.getTargetBusinessObjectFormatKey());

    // Get the S3 managed "loading dock" storage entity and make sure it exists.
    StorageEntity sourceStorageEntity = storageDaoHelper
            .getStorageEntity(StorageEntity.MANAGED_LOADING_DOCK_STORAGE);

    // Get S3 bucket name for the storage. Please note that since those values are required we pass a "true" flag.
    String s3BucketName = storageHelper.getStorageBucketName(sourceStorageEntity);

    // Get the S3 managed "external" storage entity and make sure it exists.
    String targetStorageName;
    if (uploadSingleInitiationRequest.getTargetStorageName() != null) {
        targetStorageName = uploadSingleInitiationRequest.getTargetStorageName();
    } else {
        targetStorageName = configurationHelper
                .getProperty(ConfigurationValue.S3_EXTERNAL_STORAGE_NAME_DEFAULT);
    }
    StorageEntity targetStorageEntity = storageDaoHelper.getStorageEntity(targetStorageName);

    assertTargetStorageEntityValid(targetStorageEntity);

    // Generate a random UUID value.
    String uuid = UUID.randomUUID().toString();

    // Create business object data key with partition value set to the generated UUID.
    BusinessObjectDataKey businessObjectDataKey = new BusinessObjectDataKey(
            uploadSingleInitiationRequest.getSourceBusinessObjectFormatKey().getNamespace(),
            uploadSingleInitiationRequest.getSourceBusinessObjectFormatKey().getBusinessObjectDefinitionName(),
            uploadSingleInitiationRequest.getSourceBusinessObjectFormatKey().getBusinessObjectFormatUsage(),
            uploadSingleInitiationRequest.getSourceBusinessObjectFormatKey().getBusinessObjectFormatFileType(),
            uploadSingleInitiationRequest.getSourceBusinessObjectFormatKey().getBusinessObjectFormatVersion(),
            uuid, null, BusinessObjectDataEntity.BUSINESS_OBJECT_DATA_INITIAL_VERSION);

    // Get a file upload specific S3 key prefix for the source storage based on the generated UUID.
    String sourceStorageDirectoryPath = s3KeyPrefixHelper.buildS3KeyPrefix(sourceStorageEntity,
            sourceBusinessObjectFormatEntity, businessObjectDataKey);
    String sourceStorageFilePath = String.format("%s/%s", sourceStorageDirectoryPath,
            uploadSingleInitiationRequest.getFile().getFileName());

    // Create a business object data create request.
    BusinessObjectDataCreateRequest sourceBusinessObjectDataCreateRequest = businessObjectDataHelper
            .createBusinessObjectDataCreateRequest(sourceBusinessObjectFormatEntity, uuid,
                    BusinessObjectDataStatusEntity.UPLOADING,
                    uploadSingleInitiationRequest.getBusinessObjectDataAttributes(), sourceStorageEntity,
                    sourceStorageDirectoryPath, sourceStorageFilePath,
                    uploadSingleInitiationRequest.getFile().getFileSizeBytes(), null);

    // Create a new business object data instance. Set the flag to false, since for the file upload service the file size value is optional.
    BusinessObjectData sourceBusinessObjectData = businessObjectDataDaoHelper
            .createBusinessObjectData(sourceBusinessObjectDataCreateRequest, false);

    // Get a file upload specific S3 key prefix for the target storage based on the generated UUID.
    String targetStorageDirectoryPath = s3KeyPrefixHelper.buildS3KeyPrefix(targetStorageEntity,
            targetBusinessObjectFormatEntity, businessObjectDataKey);
    String targetStorageFilePath = String.format("%s/%s", targetStorageDirectoryPath,
            uploadSingleInitiationRequest.getFile().getFileName());

    uploadDownloadHelperService.assertS3ObjectKeyDoesNotExist(
            storageHelper.getStorageBucketName(targetStorageEntity), targetStorageFilePath);

    // Create a target business object data based on the source business object data and target business object format.
    BusinessObjectDataCreateRequest targetBusinessObjectDataCreateRequest = businessObjectDataHelper
            .createBusinessObjectDataCreateRequest(targetBusinessObjectFormatEntity, uuid,
                    BusinessObjectDataStatusEntity.UPLOADING,
                    uploadSingleInitiationRequest.getBusinessObjectDataAttributes(), targetStorageEntity,
                    targetStorageDirectoryPath, targetStorageFilePath,
                    uploadSingleInitiationRequest.getFile().getFileSizeBytes(), null);

    // Create a target business object data instance. Set the flag to false, since for the file upload service the file size value is optional.
    BusinessObjectData targetBusinessObjectData = businessObjectDataDaoHelper
            .createBusinessObjectData(targetBusinessObjectDataCreateRequest, false);

    // Get decrypted AWS ARN of the role that is required to provide access to S3_MANAGED_LOADING_DOCK storage.
    String awsRoleArn = getStorageUploadRoleArn(sourceStorageEntity);

    // Get expiration interval for the pre-signed URL to be generated.
    Integer awsRoleDurationSeconds = getStorageUploadSessionDuration(sourceStorageEntity);

    String awsKmsKeyId = storageHelper.getStorageKmsKeyId(sourceStorageEntity);

    // Get the temporary security credentials to access S3_MANAGED_STORAGE.
    Credentials assumedSessionCredentials = stsDao.getTemporarySecurityCredentials(awsHelper.getAwsParamsDto(),
            String.valueOf(sourceBusinessObjectData.getId()), awsRoleArn, awsRoleDurationSeconds,
            createUploaderPolicy(s3BucketName, sourceStorageFilePath, awsKmsKeyId));

    // Create the response.
    UploadSingleInitiationResponse response = new UploadSingleInitiationResponse();
    response.setSourceBusinessObjectData(sourceBusinessObjectData);
    response.setTargetBusinessObjectData(targetBusinessObjectData);
    response.setFile(uploadSingleInitiationRequest.getFile());
    response.setUuid(uuid);
    response.setAwsAccessKey(assumedSessionCredentials.getAccessKeyId());
    response.setAwsSecretKey(assumedSessionCredentials.getSecretAccessKey());
    response.setAwsSessionToken(assumedSessionCredentials.getSessionToken());
    response.setAwsSessionExpirationTime(
            HerdDateUtils.getXMLGregorianCalendarValue(assumedSessionCredentials.getExpiration()));
    response.setAwsKmsKeyId(awsKmsKeyId);
    response.setTargetStorageName(targetStorageName);

    return response;
}

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

License:Apache License

@NamespacePermission(fields = "#namespace", permissions = NamespacePermissionEnum.READ)
@Override/*w  w w . j a  v  a2s .  c om*/
public DownloadSingleInitiationResponse initiateDownloadSingle(String namespace,
        String businessObjectDefinitionName, String businessObjectFormatUsage,
        String businessObjectFormatFileType, Integer businessObjectFormatVersion, String partitionValue,
        Integer businessObjectDataVersion) {
    // Create the business object data key.
    BusinessObjectDataKey businessObjectDataKey = new BusinessObjectDataKey(namespace,
            businessObjectDefinitionName, businessObjectFormatUsage, businessObjectFormatFileType,
            businessObjectFormatVersion, partitionValue, null, businessObjectDataVersion);

    // Validate the parameters
    businessObjectDataHelper.validateBusinessObjectDataKey(businessObjectDataKey, true, true);

    // Retrieve the persisted business object data
    BusinessObjectDataEntity businessObjectDataEntity = businessObjectDataDaoHelper
            .getBusinessObjectDataEntity(businessObjectDataKey);

    // Make sure the status of the business object data is VALID
    businessObjectDataHelper.assertBusinessObjectDataStatusEquals(BusinessObjectDataStatusEntity.VALID,
            businessObjectDataEntity);

    // Get the external storage registered against this data
    // Validate that the storage unit exists
    StorageUnitEntity storageUnitEntity = IterableUtils.get(businessObjectDataEntity.getStorageUnits(), 0);

    // Validate that the storage unit contains only 1 file
    assertHasOneStorageFile(storageUnitEntity);

    String s3BucketName = storageHelper.getStorageBucketName(storageUnitEntity.getStorage());
    String s3ObjectKey = IterableUtils.get(storageUnitEntity.getStorageFiles(), 0).getPath();

    // Get the temporary credentials
    Credentials downloaderCredentials = getExternalDownloaderCredentials(storageUnitEntity.getStorage(),
            String.valueOf(businessObjectDataEntity.getId()), s3ObjectKey);

    // Generate a pre-signed URL
    Date expiration = downloaderCredentials.getExpiration();
    S3FileTransferRequestParamsDto s3BucketAccessParams = storageHelper
            .getS3BucketAccessParams(storageUnitEntity.getStorage());
    String presignedUrl = s3Dao.generateGetObjectPresignedUrl(s3BucketName, s3ObjectKey, expiration,
            s3BucketAccessParams);

    // Construct and return the response
    DownloadSingleInitiationResponse response = new DownloadSingleInitiationResponse();
    response.setBusinessObjectData(
            businessObjectDataHelper.createBusinessObjectDataFromEntity(businessObjectDataEntity));
    response.setAwsAccessKey(downloaderCredentials.getAccessKeyId());
    response.setAwsSecretKey(downloaderCredentials.getSecretAccessKey());
    response.setAwsSessionToken(downloaderCredentials.getSessionToken());
    response.setAwsSessionExpirationTime(HerdDateUtils.getXMLGregorianCalendarValue(expiration));
    response.setPreSignedUrl(presignedUrl);
    return response;
}

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

License:Apache License

@NamespacePermission(fields = "#namespace", permissions = NamespacePermissionEnum.WRITE)
@Override/*from   ww w .  j  av a2  s.co m*/
public UploadSingleCredentialExtensionResponse extendUploadSingleCredentials(String namespace,
        String businessObjectDefinitionName, String businessObjectFormatUsage,
        String businessObjectFormatFileType, Integer businessObjectFormatVersion, String partitionValue,
        Integer businessObjectDataVersion) {
    // Create the business object data key.
    BusinessObjectDataKey businessObjectDataKey = new BusinessObjectDataKey(namespace,
            businessObjectDefinitionName, businessObjectFormatUsage, businessObjectFormatFileType,
            businessObjectFormatVersion, partitionValue, null, businessObjectDataVersion);

    // Validate and trim the business object data key.
    businessObjectDataHelper.validateBusinessObjectDataKey(businessObjectDataKey, true, true);

    // Get the business object data for the key.
    BusinessObjectDataEntity businessObjectDataEntity = businessObjectDataDaoHelper
            .getBusinessObjectDataEntity(businessObjectDataKey);

    // Ensure the status of the business object data is "uploading" in order to extend credentials.
    if (!(businessObjectDataEntity.getStatus().getCode().equals(BusinessObjectDataStatusEntity.UPLOADING))) {
        throw new IllegalArgumentException(String.format(String.format(
                "Business object data {%s} has a status of \"%s\" and must be \"%s\" to extend "
                        + "credentials.",
                businessObjectDataHelper.businessObjectDataKeyToString(businessObjectDataKey),
                businessObjectDataEntity.getStatus().getCode(), BusinessObjectDataStatusEntity.UPLOADING)));
    }

    // Get the S3 managed "loading dock" storage entity and make sure it exists.
    StorageEntity storageEntity = storageDaoHelper.getStorageEntity(StorageEntity.MANAGED_LOADING_DOCK_STORAGE);

    String s3BucketName = storageHelper.getStorageBucketName(storageEntity);

    // Get the storage unit entity for this business object data in the S3 managed "loading dock" storage and make sure it exists.
    StorageUnitEntity storageUnitEntity = storageUnitDaoHelper
            .getStorageUnitEntity(StorageEntity.MANAGED_LOADING_DOCK_STORAGE, businessObjectDataEntity);

    // Validate that the storage unit contains exactly one storage file.
    assertHasOneStorageFile(storageUnitEntity);

    // Get the storage file entity.
    StorageFileEntity storageFileEntity = IterableUtils.get(storageUnitEntity.getStorageFiles(), 0);

    // Get the storage file path.
    String storageFilePath = storageFileEntity.getPath();

    String awsRoleArn = getStorageUploadRoleArn(storageEntity);

    Integer awsRoleDurationSeconds = getStorageUploadSessionDuration(storageEntity);

    String awsKmsKeyId = storageHelper.getStorageKmsKeyId(storageEntity);

    // Get the temporary security credentials to access S3_MANAGED_STORAGE.
    Credentials assumedSessionCredentials = stsDao.getTemporarySecurityCredentials(awsHelper.getAwsParamsDto(),
            String.valueOf(businessObjectDataEntity.getId()), awsRoleArn, awsRoleDurationSeconds,
            createUploaderPolicy(s3BucketName, storageFilePath, awsKmsKeyId));

    // Create the response.
    UploadSingleCredentialExtensionResponse response = new UploadSingleCredentialExtensionResponse();
    response.setAwsAccessKey(assumedSessionCredentials.getAccessKeyId());
    response.setAwsSecretKey(assumedSessionCredentials.getSecretAccessKey());
    response.setAwsSessionToken(assumedSessionCredentials.getSessionToken());
    response.setAwsSessionExpirationTime(
            HerdDateUtils.getXMLGregorianCalendarValue(assumedSessionCredentials.getExpiration()));

    return response;
}

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

License:Apache License

@Override
public DownloadBusinessObjectDefinitionSampleDataFileSingleInitiationResponse initiateDownloadSingleSampleFile(
        DownloadBusinessObjectDefinitionSampleDataFileSingleInitiationRequest request) {
    // Validate and trim the request parameters.
    validateDownloadBusinessObjectDefinitionSampleDataFileSingleInitiationRequest(request);

    // Get the business object definition sample data file key.
    BusinessObjectDefinitionSampleDataFileKey businessObjectDefinitionSampleDataFileKey = request
            .getBusinessObjectDefinitionSampleDataFileKey();

    // Get the business object definition key.
    BusinessObjectDefinitionKey businessObjectDefinitionKey = new BusinessObjectDefinitionKey(
            businessObjectDefinitionSampleDataFileKey.getNamespace(),
            businessObjectDefinitionSampleDataFileKey.getBusinessObjectDefinitionName());

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

    // Get the sample data file exists for the business object definition and ensure it exists.
    BusinessObjectDefinitionSampleDataFileEntity businessObjectDefinitionSampleDataFileEntity = getBusinessObjectDefinitionSampleDataFileEntity(
            businessObjectDefinitionEntity, businessObjectDefinitionSampleDataFileKey);

    // Retrieve the storage related information.
    StorageEntity storageEntity = businessObjectDefinitionSampleDataFileEntity.getStorage();
    String s3BucketName = storageHelper.getStorageBucketName(storageEntity);
    String s3ObjectKey = businessObjectDefinitionSampleDataFileKey.getDirectoryPath()
            + businessObjectDefinitionSampleDataFileKey.getFileName();

    String sessionID = UUID.randomUUID().toString();
    // Get the temporary credentials.
    Credentials downloaderCredentials = getDownloaderCredentialsNoKmsKey(storageEntity, sessionID, s3ObjectKey);

    // Generate a pre-signed URL.
    Date expiration = downloaderCredentials.getExpiration();
    S3FileTransferRequestParamsDto s3BucketAccessParams = storageHelper.getS3BucketAccessParams(storageEntity);
    String presignedUrl = s3Dao.generateGetObjectPresignedUrl(s3BucketName, s3ObjectKey, expiration,
            s3BucketAccessParams);//ww  w  .  j av a  2 s  .  co  m

    // Create the download business object definition sample data file single initiation response.
    DownloadBusinessObjectDefinitionSampleDataFileSingleInitiationResponse response = new DownloadBusinessObjectDefinitionSampleDataFileSingleInitiationResponse();
    response.setBusinessObjectDefinitionSampleDataFileKey(new BusinessObjectDefinitionSampleDataFileKey(
            businessObjectDefinitionEntity.getNamespace().getCode(), businessObjectDefinitionEntity.getName(),
            businessObjectDefinitionSampleDataFileEntity.getDirectoryPath(),
            businessObjectDefinitionSampleDataFileEntity.getFileName()));
    response.setAwsS3BucketName(s3BucketName);
    response.setAwsAccessKey(downloaderCredentials.getAccessKeyId());
    response.setAwsSecretKey(downloaderCredentials.getSecretAccessKey());
    response.setAwsSessionToken(downloaderCredentials.getSessionToken());
    response.setAwsSessionExpirationTime(HerdDateUtils.getXMLGregorianCalendarValue(expiration));
    response.setPreSignedUrl(presignedUrl);

    // Return the response.
    return response;
}

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

License:Apache License

@NamespacePermission(fields = "#request.businessObjectDefinitionKey.namespace", permissions = {
        NamespacePermissionEnum.WRITE_DESCRIPTIVE_CONTENT, NamespacePermissionEnum.WRITE })
@Override//from w  ww  .  j a v  a 2  s.  c  o m
public UploadBusinessObjectDefinitionSampleDataFileInitiationResponse initiateUploadSampleFile(
        UploadBusinessObjectDefinitionSampleDataFileInitiationRequest request) {
    validateUploadBusinessObjectDefinitionSampleDataFileInitiationRequest(request);

    BusinessObjectDefinitionKey businessObjectDefinitionKey = request.getBusinessObjectDefinitionKey();
    // Get the business object definition entity and ensure it exists.
    BusinessObjectDefinitionEntity businessObjectDefinitionEntity = businessObjectDefinitionDaoHelper
            .getBusinessObjectDefinitionEntity(businessObjectDefinitionKey);
    businessObjectDefinitionKey.setNamespace(businessObjectDefinitionEntity.getNamespace().getCode());
    businessObjectDefinitionKey.setBusinessObjectDefinitionName(businessObjectDefinitionEntity.getName());

    UploadBusinessObjectDefinitionSampleDataFileInitiationResponse response = new UploadBusinessObjectDefinitionSampleDataFileInitiationResponse();
    StorageEntity storageEntity = storageDaoHelper.getStorageEntity(StorageEntity.SAMPLE_DATA_FILE_STORAGE);

    String s3BucketName = storageHelper.getStorageBucketName(storageEntity);
    String s3EndPoint = storageHelper.getS3BucketAccessParams(storageEntity).getS3Endpoint();
    String awsRoleArn = getStorageUploadRoleArn(storageEntity);
    String sessionID = UUID.randomUUID().toString();
    String s3KeyPrefix = s3KeyPrefixHelper.buildS3KeyPrefix(storageEntity, businessObjectDefinitionKey);
    s3KeyPrefix = StringUtils.appendIfMissing(s3KeyPrefix, "/");
    //need to add star for aws authorization
    String s3Path = s3KeyPrefix + "*";

    Integer awsRoleDurationSeconds = getStorageUploadSessionDuration(storageEntity);

    Credentials assumedSessionCredentials = stsDao.getTemporarySecurityCredentials(awsHelper.getAwsParamsDto(),
            sessionID, awsRoleArn, awsRoleDurationSeconds, createUploaderPolicyNoKmsKey(s3BucketName, s3Path));

    response.setAwsAccessKey(assumedSessionCredentials.getAccessKeyId());
    response.setAwsSecretKey(assumedSessionCredentials.getSecretAccessKey());
    response.setAwsSessionToken(assumedSessionCredentials.getSessionToken());
    response.setAwsSessionExpirationTime(
            HerdDateUtils.getXMLGregorianCalendarValue(assumedSessionCredentials.getExpiration()));

    response.setAwsS3BucketName(s3BucketName);
    response.setBusinessObjectDefinitionKey(businessObjectDefinitionKey);
    response.setS3Endpoint(s3EndPoint);
    response.setS3KeyPrefix(s3KeyPrefix);
    return response;
}