Java Code Examples for com.amazonaws.AmazonServiceException#setStatusCode()

The following examples show how to use com.amazonaws.AmazonServiceException#setStatusCode() . 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: SimpleDbOperationRetrierTest.java    From spring-data-simpledb with MIT License 6 votes vote down vote up
@Test
public void executeWithRetries_should_fail_for_exceeded_retries() throws Exception {

	AbstractServiceUnavailableOperationRetrier retrier = new AbstractServiceUnavailableOperationRetrier(SERVICE_UNAVAILABLE_RETRIES) {

		@Override
		public void execute() {
			AmazonServiceException serviceException = new AmazonServiceException("Test message");
			serviceException.setStatusCode(SERVICE_UNAVAILABLE_STATUS_CODE);
			serviceException.setErrorType(AmazonServiceException.ErrorType.Service);
			throw serviceException;
		}
	};

	try {
		retrier.executeWithRetries();
		fail("Number of retries should be exceeded");
	} catch(DataAccessResourceFailureException e) {
		// Our Exception -- ...times
		assertThat(e.getMessage(), StringContains.containsString("times"));
	}
}
 
Example 2
Source File: AwsPlatformResourcesTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void collectAccessConfigsWhenUserGetAmazonExceptionToGetInfoThenItShouldReturnEmptyList() {
    AmazonServiceException amazonServiceException = new AmazonServiceException("Amazon problem.");
    amazonServiceException.setStatusCode(404);
    amazonServiceException.setErrorMessage("Amazon problem.");

    when(awsClient.createAmazonIdentityManagement(any(AwsCredentialView.class))).thenReturn(amazonCFClient);
    when(amazonCFClient.listInstanceProfiles(any(ListInstanceProfilesRequest.class))).thenThrow(amazonServiceException);

    thrown.expect(CloudConnectorException.class);
    thrown.expectMessage("Amazon problem.");

    CloudAccessConfigs cloudAccessConfigs =
            underTest.accessConfigs(new CloudCredential("crn", "aws-credential"), region(REGION_NAME), Collections.emptyMap());

    Assert.assertEquals(0L, cloudAccessConfigs.getCloudAccessConfigs().size());
}
 
Example 3
Source File: AwsPlatformResourcesTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void collectAccessConfigsWhenUserIsUnathorizedToGetInfoThenItShouldReturnEmptyList() {
    AmazonServiceException amazonServiceException = new AmazonServiceException("unauthorized.");
    amazonServiceException.setStatusCode(403);

    when(awsClient.createAmazonIdentityManagement(any(AwsCredentialView.class))).thenReturn(amazonCFClient);
    when(amazonCFClient.listInstanceProfiles(any(ListInstanceProfilesRequest.class))).thenThrow(amazonServiceException);

    thrown.expect(CloudConnectorException.class);
    thrown.expectMessage("unauthorized.");

    CloudAccessConfigs cloudAccessConfigs =
            underTest.accessConfigs(new CloudCredential("crn", "aws-credential"), region(REGION_NAME), new HashMap<>());

    Assert.assertEquals(0L, cloudAccessConfigs.getCloudAccessConfigs().size());
}
 
Example 4
Source File: EC2CredentialsUtils.java    From bazel with Apache License 2.0 6 votes vote down vote up
private void handleErrorResponse(InputStream errorStream, int statusCode, String responseMessage) throws IOException {
    String errorCode = null;

    // Parse the error stream returned from the service.
    if(errorStream != null) {
        try (Reader errorReader = new InputStreamReader(errorStream, Charsets.UTF_8)) {
            String errorResponse = CharStreams.toString(errorReader);
            JsonParser parser = new JsonParser();

            JsonObject node = parser.parse(errorResponse).getAsJsonObject();
            JsonElement code = node.get("code");
            JsonElement message = node.get("message");
            if (code != null && message != null) {
                errorCode = code.getAsString();
                responseMessage = message.getAsString();
            }
        } catch (Exception exception) {
            LOG.debug("Unable to parse error stream");
        }
    }

    AmazonServiceException ase = new AmazonServiceException(responseMessage);
    ase.setStatusCode(statusCode);
    ase.setErrorCode(errorCode);
    throw ase;
}
 
Example 5
Source File: MockCloudStore.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Override
AWSSecurityTokenServiceClient getTokenServiceClient() {
    if (exceptionStatusCode != 0) {
        if (amazonException) {
            AmazonServiceException ex = new AmazonServiceException("Error");
            ex.setStatusCode(exceptionStatusCode);
            throw ex;
        } else {
            throw new IllegalArgumentException("Error");
        }
    } else {
        AWSSecurityTokenServiceClient client = Mockito.mock(AWSSecurityTokenServiceClient.class);
        Mockito.when(client.assumeRole(Mockito.any(AssumeRoleRequest.class))).thenReturn(assumeRoleResult);
        Mockito.when(client.getCallerIdentity(Mockito.any(GetCallerIdentityRequest.class))).thenReturn(callerIdentityResult);
        return client;
    }
}
 
Example 6
Source File: SimpleAwsResponseHandler.java    From charles-rest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public HttpResponse handle(HttpResponse response) {

    int status = response.getStatusCode();
    if(status < 200 || status >= 300) {
        String content;
        final StringWriter writer = new StringWriter();
        try {
            IOUtils.copy(response.getContent(), writer, "UTF-8");
            content = writer.toString();
        } catch (final IOException e) {
        	content = "Couldn't get response content!";
        }
        AmazonServiceException ase = new AmazonServiceException(content);
        ase.setStatusCode(status);
        throw ase;
    }

    return response;
    
}
 
Example 7
Source File: AwsNetworkConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateNewNetworkWithSubnetsShouldCreateTheNetworkAndSubnets() {
    String networkCidr = "0.0.0.0/16";
    Set<NetworkSubnetRequest> subnets = Set.of(new NetworkSubnetRequest("1.1.1.1/8", PUBLIC), new NetworkSubnetRequest("1.1.1.2/8", PUBLIC));
    AmazonCloudFormationRetryClient cloudFormationRetryClient = mock(AmazonCloudFormationRetryClient.class);
    AmazonServiceException amazonServiceException = new AmazonServiceException("does not exist");
    amazonServiceException.setStatusCode(400);
    when(cloudFormationRetryClient.describeStacks(any(DescribeStacksRequest.class))).thenThrow(amazonServiceException);
    AmazonCloudFormationClient cfClient = mock(AmazonCloudFormationClient.class);
    AmazonEC2Client ec2Client = mock(AmazonEC2Client.class);
    Map<String, String> output = createOutput();
    NetworkCreationRequest networkCreationRequest = createNetworkRequest(networkCidr, subnets);
    List<SubnetRequest> subnetRequestList = createSubnetRequestList();
    Set<CreatedSubnet> createdSubnets = Set.of(new CreatedSubnet(), new CreatedSubnet(), new CreatedSubnet());

    when(awsClient.createAccess(any(), any())).thenReturn(ec2Client);
    when(awsSubnetRequestProvider.provide(ec2Client, new ArrayList<>(subnets), new ArrayList<>(subnets))).thenReturn(subnetRequestList);
    when(awsClient.createCloudFormationRetryClient(any(AwsCredentialView.class), eq(REGION.value()))).thenReturn(cloudFormationRetryClient);
    when(awsClient.createCloudFormationClient(any(AwsCredentialView.class), eq(REGION.value()))).thenReturn(cfClient);
    when(cfClient.waiters()).thenReturn(cfWaiters);
    when(cfWaiters.stackCreateComplete()).thenReturn(creationWaiter);
    when(cfStackUtil.getOutputs(NETWORK_ID, cloudFormationRetryClient)).thenReturn(output);
    when(awsCreatedSubnetProvider.provide(output, subnetRequestList, true)).thenReturn(createdSubnets);

    CreatedCloudNetwork actual = underTest.createNetworkWithSubnets(networkCreationRequest);

    verify(awsClient).createCloudFormationRetryClient(any(AwsCredentialView.class), eq(REGION.value()));
    verify(awsNetworkCfTemplateProvider).provide(networkCreationRequest, subnetRequestList);
    verify(awsClient).createCloudFormationClient(any(AwsCredentialView.class), eq(REGION.value()));
    verify(creationWaiter, times(1)).run(any());
    verify(awsTaggingService).prepareCloudformationTags(any(), any());
    verify(cloudFormationRetryClient).createStack(any(CreateStackRequest.class));
    verify(cfStackUtil).getOutputs(NETWORK_ID, cloudFormationRetryClient);
    assertEquals(VPC_ID, actual.getNetworkId());
    assertEquals(NUMBER_OF_SUBNETS, actual.getSubnets().size());
}
 
Example 8
Source File: AwsServiceHelperTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleAmazonExceptionWithNotFoundException()
{
    try
    {
        AmazonServiceException amazonServiceException = new AmazonServiceException(ERROR_MESSAGE);
        amazonServiceException.setStatusCode(HttpStatus.SC_NOT_FOUND);
        awsServiceHelper.handleAmazonException(amazonServiceException, MESSAGE_TEXT);
        fail();
    }
    catch (ObjectNotFoundException objectNotFoundException)
    {
        assertThat("Error message not correct.", objectNotFoundException.getMessage().contains(MESSAGE_TEXT), is(true));
    }
}
 
Example 9
Source File: AwsServiceHelperTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleAmazonExceptionWithBadRequestException()
{
    try
    {
        AmazonServiceException amazonServiceException = new AmazonServiceException(ERROR_MESSAGE);
        amazonServiceException.setStatusCode(HttpStatus.SC_BAD_REQUEST);
        awsServiceHelper.handleAmazonException(amazonServiceException, MESSAGE_TEXT);
        fail();
    }
    catch (IllegalArgumentException illegalArgumentException)
    {
        assertThat("Error message not correct.", illegalArgumentException.getMessage().contains(MESSAGE_TEXT), is(true));
    }
}
 
Example 10
Source File: ErrorResponseHandler.java    From getting-started with MIT License 5 votes vote down vote up
@Override
public AmazonServiceException handle(final HttpResponse response) {
  final AmazonServiceException ase = new AmazonServiceException(response.getStatusText());
  ase.setStatusCode(response.getStatusCode());
  try {
    final String content = IOUtils.toString(response.getContent()).trim();
    ase.setRawResponseContent(content);
  } catch (IOException exception) {
    System.err.println("Exception thrown while reading the response's content: " + exception);
  }

  return ase;
}
 
Example 11
Source File: BooleanAwsResponseHandler.java    From charles-rest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Boolean handle(HttpResponse response) {
    int status = response.getStatusCode();
    if (status != HttpStatus.SC_OK && status != HttpStatus.SC_NOT_FOUND) {
        AmazonServiceException ase = new AmazonServiceException(
                "Unexpected status: " + status);
        ase.setStatusCode(status);
        throw ase;
    }
    return status == HttpStatus.SC_OK ? true : false;
}
 
Example 12
Source File: SearchResponseHandler.java    From charles-rest with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public ElasticSearchResults handle(HttpResponse response) {
    int status = response.getStatusCode();
    if(status < 200 || status >= 300) {
        AmazonServiceException ase = new AmazonServiceException("Unexpected status: " + status);
        ase.setStatusCode(status);
        throw ase;
    }
    return new ElasticSearchResults(
        Json.createReader(
            response.getContent()
        ).readObject()
    );
}
 
Example 13
Source File: DynamoDBFibonacciRetryerTest.java    From emr-dynamodb-connector with Apache License 2.0 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void testNonRetryableASEException() throws Exception {
  AmazonServiceException ase = new AmazonServiceException("Test");
  ase.setErrorCode("ArbitNonRetryableException");
  ase.setStatusCode(400);
  when(call.call()).thenThrow(ase);
  DynamoDBFibonacciRetryer retryer = new DynamoDBFibonacciRetryer(Duration.standardSeconds(10));

  try {
    retryer.runWithRetry(call, null, null);
  } finally {
    verify(call).call();
  }
}
 
Example 14
Source File: DynamoDBFibonacciRetryerTest.java    From emr-dynamodb-connector with Apache License 2.0 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void testRetryableASEException2() throws Exception {
  AmazonServiceException ase = new AmazonServiceException("Test");
  ase.setErrorCode("ArbitRetryableException");
  ase.setStatusCode(503);
  when(call.call()).thenThrow(ase);
  DynamoDBFibonacciRetryer retryer = new DynamoDBFibonacciRetryer(Duration.standardSeconds(10));

  try {
    retryer.runWithRetry(call, null, null);
  } finally {
    verify(call, atLeast(2)).call();
    verify(call, atMost(15)).call();
  }
}
 
Example 15
Source File: DynamoDBFibonacciRetryerTest.java    From emr-dynamodb-connector with Apache License 2.0 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void testRetryableASEException() throws Exception {
  AmazonServiceException ase = new AmazonServiceException("Test");
  ase.setErrorCode("ArbitRetryableException");
  ase.setStatusCode(500);
  when(call.call()).thenThrow(ase);
  DynamoDBFibonacciRetryer retryer = new DynamoDBFibonacciRetryer(Duration.standardSeconds(10));

  try {
    retryer.runWithRetry(call, null, null);
  } finally {
    verify(call, atLeastOnce()).call();
    verify(call, atMost(15)).call();
  }
}
 
Example 16
Source File: DynamoDBFibonacciRetryerTest.java    From emr-dynamodb-connector with Apache License 2.0 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void testRetryThrottleException() throws Exception {
  AmazonServiceException ase = new AmazonServiceException("Test");
  ase.setErrorCode("ProvisionedThroughputExceededException");
  ase.setStatusCode(400);
  when(call.call()).thenThrow(ase);
  DynamoDBFibonacciRetryer retryer = new DynamoDBFibonacciRetryer(Duration.standardSeconds(10));

  try {
    retryer.runWithRetry(call, null, null);
  } finally {
    verify(call, atLeast(2)).call();
    verify(call, atMost(15)).call();
  }
}
 
Example 17
Source File: AmazonServiceExceptionMappingServiceTest.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testAccessFailure() {
    final AmazonServiceException f = new AmazonServiceException("message", null);
    f.setStatusCode(403);
    f.setErrorCode("AccessDenied");
    assertTrue(new AmazonServiceExceptionMappingService().map(f) instanceof AccessDeniedException);
    f.setErrorCode("SignatureDoesNotMatch");
    assertTrue(new AmazonServiceExceptionMappingService().map(f) instanceof LoginFailureException);
}
 
Example 18
Source File: SimpleAwsErrorHandler.java    From charles-rest with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public AmazonServiceException handle(HttpResponse response) {
    AmazonServiceException ase = new AmazonServiceException(response.getStatusText());
    ase.setStatusCode(response.getStatusCode());
    return ase;
}
 
Example 19
Source File: MockEmrOperationsImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public String runEmrJobFlow(AmazonElasticMapReduceClient emrClient, RunJobFlowRequest jobFlowRequest)
{
    String clusterStatus = ClusterState.BOOTSTRAPPING.toString();

    StatusChangeReason reason = new StatusChangeReason(ClusterStateChangeReasonCode.USER_REQUEST.toString(), "Started " + clusterStatus);
    StatusTimeline timeline = new StatusTimeline();
    timeline.setCreationTime(HerdDateUtils.getXMLGregorianCalendarValue(new Date()));

    if (StringUtils.isNotBlank(jobFlowRequest.getAmiVersion()))
    {
        if (jobFlowRequest.getAmiVersion().equals(MockAwsOperationsHelper.AMAZON_THROTTLING_EXCEPTION))
        {
            AmazonServiceException throttlingException = new AmazonServiceException("test throttling exception");
            throttlingException.setErrorCode("ThrottlingException");

            throw throttlingException;
        }
        else if (jobFlowRequest.getAmiVersion().equals(MockAwsOperationsHelper.AMAZON_BAD_REQUEST))
        {
            AmazonServiceException badRequestException = new AmazonServiceException(MockAwsOperationsHelper.AMAZON_BAD_REQUEST);
            badRequestException.setStatusCode(HttpStatus.SC_BAD_REQUEST);
            throw badRequestException;
        }
        else if (jobFlowRequest.getAmiVersion().equals(MockAwsOperationsHelper.AMAZON_NOT_FOUND))
        {
            AmazonServiceException notFoundException = new AmazonServiceException(MockAwsOperationsHelper.AMAZON_NOT_FOUND);
            notFoundException.setStatusCode(HttpStatus.SC_NOT_FOUND);
            throw notFoundException;
        }
        else if (jobFlowRequest.getAmiVersion().equals(MockAwsOperationsHelper.AMAZON_SERVICE_EXCEPTION))
        {
            throw new AmazonServiceException(MockAwsOperationsHelper.AMAZON_SERVICE_EXCEPTION);
        }
        else if (jobFlowRequest.getAmiVersion().equals(MockAwsOperationsHelper.AMAZON_CLUSTER_STATUS_WAITING))
        {
            clusterStatus = ClusterState.WAITING.toString();
        }
        else if (jobFlowRequest.getAmiVersion().equals(MockAwsOperationsHelper.AMAZON_CLUSTER_STATUS_RUNNING))
        {
            clusterStatus = ClusterState.RUNNING.toString();
        }
    }


    return createNewCluster(jobFlowRequest, clusterStatus, reason, timeline).getJobFlowId();
}
 
Example 20
Source File: AmazonServiceExceptionMappingServiceTest.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testLoginFailure() {
    final AmazonServiceException f = new AmazonServiceException("message", null);
    f.setStatusCode(401);
    assertTrue(new AmazonServiceExceptionMappingService().map(f) instanceof LoginFailureException);
}