/** * 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); }
/** * The sync client is tested less thoroughly then the async client primarily because the async * client exercises most of the same code paths so a bug introduced in the sync client builder * should be exposed via tests written against the async builder. This test is mainly for * additional coverage of the sync builder in case there is a regression specific to sync * builders. */ @Test public void syncClientBuilder() { final List<RequestHandler2> requestHandlers = createRequestHandlerList( new ConcreteRequestHandler(), new ConcreteRequestHandler()); final AWSCredentialsProvider credentials = mock(AWSCredentialsProvider.class); final RequestMetricCollector metrics = mock(RequestMetricCollector.class); //@formatter:off AmazonConcreteClient client = new ConcreteSyncBuilder() .withRegion(Regions.EU_CENTRAL_1) .withClientConfiguration(new ClientConfiguration().withSocketTimeout(1234)) .withCredentials(credentials) .withMetricsCollector(metrics) .withRequestHandlers(requestHandlers.toArray(new RequestHandler2[requestHandlers.size()])) .build(); //@formatter:on assertEquals(URI.create("https://mockprefix.eu-central-1.amazonaws.com"), client.getEndpoint()); assertEquals(1234, client.getSyncParams().getClientConfiguration().getSocketTimeout()); assertEquals(requestHandlers, client.getSyncParams().getRequestHandlers()); assertEquals(credentials, client.getSyncParams().getCredentialsProvider()); assertEquals(metrics, client.getSyncParams().getRequestMetricCollector()); }
private AWSKMSClientBuilder cloneClientBuilder(final AWSKMSClientBuilder builder) { // We need to copy all arguments out of the builder in case it's mutated later on. // Unfortunately AWSKMSClientBuilder doesn't support .clone() so we'll have to do it by hand. if (builder.getEndpoint() != null) { // We won't be able to set the region later if a custom endpoint is set. throw new IllegalArgumentException("Setting endpoint configuration is not compatible with passing a " + "builder to the KmsMasterKeyProvider. Use withCustomClientFactory" + " instead."); } final AWSKMSClientBuilder newBuilder = AWSKMSClient.builder(); newBuilder.setClientConfiguration(builder.getClientConfiguration()); newBuilder.setCredentials(builder.getCredentials()); newBuilder.setEndpointConfiguration(builder.getEndpoint()); newBuilder.setMetricsCollector(builder.getMetricsCollector()); if (builder.getRequestHandlers() != null) { newBuilder.setRequestHandlers(builder.getRequestHandlers().toArray(new RequestHandler2[0])); } return newBuilder; }
@Test public void whenHandlerConfigured_handlerIsInvoked() throws Exception { RequestHandler2 handler = spy(new RequestHandler2() {}); KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withClientBuilder( AWSKMSClientBuilder.standard() .withRequestHandlers(handler) ) .withKeysForEncryption(KMSTestFixtures.TEST_KEY_IDS[0]) .build(); new AwsCrypto().encryptData(mkp, new byte[1]); verify(handler).beforeRequest(any()); }
@SdkProtectedApi protected AmazonWebServiceClient(ClientConfiguration clientConfiguration, RequestMetricCollector requestMetricCollector, boolean disableStrictHostNameVerification) { this.clientConfiguration = clientConfiguration; requestHandler2s = new CopyOnWriteArrayList<RequestHandler2>(); client = new AmazonHttpClient(clientConfiguration, requestMetricCollector, disableStrictHostNameVerification, calculateCRC32FromCompressedData()); }
/** * Runs the {@code beforeMarshalling} method of any * {@code RequestHandler2}s associated with this client. * * @param request the request passed in from the user * @return the (possibly different) request to marshal */ @SuppressWarnings("unchecked") protected final <T extends AmazonWebServiceRequest> T beforeMarshalling( T request) { T local = request; for (RequestHandler2 handler : requestHandler2s) { local = (T) handler.beforeMarshalling(local); } return local; }
/** * Notify request handlers that we are about to start execution. */ protected final <T extends AmazonWebServiceRequest> T beforeClientExecution(T request) { T local = request; for (RequestHandler2 handler : requestHandler2s) { local = (T) handler.beforeExecution(local); } return local; }
private List<RequestHandler2> getRequestHandlers() { List<RequestHandler2> requestHandler2s = executionContext.getRequestHandler2s(); if (requestHandler2s == null) { return Collections.emptyList(); } return requestHandler2s; }
private RequestExecutor(Request<?> request, RequestConfig requestConfig, HttpResponseHandler<? extends SdkBaseException> errorResponseHandler, HttpResponseHandler<Output> responseHandler, ExecutionContext executionContext, List<RequestHandler2> requestHandler2s) { this.request = request; this.requestConfig = requestConfig; this.errorResponseHandler = errorResponseHandler; this.responseHandler = responseHandler; this.executionContext = executionContext; this.requestHandler2s = requestHandler2s; this.awsRequestMetrics = executionContext.getAwsRequestMetrics(); }
private void runBeforeRequestHandlers() { AWSCredentials credentials = getCredentialsFromContext(); request.addHandlerContext(HandlerContextKey.AWS_CREDENTIALS, credentials); // Apply any additional service specific request handlers that need to be run for (RequestHandler2 requestHandler2 : requestHandler2s) { // If the request handler is a type of CredentialsRequestHandler, then set the credentials in the request handler. if (requestHandler2 instanceof CredentialsRequestHandler) { ((CredentialsRequestHandler) requestHandler2).setCredentials(credentials); } requestHandler2.beforeRequest(request); } }
private void afterError(Response<?> response, AmazonClientException e) throws InterruptedException { for (RequestHandler2 handler2 : requestHandler2s) { handler2.afterError(request, response, e); checkInterrupted(response); } }
/** * Run {@link RequestHandler2#beforeUnmarshalling(Request, HttpResponse)} callback * * @param origHttpResponse Original {@link HttpResponse} * @return {@link HttpResponse} object to pass to unmarshaller. May have been modified or * replaced by the request handlers */ private HttpResponse beforeUnmarshalling(HttpResponse origHttpResponse) { HttpResponse toReturn = origHttpResponse; for (RequestHandler2 requestHandler : requestHandler2s) { toReturn = requestHandler.beforeUnmarshalling(request, toReturn); } return toReturn; }
@Deprecated public ExecutionContext(List<RequestHandler2> requestHandler2s, boolean isMetricEnabled, AmazonWebServiceClient awsClient) { this.requestHandler2s = requestHandler2s; awsRequestMetrics = isMetricEnabled ? new AWSRequestMetricsFullSupport() : new AWSRequestMetrics(); this.awsClient = awsClient; this.signerProvider = new SignerProvider() { @Override public Signer getSigner(SignerProviderContext context) { return getSignerByURI(context.getUri()); } }; }
/** * Runs the {@code beforeMarshalling} method of any {@code RequestHandler2}s associated with * this client. * * @param request the request passed in from the user * @return The (possibly different) request to marshall */ @SuppressWarnings("unchecked") protected final <T extends AmazonWebServiceRequest> T beforeMarshalling(T request) { T local = request; for (RequestHandler2 handler : requestHandler2s) { local = (T) handler.beforeMarshalling(local); } return local; }
public static List<RequestHandler2> buildRequestHandlerList(RequestHandler2... requestHandlers) { List<RequestHandler2> requestHandlerList = new ArrayList<RequestHandler2>(); for(RequestHandler2 requestHandler : requestHandlers) { requestHandlerList.add(requestHandler); } return requestHandlerList; }
@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(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 public void requestHandlersExplicitlySet_UsesClonedListOfExplicitRequestHandlers() throws Exception { List<RequestHandler2> expectedHandlers = createRequestHandlerList( new ConcreteRequestHandler(), new ConcreteRequestHandler()); List<RequestHandler2> actualHandlers = builderWithRegion() .withRequestHandlers(expectedHandlers.toArray(new RequestHandler2[0])).build() .getAsyncParams().getRequestHandlers(); assertEquals(expectedHandlers, actualHandlers); // List should be copied or cloned assertThat(actualHandlers, not(sameInstance(expectedHandlers))); }
@Test public void requestHandlersExplicitlySetWithVarArgs_UsesExplicitRequestHandlers() throws Exception { RequestHandler2 handlerOne = new ConcreteRequestHandler(); RequestHandler2 handlerTwo = new ConcreteRequestHandler(); RequestHandler2 handlerThree = new ConcreteRequestHandler(); List<RequestHandler2> actualHandlers = builderWithRegion() .withRequestHandlers(handlerOne, handlerTwo, handlerThree).build().getAsyncParams() .getRequestHandlers(); assertEquals(createRequestHandlerList(handlerOne, handlerTwo, handlerThree), actualHandlers); }
private <T> void beforeRequest(Request<T> request) { if (requestHandler2s != null) { for (RequestHandler2 requestHandler2 : requestHandler2s) { requestHandler2.beforeRequest(request); } } }
@Test public void whenBuilderCloned_clientBuilderCustomizationIsRetained() throws Exception { RequestHandler2 handler = spy(new RequestHandler2() {}); KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withClientBuilder( AWSKMSClientBuilder.standard().withRequestHandlers(handler) ) .withKeysForEncryption(KMSTestFixtures.TEST_KEY_IDS[0]) .clone().build(); new AwsCrypto().encryptData(mkp, new byte[0]); verify(handler, atLeastOnce()).beforeRequest(any()); }
/** * @deprecated use {@link AwsClientBuilder#withRequestHandlers(RequestHandler2...)} */ @Deprecated public void removeRequestHandler(RequestHandler2 requestHandler2) { checkMutability(); requestHandler2s.remove(requestHandler2); }
private <T> void afterResponse(Response<T> response) throws InterruptedException { for (RequestHandler2 handler2 : requestHandler2s) { handler2.afterResponse(request, response); checkInterrupted(response); } }
public List<RequestHandler2> getRequestHandler2s() { return requestHandler2s; }
public void setRequestHandler2s(final List<RequestHandler2> requestHandler2s) { this.requestHandler2s = requestHandler2s; }
public Builder withRequestHandler2s(final List<RequestHandler2> requestHandler2s) { setRequestHandler2s(requestHandler2s); return this; }
/** * Gets the list of request handlers in use by the builder. */ public final List<RequestHandler2> getRequestHandlers() { return this.requestHandlers == null ? null : Collections.unmodifiableList(this.requestHandlers); }
/** * Request handlers are copied to a new list to avoid mutation, if no request handlers are * provided to the builder we supply an empty list. */ private List<RequestHandler2> resolveRequestHandlers() { return (requestHandlers == null) ? new ArrayList<RequestHandler2>() : new ArrayList<RequestHandler2>(requestHandlers); }
@Override public List<RequestHandler2> getRequestHandlers() { return this._requestHandlers; }
private ExecutionContext withHandlers(List<RequestHandler2> requestHandlers) { return ExecutionContext.builder().withRequestHandler2s(requestHandlers).build(); }
@Test public void noRequestHandlersExplicitlySet_UsesEmptyRequestHandlerList() throws Exception { List<RequestHandler2> requestHandlers = builderWithRegion().build().getAsyncParams() .getRequestHandlers(); assertThat(requestHandlers, empty()); }
private List<RequestHandler2> createRequestHandlerList(RequestHandler2... handlers) { List<RequestHandler2> requestHandlers = new ArrayList<RequestHandler2>(); Collections.addAll(requestHandlers, handlers); return requestHandlers; }
/** * The only information needed to create a client are security credentials * consisting of the AWS Access Key ID and Secret Access Key. All other * configuration, such as the service endpoints, are performed * automatically. Client parameters, such as proxies, can be specified in an * optional ClientConfiguration object when constructing a client. * * @see com.amazonaws.auth.BasicAWSCredentials * @see com.amazonaws.auth.PropertiesCredentials * @see com.amazonaws.ClientConfiguration */ private static void init() throws Exception { dynamoDBClient = new AmazonDynamoDBClient(new DefaultAWSCredentialsProviderChain()); // pass in the client for access to the cached metadata. RequestHandler2 requestHandler = new FaultInjectionRequestHandler(dynamoDBClient); dynamoDBClient.addRequestHandler(requestHandler); }
/** * @deprecated by {@link #addRequestHandler(RequestHandler2)}. * * Appends a request handler to the list of registered handlers that are run * as part of a request's lifecycle. * * @param requestHandler * The new handler to add to the current list of request * handlers. */ @Deprecated public void addRequestHandler(RequestHandler requestHandler) { checkMutability(); requestHandler2s.add(RequestHandler2.adapt(requestHandler)); }
/** * Appends a request handler to the list of registered handlers that are run * as part of a request's lifecycle. * * @param requestHandler2 * The new handler to add to the current list of request * handlers. * @deprecated use {@link AwsClientBuilder#withRequestHandlers(RequestHandler2...)} */ @Deprecated public void addRequestHandler(RequestHandler2 requestHandler2) { checkMutability(); requestHandler2s.add(requestHandler2); }
/** * Removes a request handler from the list of registered handlers that are run * as part of a request's lifecycle. * * @param requestHandler * The handler to remove from the current list of request * handlers. * @deprecated use {@link AwsClientBuilder#withRequestHandlers(RequestHandler2...)} */ @Deprecated public void removeRequestHandler(RequestHandler requestHandler) { checkMutability(); requestHandler2s.remove(RequestHandler2.adapt(requestHandler)); }
/** * Sets the request handlers to use in the client. * * @param handlers Request handlers to use for client. */ public final void setRequestHandlers(RequestHandler2... handlers) { this.requestHandlers = Arrays.asList(handlers); }
/** * Sets the request handlers to use in the client. * * @param handlers Request handlers to use for client. * @return This object for method chaining. */ public final Subclass withRequestHandlers(RequestHandler2... handlers) { setRequestHandlers(handlers); return getSubclass(); }