@Test public void testExecute_noApiKey_noCreds() throws IOException { client = new GenericApiGatewayClientBuilder() .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com") .withRegion(Region.getRegion(Regions.fromName("us-east-1"))) .withClientConfiguration(new ClientConfiguration()) .withHttpClient(new AmazonHttpClient(new ClientConfiguration(), mockClient, null)) .build(); GenericApiGatewayResponse response = client.execute( new GenericApiGatewayRequestBuilder() .withBody(new ByteArrayInputStream("test request".getBytes())) .withHttpMethod(HttpMethodName.POST) .withResourcePath("/test/orders").build()); assertEquals("Wrong response body", "test payload", response.getBody()); assertEquals("Wrong response status", 200, response.getHttpResponse().getStatusCode()); Mockito.verify(mockClient, times(1)).execute(argThat(new LambdaMatcher<>( x -> (x.getMethod().equals("POST") && x.getFirstHeader("x-api-key") == null && x.getFirstHeader("Authorization") == null && x.getURI().toString().equals("https://foobar.execute-api.us-east-1.amazonaws.com/test/orders")))), any(HttpContext.class)); }
@Test(timeout = TEST_TIMEOUT) public void requestTimeoutEnabled_HonorsRetryPolicy() throws IOException { int maxRetries = 2; ClientConfiguration config = new ClientConfiguration().withRequestTimeout(1 * 1000) .withMaxErrorRetry(maxRetries); HttpClientFactory<ConnectionManagerAwareHttpClient> httpClientFactory = new ApacheHttpClientFactory(); ConnectionManagerAwareHttpClient rawHttpClient = spy(httpClientFactory.create(HttpClientSettings.adapt(config))); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { execute(httpClient, newGetRequest()); fail("Exception expected"); } catch (AmazonClientException e) { /* the expected exception and number of requests. */ assertThat(e.getCause(), instanceOf(HttpRequestTimeoutException.class)); int expectedNumberOfRequests = 1 + maxRetries; assertNumberOfRetries(rawHttpClient, expectedNumberOfRequests); assertNumberOfTasksTriggered(httpClient.getHttpRequestTimer(), expectedNumberOfRequests); } }
@Test public void requestTimeoutEnabled_RequestCompletesWithinTimeout_TaskCanceledAndEntityBuffered() throws Exception { ClientConfiguration config = new ClientConfiguration().withRequestTimeout(5 * 1000).withMaxErrorRetry(0); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); HttpResponseProxy responseProxy = createHttpResponseProxySpy(); doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { execute(httpClient, createMockGetRequest()); fail("Exception expected"); } catch (AmazonClientException e) { NullResponseHandler.assertIsUnmarshallingException(e); } assertResponseIsBuffered(responseProxy); ScheduledThreadPoolExecutor requestTimerExecutor = httpClient.getHttpRequestTimer().getExecutor(); assertTimerNeverTriggered(requestTimerExecutor); assertCanceledTasksRemoved(requestTimerExecutor); // Core threads should be spun up on demand. Since only one task was submitted only one // thread should exist assertEquals(1, requestTimerExecutor.getPoolSize()); assertCoreThreadsShutDownAfterBeingIdle(requestTimerExecutor); }
/** * Response to HEAD requests don't have an entity so we shouldn't try to wrap the response in a * {@link BufferedHttpEntity}. */ @Test public void requestTimeoutEnabled_HeadRequestCompletesWithinTimeout_EntityNotBuffered() throws Exception { ClientConfiguration config = new ClientConfiguration().withRequestTimeout(5 * 1000).withMaxErrorRetry(0); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); HttpResponseProxy responseProxy = createHttpHeadResponseProxy(); doReturn(responseProxy).when(rawHttpClient).execute(any(HttpHead.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { execute(httpClient, createMockHeadRequest()); fail("Exception expected"); } catch (AmazonClientException e) { NullResponseHandler.assertIsUnmarshallingException(e); } assertNull(responseProxy.getEntity()); }
@Test public void requestTimeoutDisabled_RequestCompletesWithinTimeout_EntityNotBuffered() throws Exception { ClientConfiguration config = new ClientConfiguration().withRequestTimeout(0); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); HttpResponseProxy responseProxy = createHttpResponseProxySpy(); doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { execute(httpClient, createMockGetRequest()); fail("Exception expected"); } catch (AmazonClientException e) { } assertResponseWasNotBuffered(responseProxy); }
@Test public void requestTimeoutEnabled_RequestCompletesWithinTimeout_EntityNotBufferedForStreamedResponse() throws Exception { ClientConfiguration config = new ClientConfiguration().withRequestTimeout(5 * 1000); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); HttpResponseProxy responseProxy = createHttpResponseProxySpy(); doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { httpClient.requestExecutionBuilder().request(createMockGetRequest()).execute(new ErrorDuringUnmarshallingResponseHandler().leaveConnectionOpen()); fail("Exception expected"); } catch (AmazonClientException e) { } assertResponseWasNotBuffered(responseProxy); }
@Test(timeout = TEST_TIMEOUT) public void requestTimeoutSetInRequestObject_TakesPrecedenceOverClientConfiguration() { // Client configuration is set arbitrarily high so that the test will timeout if the // client configuration is incorrectly honored over the request config httpClient = new AmazonHttpClient(new ClientConfiguration().withSocketTimeout(LONGER_SOCKET_TIMEOUT) .withRequestTimeout(REQUEST_TIMEOUT * 1000).withMaxErrorRetry(0)); try { EmptyHttpRequest request = newGetRequest(); request.setOriginalRequest(new EmptyAmazonWebServiceRequest().withSdkRequestTimeout(REQUEST_TIMEOUT)); execute(httpClient, request); fail("Exception expected"); } catch (AmazonClientException e) { assertThat(e.getCause(), instanceOf(HttpRequestTimeoutException.class)); } }
@Test(timeout = TEST_TIMEOUT) public void requestTimeoutDisabledInRequestObject_TakesPrecedenceOverClientConfiguration() { final int socketTimeout = REQUEST_TIMEOUT; // Client configuration is set arbitrarily low so that the request will be aborted if // the client configuration is incorrectly honored over the request config httpClient = new AmazonHttpClient( new ClientConfiguration().withSocketTimeout(socketTimeout).withRequestTimeout(1).withMaxErrorRetry(0)); try { EmptyHttpRequest request = newGetRequest(); request.setOriginalRequest(new EmptyAmazonWebServiceRequest().withSdkRequestTimeout(0)); execute(httpClient, request); fail("Exception expected"); } catch (AmazonClientException e) { assertThat(e.getCause(), instanceOf(SocketTimeoutException.class)); } }
@Test(timeout = TEST_TIMEOUT) public void requestTimeoutEnabled_ServerRespondsWithRetryableError_RetriesUpToLimitThenThrowsServerException() throws IOException { int maxRetries = 2; ClientConfiguration config = new ClientConfiguration().withRequestTimeout(25 * 1000) .withClientExecutionTimeout(25 * 1000).withMaxErrorRetry(maxRetries); HttpClientFactory<ConnectionManagerAwareHttpClient> httpClientFactory = new ApacheHttpClientFactory(); ConnectionManagerAwareHttpClient rawHttpClient = spy(httpClientFactory.create(HttpClientSettings.adapt(config))); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { httpClient.execute(newGetRequest(), new ErrorDuringUnmarshallingResponseHandler(), new NullErrorResponseHandler(), new ExecutionContext()); fail("Exception expected"); } catch (AmazonServiceException e) { assertEquals(e.getStatusCode(), STATUS_CODE); int expectedNumberOfRequests = 1 + maxRetries; assertNumberOfRetries(rawHttpClient, expectedNumberOfRequests); assertNumberOfTasksTriggered(httpClient.getHttpRequestTimer(), 0); assertNumberOfTasksTriggered(httpClient.getClientExecutionTimer(), 0); } }
@Test(expected = AbortedException.class) public void clientExecutionTimeoutEnabled_aborted_exception_occurs_timeout_not_expired() throws Exception { ClientConfiguration config = new ClientConfiguration() .withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT) .withMaxErrorRetry(0); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); doThrow(new AbortedException()).when(rawHttpClient).execute(any (HttpRequestBase.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); execute(httpClient, createMockGetRequest()); }
@Test(expected = ClientExecutionTimeoutException.class) public void clientExecutionTimeoutEnabled_aborted_exception_occurs_timeout_expired() throws Exception { ClientConfiguration config = new ClientConfiguration() .withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT) .withMaxErrorRetry(0); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); httpClient = new AmazonHttpClient(config, rawHttpClient, null); execute(httpClient, new EmptyHttpRequest(server.getEndpoint(), HttpMethodName.PUT, new SdkBufferedInputStream(new InputStream() { @Override public int read() throws IOException { // Sleeping here to avoid OOM issues from a limitless InputStream try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return 1; } }))); }
/** * Tests that a streaming operation has it's request properly cleaned up if the client is interrupted after the * response is received. * * @see TT0070103230 */ @Test public void clientInterruptedDuringResponseHandlers_DoesNotLeakConnection() throws IOException { ClientConfiguration config = new ClientConfiguration(); ConnectionManagerAwareHttpClient rawHttpClient = new ApacheHttpClientFactory().create(HttpClientSettings.adapt(config)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); interruptCurrentThreadAfterDelay(1000); List<RequestHandler2> requestHandlers = RequestHandlerTestUtils .buildRequestHandlerList(new SlowRequestHandler().withAfterResponseWaitInSeconds(10)); try { requestBuilder().executionContext(withHandlers(requestHandlers)).execute(new DummyResponseHandler().leaveConnectionOpen()); fail("Expected exception"); } catch (AmazonClientException e) { assertThat(e.getCause(), instanceOf(InterruptedException.class)); } @SuppressWarnings("deprecation") int leasedConnections = ((ConnPoolControl<?>) ((SdkHttpClient)rawHttpClient).getHttpClientConnectionManager()).getTotalStats().getLeased(); assertEquals(0, leasedConnections); }
@Test public void clientExecutionTimeoutDisabled_RequestCompletesWithinTimeout_EntityNotBuffered() throws Exception { ClientConfiguration config = new ClientConfiguration().withClientExecutionTimeout(0); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); HttpResponseProxy responseProxy = createHttpResponseProxySpy(); doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { execute(httpClient, createMockGetRequest()); fail("Exception expected"); } catch (AmazonClientException e) { } assertResponseWasNotBuffered(responseProxy); }
@Test public void clientExecutionTimeoutEnabled_RequestCompletesWithinTimeout_EntityNotBufferedForStreamedResponse() throws Exception { ClientConfiguration config = new ClientConfiguration().withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); HttpResponseProxy responseProxy = createHttpResponseProxySpy(); doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { httpClient.requestExecutionBuilder().request(createMockGetRequest()).execute(new ErrorDuringUnmarshallingResponseHandler().leaveConnectionOpen()); fail("Exception expected"); } catch (AmazonClientException e) { } assertResponseWasNotBuffered(responseProxy); }
/** * The client execution timer uses interrupts to abort the client but if another thread * interrupts the current thread for another reason we don't want to squash the * {@link InterruptedException}. We should set the thread's interrupted status and throw the * exception back out (we can't throw the actual {@link InterruptedException} because it's * checked) */ @Test(timeout = TEST_TIMEOUT) public void interruptCausedBySomethingOtherThanTimer_PropagatesInterruptToCaller() { final int socketTimeoutInMillis = 100; httpClient = new AmazonHttpClient(new ClientConfiguration().withSocketTimeout(socketTimeoutInMillis) .withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT) .withRetryPolicy(new RetryPolicy(PredefinedRetryPolicies.DEFAULT_RETRY_CONDITION, new FixedTimeBackoffStrategy(CLIENT_EXECUTION_TIMEOUT), 1, false))); // We make sure the first connection has failed due to the socket timeout before // interrupting so we know that we are sleeping per the backoff strategy. Apache HTTP // client doesn't seem to honor interrupts reliably but Thread.sleep does interruptCurrentThreadAfterDelay(socketTimeoutInMillis * 2); try { httpClient.requestExecutionBuilder().request(newGetRequest()).execute(); fail("Exception expected"); } catch (AmazonClientException e) { assertTrue(Thread.currentThread().isInterrupted()); assertThat(e.getCause(), instanceOf(InterruptedException.class)); } }
@Test(timeout = TEST_TIMEOUT) public void clientExecutionTimeoutEnabled_WithShorterRequestTimeout_ThrowsHttpRequestTimeoutException() throws IOException { httpClient = new AmazonHttpClient(new ClientConfiguration().withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT) .withRequestTimeout(SHORTER_REQUEST_TIMEOUT).withMaxErrorRetry(0)); try { httpClient.requestExecutionBuilder().request(newGetRequest()).execute(); fail("Exception expected"); } catch (AmazonClientException e) { assertThat(e.getCause(), instanceOf(HttpRequestTimeoutException.class)); // Completed tasks means the client execution was aborted by the timer assertNumberOfTasksTriggered(httpClient.getClientExecutionTimer(), 0); assertNumberOfTasksTriggered(httpClient.getHttpRequestTimer(), 1); } }
@Test(timeout = TEST_TIMEOUT) public void clientExecutionTimeoutEnabled_WithShorterRequestTimeoutAndRetry_ThrowsClientExecutionTimeoutException() throws IOException { final int clientExecutionTimeout = 1500; final int requestTimeout = 1000; final int backoffTime = 300; httpClient = new AmazonHttpClient(new ClientConfiguration().withClientExecutionTimeout(clientExecutionTimeout) .withRequestTimeout(requestTimeout) .withRetryPolicy(new RetryPolicy(PredefinedRetryPolicies.DEFAULT_RETRY_CONDITION, new FixedTimeBackoffStrategy(backoffTime), Integer.MAX_VALUE, false))); try { httpClient.requestExecutionBuilder().request(newGetRequest()).execute(); fail("Exception expected"); } catch (AmazonClientException e) { assertThat(e, instanceOf(ClientExecutionTimeoutException.class)); // Completed tasks means the client execution was aborted by the timer assertNumberOfTasksTriggered(httpClient.getClientExecutionTimer(), 1); assertNumberOfTasksTriggered(httpClient.getHttpRequestTimer(), 1); } }
/** * Verifies the request is actually retried for the expected times. */ private void testActualRetries(int expectedRetryAttempts) { testedClient = new AmazonHttpClient(clientConfiguration); injectMockHttpClient(testedClient, new ReturnServiceErrorHttpClient(500, "fake 500 service error")); // The ExecutionContext should collect the expected RequestCount ExecutionContext context = new ExecutionContext(true); try { testedClient.requestExecutionBuilder() .request(getSampleRequestWithRepeatableContent(originalRequest)) .errorResponseHandler(errorResponseHandler) .executionContext(context) .execute(); Assert.fail("AmazonServiceException is expected."); } catch (AmazonServiceException ase) {} RetryTestUtils.assertExpectedRetryCount(expectedRetryAttempts, context); }
GenericApiGatewayClient(ClientConfiguration clientConfiguration, String endpoint, Region region, AWSCredentialsProvider credentials, String apiKey, AmazonHttpClient httpClient) { super(clientConfiguration); setRegion(region); setEndpoint(endpoint); this.credentials = credentials; this.apiKey = apiKey; this.signer = new AWS4Signer(); this.signer.setServiceName(API_GATEWAY_SERVICE_NAME); this.signer.setRegionName(region.getName()); final JsonOperationMetadata metadata = new JsonOperationMetadata().withHasStreamingSuccessResponse(false).withPayloadJson(false); final Unmarshaller<GenericApiGatewayResponse, JsonUnmarshallerContext> responseUnmarshaller = in -> new GenericApiGatewayResponse(in.getHttpResponse()); this.responseHandler = SdkStructuredPlainJsonFactory.SDK_JSON_FACTORY.createResponseHandler(metadata, responseUnmarshaller); JsonErrorUnmarshaller defaultErrorUnmarshaller = new JsonErrorUnmarshaller(GenericApiGatewayException.class, null) { @Override public AmazonServiceException unmarshall(JsonNode jsonContent) throws Exception { return new GenericApiGatewayException(jsonContent.toString()); } }; this.errorResponseHandler = SdkStructuredPlainJsonFactory.SDK_JSON_FACTORY.createErrorResponseHandler( Collections.singletonList(defaultErrorUnmarshaller), null); if (httpClient != null) { super.client = httpClient; } }
@Before public void setUp() throws IOException { AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar")); mockClient = Mockito.mock(SdkHttpClient.class); HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK")); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream("test payload".getBytes())); resp.setEntity(entity); Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class)); ClientConfiguration clientConfig = new ClientConfiguration(); client = new GenericApiGatewayClientBuilder() .withClientConfiguration(clientConfig) .withCredentials(credentials) .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com") .withRegion(Region.getRegion(Regions.fromName("us-east-1"))) .withApiKey("12345") .withHttpClient(new AmazonHttpClient(clientConfig, mockClient, null)) .build(); }
@Test public void testLambdaInvokeSubsegmentContainsFunctionName() { // Setup test AWSLambda lambda = AWSLambdaClientBuilder.standard().withRequestHandlers(new TracingHandler()).withRegion(Regions.US_EAST_1).withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake"))).build(); AmazonHttpClient amazonHttpClient = new AmazonHttpClient(new ClientConfiguration()); ConnectionManagerAwareHttpClient apacheHttpClient = Mockito.mock(ConnectionManagerAwareHttpClient.class); HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK")); BasicHttpEntity responseBody = new BasicHttpEntity(); responseBody.setContent(new ByteArrayInputStream("null".getBytes(StandardCharsets.UTF_8))); // Lambda returns "null" on successful fn. with no return value httpResponse.setEntity(responseBody); try { Mockito.doReturn(httpResponse).when(apacheHttpClient).execute(Mockito.any(HttpUriRequest.class), Mockito.any(HttpContext.class)); } catch (IOException e) { } Whitebox.setInternalState(amazonHttpClient, "httpClient", apacheHttpClient); Whitebox.setInternalState(lambda, "client", amazonHttpClient); // Test logic Segment segment = AWSXRay.beginSegment("test"); InvokeRequest request = new InvokeRequest(); request.setFunctionName("testFunctionName"); InvokeResult r = lambda.invoke(request); System.out.println(r.getStatusCode()); System.out.println(r); Assert.assertEquals(1, segment.getSubsegments().size()); Assert.assertEquals("Invoke", segment.getSubsegments().get(0).getAws().get("operation")); System.out.println(segment.getSubsegments().get(0).getAws()); Assert.assertEquals("testFunctionName", segment.getSubsegments().get(0).getAws().get("function_name")); }
@SdkProtectedApi protected AmazonWebServiceClient(ClientConfiguration clientConfiguration, RequestMetricCollector requestMetricCollector, boolean disableStrictHostNameVerification) { this.clientConfiguration = clientConfiguration; requestHandler2s = new CopyOnWriteArrayList<RequestHandler2>(); client = new AmazonHttpClient(clientConfiguration, requestMetricCollector, disableStrictHostNameVerification, calculateCRC32FromCompressedData()); }
protected AmazonWebServiceClient(AwsSyncClientParams clientParams) { this.clientConfiguration = clientParams.getClientConfiguration(); requestHandler2s = clientParams.getRequestHandlers(); client = new AmazonHttpClient(clientConfiguration, clientParams.getRequestMetricCollector(), !useStrictHostNameVerification(), calculateCRC32FromCompressedData()); }
private AmazonHttpClient buildHttpClient(ClientHandlerParams handlerParams) { final AwsSyncClientParams clientParams = handlerParams.getClientParams(); return AmazonHttpClient.builder() .clientConfiguration(clientParams.getClientConfiguration()) .retryPolicy(clientParams.getRetryPolicy()) .requestMetricCollector(clientParams.getRequestMetricCollector()) .useBrowserCompatibleHostNameVerifier(handlerParams.isDisableStrictHostnameVerification()) .build(); }
/** * Execute the request with a dummy response handler and error response handler */ public static void execute(AmazonHttpClient httpClient, Request<?> request) { httpClient.requestExecutionBuilder() .request(request) .errorResponseHandler(new NullErrorResponseHandler()) .execute(new ErrorDuringUnmarshallingResponseHandler()); }
@Test(timeout = TEST_TIMEOUT) public void requestTimeoutDisabled_ConnectionClosedBySocketTimeout_NoThreadsCreated() { final int socketTimeout = 1000; httpClient = new AmazonHttpClient( new ClientConfiguration().withSocketTimeout(socketTimeout).withRequestTimeout(0).withMaxErrorRetry(0)); try { execute(httpClient, newGetRequest()); fail("Exception expected"); } catch (AmazonClientException e) { assertThat(e.getCause(), instanceOf(SocketTimeoutException.class)); assertRequestTimerExecutorNotCreated(httpClient.getHttpRequestTimer()); } }
@Test(timeout = TEST_TIMEOUT) public void requestTimeoutSetInRequestObject_WithLongerSocketTimeout_ThrowsRequestTimeoutException() { httpClient = new AmazonHttpClient( new ClientConfiguration().withSocketTimeout(LONGER_SOCKET_TIMEOUT).withMaxErrorRetry(0)); try { EmptyHttpRequest request = newGetRequest(); request.setOriginalRequest(new EmptyAmazonWebServiceRequest().withSdkRequestTimeout(REQUEST_TIMEOUT)); execute(httpClient, request); fail("Exception expected"); } catch (AmazonClientException e) { assertThat(e.getCause(), instanceOf(HttpRequestTimeoutException.class)); } }
@Test(timeout = TEST_TIMEOUT) public void requestTimeoutSetInRequestObject_WithShorterSocketTimeout_ThrowsRequestTimeoutException() { httpClient = new AmazonHttpClient( new ClientConfiguration().withSocketTimeout(SHORTER_SOCKET_TIMEOUT).withMaxErrorRetry(0)); try { EmptyHttpRequest request = newGetRequest(); request.setOriginalRequest(new EmptyAmazonWebServiceRequest().withSdkRequestTimeout(REQUEST_TIMEOUT)); execute(httpClient, request); fail("Exception expected"); } catch (AmazonClientException e) { assertThat(e.getCause(), instanceOf(SocketTimeoutException.class)); } }
@Test(timeout = TEST_TIMEOUT, expected = ClientExecutionTimeoutException.class) public void clientExecutionTimeoutEnabled_SlowResponseHandler_ThrowsClientExecutionTimeoutException() throws Exception { httpClient = new AmazonHttpClient( new ClientConfiguration().withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT)); requestBuilder().execute(new UnresponsiveResponseHandler()); }
@Test(timeout = TEST_TIMEOUT, expected = ClientExecutionTimeoutException.class) public void clientExecutionTimeoutEnabled_SlowAfterResponseRequestHandler_ThrowsClientExecutionTimeoutException() throws Exception { httpClient = new AmazonHttpClient( new ClientConfiguration().withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT)); List<RequestHandler2> requestHandlers = RequestHandlerTestUtils.buildRequestHandlerList( new SlowRequestHandler().withAfterResponseWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT)); requestBuilder().executionContext(withHandlers(requestHandlers)).execute(new DummyResponseHandler()); }
@Test(timeout = TEST_TIMEOUT, expected = ClientExecutionTimeoutException.class) public void clientExecutionTimeoutEnabled_SlowBeforeRequestRequestHandler_ThrowsClientExecutionTimeoutException() throws Exception { httpClient = new AmazonHttpClient( new ClientConfiguration().withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT)); List<RequestHandler2> requestHandlers = RequestHandlerTestUtils.buildRequestHandlerList( new SlowRequestHandler().withBeforeRequestWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT)); requestBuilder().executionContext(withHandlers(requestHandlers)).execute(new DummyResponseHandler()); }
@Test public void clientExecutionTimeoutEnabled_RequestCompletesWithinTimeout_TaskCanceledAndEntityBuffered() throws Exception { ClientConfiguration config = new ClientConfiguration().withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT) .withMaxErrorRetry(0); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); HttpResponseProxy responseProxy = createHttpResponseProxySpy(); doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { execute(httpClient, createMockGetRequest()); fail("Exception expected"); } catch (AmazonClientException e) { NullResponseHandler.assertIsUnmarshallingException(e); } assertResponseIsBuffered(responseProxy); ScheduledThreadPoolExecutor requestTimerExecutor = httpClient.getClientExecutionTimer().getExecutor(); assertTimerNeverTriggered(requestTimerExecutor); assertCanceledTasksRemoved(requestTimerExecutor); // Core threads should be spun up on demand. Since only one task was submitted only one // thread should exist assertEquals(1, requestTimerExecutor.getPoolSize()); assertCoreThreadsShutDownAfterBeingIdle(requestTimerExecutor); }
@Test(timeout = TEST_TIMEOUT, expected = ClientExecutionTimeoutException.class) public void clientExecutionTimeoutEnabled_SlowErrorResponseHandler_ThrowsClientExecutionTimeoutException() throws Exception { httpClient = new AmazonHttpClient( new ClientConfiguration().withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT)); httpClient.requestExecutionBuilder().request(newGetRequest()).errorResponseHandler(new UnresponsiveErrorResponseHandler()).execute(); }
@Test(timeout = TEST_TIMEOUT, expected = ClientExecutionTimeoutException.class) public void clientExecutionTimeoutEnabled_SlowAfterErrorRequestHandler_ThrowsClientExecutionTimeoutException() throws Exception { httpClient = new AmazonHttpClient( new ClientConfiguration().withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT)); List<RequestHandler2> requestHandlers = RequestHandlerTestUtils.buildRequestHandlerList( new SlowRequestHandler().withAfterErrorWaitInSeconds(SLOW_REQUEST_HANDLER_TIMEOUT)); httpClient.requestExecutionBuilder() .request(newGetRequest()) .errorResponseHandler(new NullErrorResponseHandler()) .executionContext(ExecutionContext.builder().withRequestHandler2s(requestHandlers).build()) .execute(); }
@Test(timeout = TEST_TIMEOUT) public void clientExecutionTimeoutDisabled_SocketTimeoutExceptionIsThrown_NoThreadsCreated() { httpClient = new AmazonHttpClient(new ClientConfiguration().withSocketTimeout(1 * 1000).withMaxErrorRetry(0)); try { httpClient.requestExecutionBuilder().request(newGetRequest()).execute(); fail("Exception expected"); } catch (AmazonClientException e) { assertThat(e.getCause(), instanceOf(SocketTimeoutException.class)); assertClientExecutionTimerExecutorNotCreated(httpClient.getClientExecutionTimer()); } }
@Test(timeout = TEST_TIMEOUT) public void clientExecutionTimeoutEnabled_WithLongerSocketTimeout_ThrowsClientExecutionTimeoutException() throws IOException { httpClient = new AmazonHttpClient(new ClientConfiguration().withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT) .withSocketTimeout(LONGER_SOCKET_TIMEOUT).withMaxErrorRetry(0)); try { httpClient.requestExecutionBuilder().request(newGetRequest()).execute(); fail("Exception expected"); } catch (AmazonClientException e) { assertThat(e, instanceOf(ClientExecutionTimeoutException.class)); assertNumberOfTasksTriggered(httpClient.getClientExecutionTimer(), 1); } }
@Test(timeout = TEST_TIMEOUT) public void clientExecutionTimeoutEnabled_WithShorterSocketTimeout_ThrowsSocketTimeoutException() throws IOException { httpClient = new AmazonHttpClient(new ClientConfiguration().withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT) .withSocketTimeout(SHORTER_SOCKET_TIMEOUT).withMaxErrorRetry(0)); try { httpClient.requestExecutionBuilder().request(newGetRequest()).execute(); fail("Exception expected"); } catch (AmazonClientException e) { assertThat(e.getCause(), instanceOf(SocketTimeoutException.class)); assertNumberOfTasksTriggered(httpClient.getClientExecutionTimer(), 0); } }
@Test(timeout = TEST_TIMEOUT) public void clientExecutionTimeoutEnabled_WithShorterClientExecutionTimeout_ThrowsClientExecutionTimeoutException() throws IOException { httpClient = new AmazonHttpClient(new ClientConfiguration().withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT) .withRequestTimeout(LONGER_REQUEST_TIMEOUT).withMaxErrorRetry(0)); try { httpClient.requestExecutionBuilder().request(newGetRequest()).execute(); fail("Exception expected"); } catch (AmazonClientException e) { assertThat(e, instanceOf(ClientExecutionTimeoutException.class)); assertNumberOfTasksTriggered(httpClient.getClientExecutionTimer(), 1); assertNumberOfTasksTriggered(httpClient.getHttpRequestTimer(), 0); } }
/** Reset the RetryPolicy and restart collecting context data */ @Before public void resetContextData() { retryCondition = new ContextDataCollectionRetryCondition(); backoffStrategy = new ContextDataCollectionBackoffStrategy(); // Reset the RetryPolicy clientConfiguration.setRetryPolicy( new RetryPolicy(retryCondition, backoffStrategy, EXPECTED_RETRY_COUNT, // max error retry false)); // ignore the maxErrorRetry in ClientConfiguration level testedClient = new AmazonHttpClient(clientConfiguration); }
public static void injectMockHttpClient(AmazonHttpClient amazonHttpClient, ConnectionManagerAwareHttpClient mockHttpClient) { try { Field f = AmazonHttpClient.class.getDeclaredField("httpClient"); f.setAccessible(true); f.set(amazonHttpClient, mockHttpClient); } catch (Exception e) { Assert.fail("Cannot inject the mock HttpClient object. " + e.getMessage()); } }