Search in sources :

Example 1 with AmazonWebServiceResponse

use of com.amazonaws.AmazonWebServiceResponse in project aws-sdk-android by aws-amplify.

the class AmazonHttpClientTest method testTemporaryRedirect.

@Test
public void testTemporaryRedirect() throws IOException, URISyntaxException {
    HttpResponse redirectResponse = HttpResponse.builder().statusCode(307).header("Location", "https://www.redirect.com").build();
    HttpResponse successfulResponse = HttpResponse.builder().statusCode(200).content(null).build();
    final Request<?> request = new DefaultRequest<String>(new AmazonWebServiceRequest() {
    }, "TestService");
    request.setHttpMethod(HttpMethodName.GET);
    request.setEndpoint(new URI("https://www.test.com"));
    request.setResourcePath("/test/table");
    HttpResponseHandler<AmazonWebServiceResponse<String>> responseHandler = new HttpResponseHandler<AmazonWebServiceResponse<String>>() {

        @Override
        public AmazonWebServiceResponse<String> handle(HttpResponse response) throws Exception {
            AmazonWebServiceResponse<String> awsResponse = new AmazonWebServiceResponse<String>();
            awsResponse.setResult("Result");
            return awsResponse;
        }

        @Override
        public boolean needsConnectionLeftOpen() {
            return false;
        }
    };
    ExecutionContext ec = EasyMock.createMock(ExecutionContext.class);
    EasyMock.reset(httpClient, ec);
    final List<Boolean> signerCalled = new ArrayList<Boolean>();
    EasyMock.expect(ec.getAwsRequestMetrics()).andReturn(new AWSRequestMetrics()).anyTimes();
    EasyMock.expect(ec.getContextUserAgent()).andReturn("TestUserAgent").anyTimes();
    EasyMock.expect(ec.getCredentials()).andReturn(new AnonymousAWSCredentials());
    EasyMock.expect(ec.getSignerByURI(EasyMock.anyObject(URI.class))).andReturn(new Signer() {

        @Override
        public void sign(Request<?> requestToSign, AWSCredentials credentials) {
            assertSame(request, requestToSign);
            assertTrue(credentials instanceof AnonymousAWSCredentials);
            signerCalled.add(true);
        }
    });
    EasyMock.expect(httpClient.execute(EasyMock.<HttpRequest>anyObject())).andReturn(redirectResponse);
    Capture<HttpRequest> capture = new Capture<HttpRequest>();
    EasyMock.expect(httpClient.execute(EasyMock.capture(capture))).andReturn(successfulResponse);
    EasyMock.replay(httpClient, ec);
    Response<String> response = client.executeHelper(request, responseHandler, null, ec);
    assertEquals(response.getAwsResponse(), "Result");
    assertEquals(signerCalled.size(), 2);
    assertTrue(signerCalled.get(0));
    assertTrue(signerCalled.get(1));
    assertEquals(capture.getValue().getUri().toString(), "https://www.redirect.com/");
    EasyMock.verify(httpClient, ec);
}
Also used : DefaultRequest(com.amazonaws.DefaultRequest) AWSRequestMetrics(com.amazonaws.util.AWSRequestMetrics) ArrayList(java.util.ArrayList) AnonymousAWSCredentials(com.amazonaws.auth.AnonymousAWSCredentials) AmazonWebServiceResponse(com.amazonaws.AmazonWebServiceResponse) AmazonWebServiceRequest(com.amazonaws.AmazonWebServiceRequest) URI(java.net.URI) AnonymousAWSCredentials(com.amazonaws.auth.AnonymousAWSCredentials) AWSCredentials(com.amazonaws.auth.AWSCredentials) Capture(org.easymock.Capture) Signer(com.amazonaws.auth.Signer) Test(org.junit.Test)

Example 2 with AmazonWebServiceResponse

use of com.amazonaws.AmazonWebServiceResponse in project aws-sdk-android by aws-amplify.

the class AmazonHttpClientTest method testHostPrefixPrepend.

@Test
@SuppressWarnings("unchecked")
public void testHostPrefixPrepend() throws Exception {
    HttpResponse successfulResponse = HttpResponse.builder().statusCode(200).content(null).build();
    HttpResponseHandler<AmazonWebServiceResponse<Object>> handler = EasyMock.createMock(HttpResponseHandler.class);
    EasyMock.expect(handler.needsConnectionLeftOpen()).andReturn(false);
    EasyMock.expect(handler.handle(EasyMock.anyObject(HttpResponse.class))).andReturn(new AmazonWebServiceResponse<>());
    EasyMock.replay(handler);
    Capture<HttpRequest> httpRequest = new Capture<>();
    EasyMock.expect(httpClient.execute(EasyMock.capture(httpRequest))).andReturn(successfulResponse);
    EasyMock.replay(httpClient);
    Request<?> request = new DefaultRequest<Object>("test");
    request.setContent(new ByteArrayInputStream("test".getBytes()));
    request.setHostPrefix("test.");
    request.setEndpoint(URI.create("http://region.amazonaws.com/"));
    client.execute(request, handler, null, new ExecutionContext());
    assertEquals(request.getContent(), httpRequest.getValue().getContent());
    assertEquals(URI.create("http://test.region.amazonaws.com/"), httpRequest.getValue().getUri());
}
Also used : DefaultRequest(com.amazonaws.DefaultRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) AmazonWebServiceResponse(com.amazonaws.AmazonWebServiceResponse) Capture(org.easymock.Capture) Test(org.junit.Test)

Example 3 with AmazonWebServiceResponse

use of com.amazonaws.AmazonWebServiceResponse in project aws-sdk-android by aws-amplify.

the class JsonResponseHandler method handle.

/**
 * @see com.amazonaws.http.HttpResponseHandler#handle(com.amazonaws.http.HttpResponse)
 */
@Override
public AmazonWebServiceResponse<T> handle(HttpResponse response) throws Exception {
    log.trace("Parsing service response JSON");
    final String crc32Checksum = response.getHeaders().get("x-amz-crc32");
    // Get the raw content input stream to calculate the crc32 checksum on
    // gzipped data.
    InputStream content = response.getRawContent();
    if (content == null) {
        // An empty input stream to avoid NPE
        content = new ByteArrayInputStream("{}".getBytes(StringUtils.UTF8));
    }
    log.debug("CRC32Checksum = " + crc32Checksum);
    log.debug("content encoding = " + response.getHeaders().get("Content-Encoding"));
    boolean isGzipEncoded = "gzip".equals(response.getHeaders().get("Content-Encoding"));
    CRC32ChecksumCalculatingInputStream checksumCalculatingInputStream = null;
    // encoded, no checksum) is already handled: we'll just operate on the raw content stream.
    if (crc32Checksum != null) {
        checksumCalculatingInputStream = new CRC32ChecksumCalculatingInputStream(content);
        content = checksumCalculatingInputStream;
    }
    if (isGzipEncoded) {
        content = new GZIPInputStream(content);
    }
    final AwsJsonReader jsonReader = JsonUtils.getJsonReader(new InputStreamReader(content, StringUtils.UTF8));
    try {
        final AmazonWebServiceResponse<T> awsResponse = new AmazonWebServiceResponse<T>();
        final JsonUnmarshallerContext unmarshallerContext = new JsonUnmarshallerContext(jsonReader, response);
        final T result = responseUnmarshaller.unmarshall(unmarshallerContext);
        if (checksumCalculatingInputStream != null) {
            final long serverSideCRC = Long.parseLong(crc32Checksum);
            final long clientSideCRC = checksumCalculatingInputStream.getCRC32Checksum();
            if (clientSideCRC != serverSideCRC) {
                throw new CRC32MismatchException("Client calculated crc32 checksum didn't match that calculated by server side");
            }
        }
        awsResponse.setResult(result);
        final Map<String, String> metadata = new HashMap<String, String>();
        metadata.put(ResponseMetadata.AWS_REQUEST_ID, response.getHeaders().get("x-amzn-RequestId"));
        awsResponse.setResponseMetadata(new ResponseMetadata(metadata));
        log.trace("Done parsing service response");
        return awsResponse;
    } finally {
        if (!needsConnectionLeftOpen) {
            try {
                jsonReader.close();
            } catch (final IOException e) {
                log.warn("Error closing json parser", e);
            }
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) CRC32ChecksumCalculatingInputStream(com.amazonaws.util.CRC32ChecksumCalculatingInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) CRC32ChecksumCalculatingInputStream(com.amazonaws.util.CRC32ChecksumCalculatingInputStream) IOException(java.io.IOException) AmazonWebServiceResponse(com.amazonaws.AmazonWebServiceResponse) AwsJsonReader(com.amazonaws.util.json.AwsJsonReader) CRC32MismatchException(com.amazonaws.internal.CRC32MismatchException) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) JsonUnmarshallerContext(com.amazonaws.transform.JsonUnmarshallerContext) ResponseMetadata(com.amazonaws.ResponseMetadata)

Example 4 with AmazonWebServiceResponse

use of com.amazonaws.AmazonWebServiceResponse in project aws-sdk-android by aws-amplify.

the class AbstractS3ResponseHandler method parseResponseMetadata.

/**
 * Parses the S3 response metadata (ex: AWS request ID) from the specified
 * response, and returns a AmazonWebServiceResponse<T> object ready for the
 * result to be plugged in.
 *
 * @param response The response containing the response metadata to pull
 *            out.
 * @return A new, populated AmazonWebServiceResponse<T> object, ready for
 *         the result to be plugged in.
 */
protected AmazonWebServiceResponse<T> parseResponseMetadata(HttpResponse response) {
    final AmazonWebServiceResponse<T> awsResponse = new AmazonWebServiceResponse<T>();
    final String awsRequestId = response.getHeaders().get(Headers.REQUEST_ID);
    final String hostId = response.getHeaders().get(Headers.EXTENDED_REQUEST_ID);
    final String cloudFrontId = response.getHeaders().get(Headers.CLOUD_FRONT_ID);
    final Map<String, String> metadataMap = new HashMap<String, String>();
    metadataMap.put(ResponseMetadata.AWS_REQUEST_ID, awsRequestId);
    metadataMap.put(S3ResponseMetadata.HOST_ID, hostId);
    metadataMap.put(S3ResponseMetadata.CLOUD_FRONT_ID, cloudFrontId);
    awsResponse.setResponseMetadata(new S3ResponseMetadata(metadataMap));
    return awsResponse;
}
Also used : S3ResponseMetadata(com.amazonaws.services.s3.S3ResponseMetadata) HashMap(java.util.HashMap) AmazonWebServiceResponse(com.amazonaws.AmazonWebServiceResponse)

Example 5 with AmazonWebServiceResponse

use of com.amazonaws.AmazonWebServiceResponse in project aws-sdk-android by aws-amplify.

the class ResponseHeaderHandlerChainTest method testResponseHeaderHandlerChain.

@Test
public void testResponseHeaderHandlerChain() throws Exception {
    final List<Boolean> called = new ArrayList<Boolean>();
    final HttpResponse testResponse = new HttpResponse.Builder().build();
    @SuppressWarnings("unchecked") ResponseHeaderHandlerChain<AmazonWebServiceResponse<String>> chain = new ResponseHeaderHandlerChain<AmazonWebServiceResponse<String>>(new Unmarshaller<AmazonWebServiceResponse<String>, InputStream>() {

        @Override
        public AmazonWebServiceResponse<String> unmarshall(InputStream in) throws Exception {
            called.add(true);
            return new AmazonWebServiceResponse<String>();
        }
    }, new HeaderHandler<AmazonWebServiceResponse<String>>() {

        @Override
        public void handle(AmazonWebServiceResponse<String> result, HttpResponse response) {
            assertSame(response, testResponse);
            called.add(true);
        }
    }, new HeaderHandler<AmazonWebServiceResponse<String>>() {

        @Override
        public void handle(AmazonWebServiceResponse<String> result, HttpResponse response) {
            assertSame(response, testResponse);
            called.add(true);
        }
    });
    chain.handle(testResponse);
    assertEquals(called.size(), 3);
    assertTrue(called.get(0));
    assertTrue(called.get(1));
    assertTrue(called.get(2));
}
Also used : InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) HttpResponse(com.amazonaws.http.HttpResponse) AmazonWebServiceResponse(com.amazonaws.AmazonWebServiceResponse) Test(org.junit.Test)

Aggregations

AmazonWebServiceResponse (com.amazonaws.AmazonWebServiceResponse)9 ByteArrayInputStream (java.io.ByteArrayInputStream)4 InputStream (java.io.InputStream)4 Test (org.junit.Test)4 DefaultRequest (com.amazonaws.DefaultRequest)3 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 AmazonClientException (com.amazonaws.AmazonClientException)2 ResponseMetadata (com.amazonaws.ResponseMetadata)2 AWSCredentials (com.amazonaws.auth.AWSCredentials)2 Signer (com.amazonaws.auth.Signer)2 AWSRequestMetrics (com.amazonaws.util.AWSRequestMetrics)2 URI (java.net.URI)2 ArrayList (java.util.ArrayList)2 Capture (org.easymock.Capture)2 AmazonServiceException (com.amazonaws.AmazonServiceException)1 AmazonWebServiceRequest (com.amazonaws.AmazonWebServiceRequest)1 Response (com.amazonaws.Response)1 AnonymousAWSCredentials (com.amazonaws.auth.AnonymousAWSCredentials)1 HttpResponse (com.amazonaws.http.HttpResponse)1