com.amazonaws.SdkClientException Java Examples

The following examples show how to use com.amazonaws.SdkClientException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DeleteApplicationRequestProtocolMarshaller.java    From realworld-serverless-application with Apache License 2.0 6 votes vote down vote up
public Request<DeleteApplicationRequest> marshall(DeleteApplicationRequest deleteApplicationRequest) {

        if (deleteApplicationRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            final ProtocolRequestMarshaller<DeleteApplicationRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
                    deleteApplicationRequest);

            protocolMarshaller.startMarshalling();
            DeleteApplicationRequestMarshaller.getInstance().marshall(deleteApplicationRequest, protocolMarshaller);
            return protocolMarshaller.finishMarshalling();
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }
 
Example #2
Source File: ApplicationMarshaller.java    From realworld-serverless-application with Apache License 2.0 6 votes vote down vote up
/**
 * Marshall the given parameter object.
 */
public void marshall(Application application, ProtocolMarshaller protocolMarshaller) {

    if (application == null) {
        throw new SdkClientException("Invalid argument passed to marshall(...)");
    }

    try {
        protocolMarshaller.marshall(application.getApplicationId(), APPLICATIONID_BINDING);
        protocolMarshaller.marshall(application.getAuthor(), AUTHOR_BINDING);
        protocolMarshaller.marshall(application.getCreationTime(), CREATIONTIME_BINDING);
        protocolMarshaller.marshall(application.getDescription(), DESCRIPTION_BINDING);
        protocolMarshaller.marshall(application.getHomePageUrl(), HOMEPAGEURL_BINDING);
    } catch (Exception e) {
        throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
    }
}
 
Example #3
Source File: Validation.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
public static AWSCredentialsProvider getBasicCredentialsOrDefaultChain(String accessKey, String secretKey, String awsSessionToken) {
    AWSCredentialsProvider result;
    if (StringUtils.isNotEmpty(accessKey) && StringUtils.isNotEmpty(secretKey) && StringUtils.isNotEmpty(awsSessionToken)) {
        result = new AWSStaticCredentialsProvider(new BasicSessionCredentials(accessKey, secretKey, awsSessionToken));
    }
    else if (StringUtils.isNotEmpty(accessKey) && StringUtils.isNotEmpty(secretKey)) {
        result = new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey));
    } else {
        result = DefaultAWSCredentialsProviderChain.getInstance();
        try {
            result.getCredentials();
        } catch (SdkClientException e) {
            throw new InvalidInputException(invalidDefaultCredentialsError);
        }
    }
    return result;
}
 
Example #4
Source File: UpdateApplicationRequestProtocolMarshaller.java    From realworld-serverless-application with Apache License 2.0 6 votes vote down vote up
public Request<UpdateApplicationRequest> marshall(UpdateApplicationRequest updateApplicationRequest) {

        if (updateApplicationRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            final ProtocolRequestMarshaller<UpdateApplicationRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
                    updateApplicationRequest);

            protocolMarshaller.startMarshalling();
            UpdateApplicationRequestMarshaller.getInstance().marshall(updateApplicationRequest, protocolMarshaller);
            return protocolMarshaller.finishMarshalling();
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }
 
Example #5
Source File: CreateApplicationInputMarshaller.java    From realworld-serverless-application with Apache License 2.0 6 votes vote down vote up
/**
 * Marshall the given parameter object.
 */
public void marshall(CreateApplicationInput createApplicationInput, ProtocolMarshaller protocolMarshaller) {

    if (createApplicationInput == null) {
        throw new SdkClientException("Invalid argument passed to marshall(...)");
    }

    try {
        protocolMarshaller.marshall(createApplicationInput.getApplicationId(), APPLICATIONID_BINDING);
        protocolMarshaller.marshall(createApplicationInput.getAuthor(), AUTHOR_BINDING);
        protocolMarshaller.marshall(createApplicationInput.getDescription(), DESCRIPTION_BINDING);
        protocolMarshaller.marshall(createApplicationInput.getHomePageUrl(), HOMEPAGEURL_BINDING);
    } catch (Exception e) {
        throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
    }
}
 
Example #6
Source File: TestAWSSecretsManagerCredentialStore.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testInitIncorrectRegion() throws Exception {
  String region = "us-west-2";
  String awsAccessKey = "access-key";
  String awsSecretKey = "secret-key";

  CredentialStore.Context context = Mockito.mock(CredentialStore.Context.class);
  Mockito.when(context.getConfig(AWSSecretsManagerCredentialStore.AWS_REGION_PROP)).thenReturn(region);
  Mockito.when(context.getConfig(AWSSecretsManagerCredentialStore.AWS_ACCESS_KEY_PROP)).thenReturn(awsAccessKey);
  Mockito.when(context.getConfig(AWSSecretsManagerCredentialStore.AWS_SECRET_KEY_PROP)).thenReturn(awsSecretKey);

  SecretCache secretCache = Mockito.mock(SecretCache.class);
  SdkClientException exception = new SdkClientException("message");
  AWSSecretsManagerCredentialStore secretManager = createAWSSecretsManagerCredentialStore(secretCache, exception);
  List<CredentialStore.ConfigIssue> issues = secretManager.init(context);
  Assert.assertEquals(1, issues.size());
  Mockito.verify(context, Mockito.times(1)).createConfigIssue(
      Errors.AWS_SECRETS_MANAGER_CRED_STORE_01,
      exception.getMessage(),
      exception
  );
}
 
Example #7
Source File: ParallelUploader.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void upload(final AmazonS3 s3, final String bucket, final String key, final InputStream contents) {
  try (InputStream input = new BufferedInputStream(contents, chunkSize)) {
    log.debug("Starting upload to key {} in bucket {}", key, bucket);

    input.mark(chunkSize);
    ChunkReader chunkReader = new ChunkReader(input);
    Chunk chunk = chunkReader.readChunk(chunkSize).orElse(EMPTY_CHUNK);
    input.reset();

    if (chunk.dataLength < chunkSize) {
      ObjectMetadata metadata = new ObjectMetadata();
      metadata.setContentLength(chunk.dataLength);
      s3.putObject(bucket, key, new ByteArrayInputStream(chunk.data, 0, chunk.dataLength), metadata);
    }
    else {
      ChunkReader parallelReader = new ChunkReader(input);
      parallelRequests(s3, bucket, key,
          () -> (uploadId -> uploadChunks(s3, bucket, key, uploadId, parallelReader)));
    }
    log.debug("Finished upload to key {} in bucket {}", key, bucket);
  }
  catch (IOException | SdkClientException e) { // NOSONAR
    throw new BlobStoreException(format("Error uploading blob to bucket:%s key:%s", bucket, key), e, null);
  }
}
 
Example #8
Source File: AwsInstanceConnector.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Retryable(
        value = SdkClientException.class,
        maxAttempts = 15,
        backoff = @Backoff(delay = 1000, multiplier = 2, maxDelay = 10000)
)
@Override
public List<CloudVmInstanceStatus> reboot(AuthenticatedContext ac, List<CloudInstance> vms) {
    AmazonEC2Client amazonEC2Client = awsClient.createAccess(new AwsCredentialView(ac.getCloudCredential()),
            ac.getCloudContext().getLocation().getRegion().value());
    List<CloudInstance> affectedVms = new ArrayList<>();
    try {
        if (!vms.isEmpty()) {
            List<CloudVmInstanceStatus> statuses = check(ac, vms);
            doReboot(affectedVms, amazonEC2Client, getStarted(statuses));
            doStart(affectedVms, ac, getStopped(statuses));
            logInvalidStatuses(getNotStoppedOrStarted(statuses));
        }
    } catch (SdkClientException e) {
        LOGGER.warn("Failed to send reboot request to AWS: ", e);
        throw e;
    }
    return pollerUtil.waitFor(ac, affectedVms, Sets.newHashSet(InstanceStatus.STARTED, InstanceStatus.FAILED));
}
 
Example #9
Source File: EnvironmentAWSCredentialsProvider.java    From micronaut-aws with Apache License 2.0 6 votes vote down vote up
@Override
public AWSCredentials getCredentials() {
    String accessKey = environment.getProperty(ACCESS_KEY_ENV_VAR, String.class, environment.getProperty(ALTERNATE_ACCESS_KEY_ENV_VAR, String.class, (String) null));

    String secretKey = environment.getProperty(SECRET_KEY_ENV_VAR, String.class, environment.getProperty(ALTERNATE_SECRET_KEY_ENV_VAR, String.class, (String) null));
    accessKey = StringUtils.trim(accessKey);
    secretKey = StringUtils.trim(secretKey);
    String sessionToken = StringUtils.trim(environment.getProperty(AWS_SESSION_TOKEN_ENV_VAR, String.class, (String) null));

    if (StringUtils.isNullOrEmpty(accessKey) || StringUtils.isNullOrEmpty(secretKey)) {
        throw new SdkClientException(
            "Unable to load AWS credentials from environment " +
                "(" + ACCESS_KEY_ENV_VAR + " (or " + ALTERNATE_ACCESS_KEY_ENV_VAR + ") and " +
                SECRET_KEY_ENV_VAR + " (or " + ALTERNATE_SECRET_KEY_ENV_VAR + "))");
    }

    return sessionToken == null ?
        new BasicAWSCredentials(accessKey, secretKey)
        :
        new BasicSessionCredentials(accessKey, secretKey, sessionToken);
}
 
Example #10
Source File: UpdateApplicationRequestProtocolMarshaller.java    From realworld-serverless-application with Apache License 2.0 6 votes vote down vote up
public Request<UpdateApplicationRequest> marshall(UpdateApplicationRequest updateApplicationRequest) {

    if (updateApplicationRequest == null) {
      throw new SdkClientException("Invalid argument passed to marshall(...)");
    }

    try {
      final ProtocolRequestMarshaller<UpdateApplicationRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
              updateApplicationRequest);

      protocolMarshaller.startMarshalling();
      UpdateApplicationRequestMarshaller.getInstance().marshall(updateApplicationRequest, protocolMarshaller);
      return protocolMarshaller.finishMarshalling();
    } catch (Exception e) {
      throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
    }
  }
 
Example #11
Source File: AWSParameterStoreConfigClient.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
private static Publisher<? extends GetParametersResult> onGetParametersError(Throwable throwable) {
    if (throwable instanceof SdkClientException) {
        return Flowable.error(throwable);
    } else {
        return Flowable.error(new ConfigurationException("Error reading distributed configuration from AWS Parameter Store: " + throwable.getMessage(), throwable));
    }
}
 
Example #12
Source File: AwsValidatorsTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testStackValidatorStackUseRetryClient() {
    doReturn(amazonCloudFormationClient).when(awsClient).createCloudFormationClient(any(), anyString());
    when(amazonCloudFormationClient.describeStacks(any()))
            .thenThrow(new SdkClientException("repeat1 Rate exceeded"))
            .thenThrow(new SdkClientException("repeat2Request limit exceeded"))
            .thenReturn(null);
    Assertions.assertThrows(CloudConnectorException.class, () -> awsStackValidatorUnderTest.validate(authenticatedContext, null));
    verify(amazonCloudFormationClient, times(3)).describeStacks(any());
}
 
Example #13
Source File: DefaultGeoWaveAWSCredentialsProvider.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public AWSCredentials getCredentials() {
  try {
    return super.getCredentials();
  } catch (final SdkClientException exception) {

  }
  // fall back to anonymous credentials
  return new AnonymousAWSCredentials();
}
 
Example #14
Source File: AwsInstanceConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Retryable(
        value = SdkClientException.class,
        maxAttemptsExpression = "#{${cb.vm.retry.attempt:15}}",
        backoff = @Backoff(delayExpression = "#{${cb.vm.retry.backoff.delay:1000}}",
                multiplierExpression = "#{${cb.vm.retry.backoff.multiplier:2}}",
                maxDelayExpression = "#{${cb.vm.retry.backoff.maxdelay:10000}}")
)
@Override
public List<CloudVmInstanceStatus> start(AuthenticatedContext ac, List<CloudResource> resources, List<CloudInstance> vms) {
    return setCloudVmInstanceStatuses(ac, vms, "Running",
            (ec2Client, instances) -> ec2Client.startInstances(new StartInstancesRequest().withInstanceIds(instances)),
            "Failed to send start request to AWS: ");
}
 
Example #15
Source File: AWSParameterStoreConfigClient.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
private static Publisher<? extends GetParametersByPathResult> onGetParametersByPathResult(Throwable throwable) {
    if (throwable instanceof SdkClientException) {
        return Flowable.error(throwable);
    } else {
        return Flowable.error(new ConfigurationException("Error reading distributed configuration from AWS Parameter Store: " + throwable.getMessage(), throwable));
    }
}
 
Example #16
Source File: DummyS3Client.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public Bucket createBucket(String bucketName) throws SdkClientException {
    if (doesBucketExist(bucketName))
        throw new AmazonS3Exception("The specified bucket already exist");
    else {
        objMap.put(bucketName, new HashSet<>());

        return new Bucket();
    }
}
 
Example #17
Source File: AWSParameterStoreConfigClient.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize @Singleton.
 *
 * @param awsConfiguration                    your aws configuration credentials
 * @param awsParameterStoreConfiguration      configuration for the parameter store
 * @param applicationConfiguration            the application configuration
 * @param route53ClientDiscoveryConfiguration configuration for route53 service discovery, if you are using this (not required)
 * @throws SdkClientException If the aws sdk client could not be created
 */
AWSParameterStoreConfigClient(
        AWSClientConfiguration awsConfiguration,
        AWSParameterStoreConfiguration awsParameterStoreConfiguration,
        ApplicationConfiguration applicationConfiguration,
        @Nullable Route53ClientDiscoveryConfiguration route53ClientDiscoveryConfiguration) throws SdkClientException {
    this.awsConfiguration = awsConfiguration;
    this.awsParameterStoreConfiguration = awsParameterStoreConfiguration;
    this.client = AWSSimpleSystemsManagementAsyncClient.asyncBuilder().withClientConfiguration(awsConfiguration.getClientConfiguration()).build();
    this.serviceId = (route53ClientDiscoveryConfiguration != null ? route53ClientDiscoveryConfiguration.getServiceId() : applicationConfiguration.getName()).orElse(null);
}
 
Example #18
Source File: KinesisProxy.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether the exception is recoverable using exponential-backoff.
 *
 * @param ex Exception to inspect
 * @return <code>true</code> if the exception can be recovered from, else
 *         <code>false</code>
 */
protected boolean isRecoverableSdkClientException(SdkClientException ex) {
	if (ex instanceof AmazonServiceException) {
		return KinesisProxy.isRecoverableException((AmazonServiceException) ex);
	}
	// customizations may decide to retry other errors, such as read timeouts
	return false;
}
 
Example #19
Source File: ListApplicationsRequestMarshaller.java    From realworld-serverless-application with Apache License 2.0 5 votes vote down vote up
/**
 * Marshall the given parameter object.
 */
public void marshall(ListApplicationsRequest listApplicationsRequest, ProtocolMarshaller protocolMarshaller) {

  if (listApplicationsRequest == null) {
    throw new SdkClientException("Invalid argument passed to marshall(...)");
  }

  try {
    protocolMarshaller.marshall(listApplicationsRequest.getMaxItems(), MAXITEMS_BINDING);
    protocolMarshaller.marshall(listApplicationsRequest.getNextToken(), NEXTTOKEN_BINDING);
  } catch (Exception e) {
    throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
  }
}
 
Example #20
Source File: SecretCacheTest.java    From aws-secretsmanager-caching-java with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = {SdkClientException.class})
public void exceptionSecretCacheConfigTest() {
    try (SecretCache sc = new SecretCache(new SecretCacheConfiguration()
            .withCacheItemTTL(SecretCacheConfiguration.DEFAULT_CACHE_ITEM_TTL)
            .withMaxCacheSize(SecretCacheConfiguration.DEFAULT_MAX_CACHE_SIZE)
            .withVersionStage(SecretCacheConfiguration.DEFAULT_VERSION_STAGE))) {
        sc.getSecretString("");
    }
}
 
Example #21
Source File: AwsS3BuildCacheServiceFactory.java    From gradle-s3-build-cache with Apache License 2.0 5 votes vote down vote up
private AmazonS3 createS3Client(AwsS3BuildCache config) {
  AmazonS3 s3;
  try {
    AmazonS3ClientBuilder s3Builder = AmazonS3ClientBuilder.standard();
    if (!isNullOrEmpty(config.getAwsAccessKeyId()) && !isNullOrEmpty(config.getAwsSecretKey()) &&
              !isNullOrEmpty(config.getSessionToken())) {
          s3Builder.withCredentials(new AWSStaticCredentialsProvider(
                  new BasicSessionCredentials(config.getAwsAccessKeyId(), config.getAwsSecretKey(),
                          config.getSessionToken())));
    } else if (!isNullOrEmpty(config.getAwsAccessKeyId()) && !isNullOrEmpty(config.getAwsSecretKey())) {
      s3Builder.withCredentials(new AWSStaticCredentialsProvider(
          new BasicAWSCredentials(config.getAwsAccessKeyId(), config.getAwsSecretKey())));
    }

    addHttpHeaders(s3Builder, config);

    if (isNullOrEmpty(config.getEndpoint())) {
      s3Builder.withRegion(config.getRegion());
    } else {
      s3Builder.withEndpointConfiguration(
          new AwsClientBuilder.EndpointConfiguration(config.getEndpoint(), config.getRegion()));
    }
    s3 = s3Builder.build();
  } catch (SdkClientException e) {
    logger.debug("Error while building AWS S3 client: {}", e.getMessage());
    throw new GradleException("Creation of S3 build cache failed; cannot create S3 client", e);
  }
  return s3;
}
 
Example #22
Source File: UnsignedXrayClient.java    From aws-xray-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the given date string returned by the AWS service into a Date
 * object.
 */
private static Date parseServiceSpecificDate(String dateString) {
    try {
        BigDecimal dateValue = new BigDecimal(dateString);
        return new Date(dateValue.scaleByPowerOfTen(AWS_DATE_MILLI_SECOND_PRECISION).longValue());
    } catch (NumberFormatException nfe) {
        throw new SdkClientException("Unable to parse date : " + dateString, nfe);
    }
}
 
Example #23
Source File: CustomRegionProviderChain.java    From strongbox with Apache License 2.0 5 votes vote down vote up
private Optional<Region> getRegionFromMetadata() {
    try {
        Region resolvedRegion = null;
        if (EC2MetadataUtils.getInstanceInfo() != null) {
            if (EC2MetadataUtils.getInstanceInfo().getRegion() != null) {
                resolvedRegion = Region.fromName(EC2MetadataUtils.getInstanceInfo().getRegion());
            } else { // fallback to provider chain if region is not exposed
                resolvedRegion = Region.fromName(new DefaultAwsRegionProviderChain().getRegion());
            }
        }
        return Optional.ofNullable(resolvedRegion);
    } catch (SdkClientException e) {
        return Optional.empty();
    }
}
 
Example #24
Source File: S3ObjectsProvider.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the buckets belonging to the service user
 *
 * @return the list of buckets owned by the service user.
 * @throws SdkClientException
 */
private List<Bucket> getBuckets() throws SdkClientException {
  ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();

  List result;
  try {
    Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );
    result = s3Client.listBuckets();
  } finally {
    Thread.currentThread().setContextClassLoader( currentClassLoader );
  }

  return result;
}
 
Example #25
Source File: AmazonRetryClient.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
protected <T> T mapThrottlingError(Supplier<T> supplier) {
    try {
        return supplier.get();
    } catch (SdkClientException e) {
        if (e.getMessage().contains("Rate exceeded") || e.getMessage().contains("Request limit exceeded")) {
            throw new ActionFailedException(e.getMessage());
        }
        throw e;
    }
}
 
Example #26
Source File: XmlResponsesSaxParser.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs the XML SAX parser.
 *
 * @throws SdkClientException
 */
public XmlResponsesSaxParser() throws SdkClientException {
    // Ensure we can load the XML Reader.
    try {
        // Need to explicitly enable Sax' NAMESPACES_FEATURE (default true) in JAXP (default false)!
        SAX_PARSER_FACTORY.setNamespaceAware(true);
        xr = SAX_PARSER_FACTORY.newSAXParser().getXMLReader();
        disableExternalResourceFetching(xr);
    } catch (SAXException | ParserConfigurationException e) {
        throw new SdkClientException("Couldn't initialize a SAX driver to create an XMLReader", e);
    }
}
 
Example #27
Source File: S3PayloadStorage.java    From conductor with Apache License 2.0 5 votes vote down vote up
/**
 * Uploads the payload to the given s3 object key.
 * It is expected that the caller retrieves the object key using {@link #getLocation(Operation, PayloadType, String)} before making this call.
 *
 * @param path        the s3 key of the object to be uploaded
 * @param payload     an {@link InputStream} containing the json payload which is to be uploaded
 * @param payloadSize the size of the json payload in bytes
 */
@Override
public void upload(String path, InputStream payload, long payloadSize) {
    try {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(CONTENT_TYPE);
        objectMetadata.setContentLength(payloadSize);
        PutObjectRequest request = new PutObjectRequest(bucketName, path, payload, objectMetadata);
        s3Client.putObject(request);
    } catch (SdkClientException e) {
        String msg = "Error communicating with S3";
        logger.error(msg, e);
        throw new ApplicationException(ApplicationException.Code.BACKEND_ERROR, msg, e);
    }
}
 
Example #28
Source File: S3PayloadStorage.java    From conductor with Apache License 2.0 5 votes vote down vote up
/**
 * Downloads the payload stored in the s3 object.
 *
 * @param path the S3 key of the object
 * @return an input stream containing the contents of the object
 * Caller is expected to close the input stream.
 */
@Override
public InputStream download(String path) {
    try {
        S3Object s3Object = s3Client.getObject(new GetObjectRequest(bucketName, path));
        return s3Object.getObjectContent();
    } catch (SdkClientException e) {
        String msg = "Error communicating with S3";
        logger.error(msg, e);
        throw new ApplicationException(ApplicationException.Code.BACKEND_ERROR, msg, e);
    }
}
 
Example #29
Source File: ProfileAssumeRoleCredentialsProvider.java    From bazel with Apache License 2.0 5 votes vote down vote up
private AWSCredentialsProvider fromAssumeRole() {
    if (StringUtils.isNullOrEmpty(profile.getRoleSourceProfile())) {
        throw new SdkClientException(String.format(
                "Unable to load credentials from profile [%s]: Source profile name is not specified",
                profile.getProfileName()));
    }

    final BasicProfile sourceProfile = allProfiles
            .getProfile(this.profile.getRoleSourceProfile());
    if (sourceProfile == null) {
        throw new SdkClientException(String.format(
                "Unable to load source profile [%s]: Source profile was not found [%s]",
                profile.getProfileName(), profile.getRoleSourceProfile()));
    }
    AWSCredentials sourceCredentials = new ProfileStaticCredentialsProvider(sourceProfile)
            .getCredentials();


    final String roleSessionName = (this.profile.getRoleSessionName() == null) ?
            "aws-sdk-java-" + System.currentTimeMillis() : this.profile.getRoleSessionName();

    RoleInfo roleInfo = new RoleInfo().withRoleArn(this.profile.getRoleArn())
            .withRoleSessionName(roleSessionName)
            .withExternalId(this.profile.getRoleExternalId())
            .withLongLivedCredentials(sourceCredentials);
    return profileCredentialsService.getAssumeRoleCredentialsProvider(roleInfo);
}
 
Example #30
Source File: S3UploaderTest.java    From incubator-heron with Apache License 2.0 5 votes vote down vote up
@Test(expected = UploaderException.class)
@SuppressWarnings("unchecked")
public void handlePutObjectExceptionOnUpload() throws Exception {
  String expectedRemotePath = "test-topology/topology.tar.gz";
  String expectedBucket = "bucket";

  when(mockS3Client.doesObjectExist(expectedBucket, expectedRemotePath)).thenReturn(true);
  when(mockS3Client.putObject(Mockito.eq(expectedBucket), Mockito.eq(expectedRemotePath),
      Mockito.any(File.class))).thenThrow(SdkClientException.class);
  uploader.uploadPackage();
}