Java Code Examples for com.amazonaws.ClientConfiguration

The following are top voted examples for showing how to use com.amazonaws.ClientConfiguration. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: apigateway-generic-java-sdk   File: GenericApiGatewayClientTest.java   View source code 10 votes vote down vote up
@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));
}
 
Example 2
Project: spring-cloud-stream-binder-aws-kinesis   File: LocalKinesisResource.java   View source code 8 votes vote down vote up
@Override
protected void obtainResource() throws Exception {
	// See https://github.com/mhart/kinesalite#cbor-protocol-issues-with-the-java-sdk
	System.setProperty(SDKGlobalConfiguration.AWS_CBOR_DISABLE_SYSTEM_PROPERTY, "true");

	this.resource = AmazonKinesisAsyncClientBuilder.standard()
			.withClientConfiguration(
					new ClientConfiguration()
							.withMaxErrorRetry(0)
							.withConnectionTimeout(1000))
			.withEndpointConfiguration(
					new AwsClientBuilder.EndpointConfiguration("http://localhost:" + this.port,
							Regions.DEFAULT_REGION.getName()))
			.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("", "")))
			.build();

	// Check connection
	this.resource.listStreams();
}
 
Example 3
Project: Reer   File: S3Client.java   View source code 7 votes vote down vote up
private ClientConfiguration createConnectionProperties() {
    ClientConfiguration clientConfiguration = new ClientConfiguration();
    Optional<HttpProxySettings.HttpProxy> proxyOptional = s3ConnectionProperties.getProxy();
    if (proxyOptional.isPresent()) {
        HttpProxySettings.HttpProxy proxy = s3ConnectionProperties.getProxy().get();
        clientConfiguration.setProxyHost(proxy.host);
        clientConfiguration.setProxyPort(proxy.port);
        PasswordCredentials credentials = proxy.credentials;
        if (credentials != null) {
            clientConfiguration.setProxyUsername(credentials.getUsername());
            clientConfiguration.setProxyPassword(credentials.getPassword());
        }
    }
    Optional<Integer> maxErrorRetryCount = s3ConnectionProperties.getMaxErrorRetryCount();
    if (maxErrorRetryCount.isPresent()) {
        clientConfiguration.setMaxErrorRetry(maxErrorRetryCount.get());
    }
    return clientConfiguration;
}
 
Example 4
Project: elasticsearch_my   File: AWSSignersTests.java   View source code 6 votes vote down vote up
public void testSigners() {
    assertThat(signerTester(null), is(false));
    assertThat(signerTester("QueryStringSignerType"), is(true));
    assertThat(signerTester("AWS3SignerType"), is(true));
    assertThat(signerTester("AWS4SignerType"), is(true));
    assertThat(signerTester("NoOpSignerType"), is(true));
    assertThat(signerTester("UndefinedSigner"), is(false));

    assertThat(signerTester("S3SignerType"), is(false));
    assertThat(signerTester("AWSS3V4SignerType"), is(false));

    ClientConfiguration configuration = new ClientConfiguration();
    AwsSigner.configureSigner("AWS4SignerType", configuration);
    assertEquals(configuration.getSignerOverride(), "AWS4SignerType");
    AwsSigner.configureSigner("AWS3SignerType", configuration);
    assertEquals(configuration.getSignerOverride(), "AWS3SignerType");
}
 
Example 5
Project: ibm-cos-sdk-java   File: AbortedExceptionClientExecutionTimerIntegrationTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 6
Project: ibm-cos-sdk-java   File: AwsClientBuilderTest.java   View source code 6 votes vote down vote up
/**
 * 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());
}
 
Example 7
Project: ibm-cos-sdk-java   File: MockedClientTests.java   View source code 6 votes vote down vote up
@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);
}
 
Example 8
Project: aem-orchestrator   File: AwsConfig.java   View source code 6 votes vote down vote up
@Bean
public AmazonCloudWatch amazonCloudWatchClient(final AWSCredentialsProvider awsCredentialsProvider, 
    final ClientConfiguration awsClientConfig, final Region awsRegion) {
    return AmazonCloudWatchClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(awsClientConfig)
        .withRegion(awsRegion.getName())
        .build();
}
 
Example 9
Project: aem-orchestrator   File: AwsConfigTest.java   View source code 6 votes vote down vote up
@Test
public void testAwsClientConfig_NoProxy() {
    String clientProtocol = "http";
    int clientConnectionTimeout = 10;
    int clientMaxErrorRetry = 20;
    setField(awsConfig, "clientProtocol", clientProtocol);
    setField(awsConfig, "clientConnectionTimeout", clientConnectionTimeout);
    setField(awsConfig, "clientMaxErrorRetry", clientMaxErrorRetry);
    
    setField(awsConfig, "useProxy", false);
    ClientConfiguration clientConfiguration = awsConfig.awsClientConfig(null);
    
    assertThat(clientConfiguration.getProxyHost(), nullValue());
    assertThat(clientConfiguration.getProxyPort(), equalTo(-1));
    assertThat(clientConfiguration.getProtocol().toString(), equalTo(clientProtocol));
    assertThat(clientConfiguration.getConnectionTimeout(), equalTo(clientConnectionTimeout));
    assertThat(clientConfiguration.getMaxErrorRetry(), equalTo(clientMaxErrorRetry));
}
 
Example 10
Project: cyberduck   File: KMSEncryptionFeature.java   View source code 6 votes vote down vote up
public KMSEncryptionFeature(final S3Session session, final int timeout) {
    super(session);
    this.bookmark = session.getHost();
    configuration = new ClientConfiguration();
    configuration.setConnectionTimeout(timeout);
    configuration.setSocketTimeout(timeout);
    final UseragentProvider ua = new PreferencesUseragentProvider();
    configuration.setUserAgentPrefix(ua.get());
    configuration.setMaxErrorRetry(0);
    configuration.setMaxConnections(1);
    configuration.setUseGzip(PreferencesFactory.get().getBoolean("http.compression.enable"));
    final Proxy proxy = ProxyFactory.get().find(bookmark);
    switch(proxy.getType()) {
        case HTTP:
        case HTTPS:
            configuration.setProxyHost(proxy.getHostname());
            configuration.setProxyPort(proxy.getPort());
    }
    locationFeature = session.getFeature(Location.class);
}
 
Example 11
Project: cyberduck   File: AmazonIdentityConfiguration.java   View source code 6 votes vote down vote up
public AmazonIdentityConfiguration(final Host bookmark, final int timeout) {
    this.bookmark = bookmark;
    this.configuration = new ClientConfiguration();
    this.configuration.setConnectionTimeout(timeout);
    this.configuration.setSocketTimeout(timeout);
    final UseragentProvider ua = new PreferencesUseragentProvider();
    this.configuration.setUserAgentPrefix(ua.get());
    this.configuration.setMaxErrorRetry(0);
    this.configuration.setMaxConnections(1);
    this.configuration.setUseGzip(PreferencesFactory.get().getBoolean("http.compression.enable"));
    final Proxy proxy = ProxyFactory.get().find(bookmark);
    switch(proxy.getType()) {
        case HTTP:
        case HTTPS:
            this.configuration.setProxyHost(proxy.getHostname());
            this.configuration.setProxyPort(proxy.getPort());
    }
}
 
Example 12
Project: ibm-cos-sdk-java   File: AbortedExceptionClientExecutionTimerIntegrationTest.java   View source code 6 votes vote down vote up
@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;
        }
    })));
}
 
Example 13
Project: aws-codecommit-trigger-plugin   File: SQSFactoryImpl.java   View source code 6 votes vote down vote up
private AmazonSQSAsyncClientBuilder createStandardAsyncClientBuilder(SQSQueue queue, AWSCredentialsProvider credentials) {
    ClientConfiguration clientConfiguration = this.getClientConfiguration(queue);
    AmazonSQSAsyncClientBuilder builder = AmazonSQSAsyncClientBuilder.standard()
        .withClientConfiguration(clientConfiguration)
        .withCredentials(credentials)
        .withExecutorFactory(this.SQSExecutorFactory);

    if (queue != null) {
        Regions region = queue.getRegion();
        if (region != null) {
            builder.withRegion(region);
        }
    }

    return builder;
}
 
Example 14
Project: dremio-oss   File: S3FileSystem.java   View source code 6 votes vote down vote up
@Override
public AmazonS3Client load(S3ClientKey clientKey) throws Exception {
  logger.debug("Opening S3 client connection for {}", clientKey);
  ClientConfiguration clientConf = new ClientConfiguration();
  clientConf.setProtocol(clientKey.isSecure ? Protocol.HTTPS : Protocol.HTTP);
  // Proxy settings (if configured)
  clientConf.setProxyHost(clientKey.s3Config.get(Constants.PROXY_HOST));
  if (clientKey.s3Config.get(Constants.PROXY_PORT) != null) {
    clientConf.setProxyPort(Integer.valueOf(clientKey.s3Config.get(Constants.PROXY_PORT)));
  }
  clientConf.setProxyDomain(clientKey.s3Config.get(Constants.PROXY_DOMAIN));
  clientConf.setProxyUsername(clientKey.s3Config.get(Constants.PROXY_USERNAME));
  clientConf.setProxyPassword(clientKey.s3Config.get(Constants.PROXY_PASSWORD));
  clientConf.setProxyWorkstation(clientKey.s3Config.get(Constants.PROXY_WORKSTATION));

  if (clientKey.accessKey == null){
    return new AmazonS3Client(new AnonymousAWSCredentialsProvider(), clientConf);
  } else {
    return new AmazonS3Client(new BasicAWSCredentials(clientKey.accessKey, clientKey.secretKey), clientConf);
  }
}
 
Example 15
Project: ibm-cos-sdk-java   File: AmazonHttpClientSslHandshakeTimeoutIntegrationTest.java   View source code 6 votes vote down vote up
@Test(timeout = 60 * 1000)
public void testSslHandshakeTimeout() {
    AmazonHttpClient httpClient = new AmazonHttpClient(new ClientConfiguration()
            .withSocketTimeout(CLIENT_SOCKET_TO).withMaxErrorRetry(0));

    System.out.println("Sending request to localhost...");

    try {
        httpClient.requestExecutionBuilder()
                .request(new EmptyHttpRequest(server.getHttpsEndpoint(), HttpMethodName.GET))
                .execute();
        fail("Client-side socket read timeout is expected!");

    } catch (AmazonClientException e) {
        /**
         * Http client catches the SocketTimeoutException and throws a
         * ConnectTimeoutException.
         * {@link org.apache.http.impl.conn.DefaultHttpClientConnectionOperator#connect(ManagedHttpClientConnection, HttpHost, InetSocketAddress, int, SocketConfig, HttpContext)}
         */
        Assert.assertTrue(e.getCause() instanceof ConnectTimeoutException);

        ConnectTimeoutException cte = (ConnectTimeoutException) e.getCause();
        Assert.assertThat(cte.getMessage(), org.hamcrest.Matchers
                .containsString("Read timed out"));
    }
}
 
Example 16
Project: ibm-cos-sdk-java   File: ConnectionPoolMaxConnectionsIntegrationTest.java   View source code 6 votes vote down vote up
@Test(timeout = 60 * 1000)
public void leasing_a_new_connection_fails_with_connection_pool_timeout()
        throws Exception {

    String localhostEndpoint = "http://localhost:" + server.getPort();

    AmazonHttpClient httpClient = new AmazonHttpClient(
            new ClientConfiguration()
                    .withMaxConnections(1)
                    .withConnectionTimeout(100)
                    .withMaxErrorRetry(0));

    Request<?> request = new EmptyHttpRequest(localhostEndpoint, HttpMethodName.GET);

    // Block the first connection in the pool with this request.
    httpClient.requestExecutionBuilder().request(request).execute(new EmptyAWSResponseHandler());

    try {
        // A new connection will be leased here which would fail in
        // ConnectionPoolTimeoutException.
        httpClient.requestExecutionBuilder().request(request).execute();
        Assert.fail("Connection pool timeout exception is expected!");
    } catch (AmazonClientException e) {
        Assert.assertTrue(e.getCause() instanceof ConnectionPoolTimeoutException);
    }
}
 
Example 17
Project: ibm-cos-sdk-java   File: UnresponsiveServerTests.java   View source code 6 votes vote down vote up
@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));
    }
}
 
Example 18
Project: ibm-cos-sdk-java   File: MockedClientTests.java   View source code 6 votes vote down vote up
@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);
}
 
Example 19
Project: ibm-cos-sdk-java   File: MockedClientTests.java   View source code 6 votes vote down vote up
@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);
}
 
Example 20
Project: ibm-cos-sdk-java   File: MockedClientTests.java   View source code 6 votes vote down vote up
@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);
}
 
Example 21
Project: ibm-cos-sdk-java   File: UnresponsiveServerTests.java   View source code 6 votes vote down vote up
@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));
    }
}
 
Example 22
Project: elasticsearch_my   File: AwsSigner.java   View source code 5 votes vote down vote up
/**
 * Add a AWS API Signer.
 * @param signer Signer to use
 * @param configuration AWS Client configuration
 */
public static void configureSigner(String signer, ClientConfiguration configuration) {
    try {
        validateSignerType(signer);
    } catch (IllegalArgumentException e) {
        logger.warn("{}", e.getMessage());
    }

    configuration.setSignerOverride(signer);
}
 
Example 23
Project: ibm-cos-sdk-java   File: AmazonS3EncryptionClient.java   View source code 5 votes vote down vote up
/**
 * @deprecated use {@link AmazonS3EncryptionClientBuilder#withEncryptionMaterials(EncryptionMaterialsProvider)} and
 *                 {@link AmazonS3EncryptionClientBuilder#withCredentials(AWSCredentialsProvider)} and
 *                 {@link AmazonS3EncryptionClientBuilder#withCryptoConfiguration(CryptoConfiguration)} and
 *                 {@link AmazonS3EncryptionClientBuilder#withClientConfiguration(ClientConfiguration)} and
 *                 {@link AmazonS3EncryptionClientBuilder#withMetricsCollector(RequestMetricCollector)}
 */
@Deprecated
public AmazonS3EncryptionClient(
        AWSCredentialsProvider credentialsProvider,
        EncryptionMaterialsProvider kekMaterialsProvider,
        ClientConfiguration clientConfig,
        CryptoConfiguration cryptoConfig,
        RequestMetricCollector requestMetricCollector) {
    this(null, // KMS client
        credentialsProvider, kekMaterialsProvider, clientConfig,
        cryptoConfig, requestMetricCollector);
}
 
Example 24
Project: ibm-cos-sdk-java   File: SdkProxyRoutePlannerIntegrationTest.java   View source code 5 votes vote down vote up
private HttpClient createHttpClient(String nonProxyHosts) {
    HttpClientFactory<ConnectionManagerAwareHttpClient> httpClientFactory = new ApacheHttpClientFactory();
    ClientConfiguration config = new ClientConfiguration()
            .withProxyHost("localhost").withProxyPort(server.getPort())
            .withNonProxyHosts(nonProxyHosts);
    return httpClientFactory.create(HttpClientSettings.adapt(config));
}
 
Example 25
Project: elasticsearch_my   File: AwsS3ServiceImplTests.java   View source code 5 votes vote down vote up
protected void launchAWSConfigurationTest(Settings settings,
                                          Settings singleRepositorySettings,
                                          Protocol expectedProtocol,
                                          String expectedProxyHost,
                                          int expectedProxyPort,
                                          String expectedProxyUsername,
                                          String expectedProxyPassword,
                                          String expectedSigner,
                                          Integer expectedMaxRetries,
                                          boolean expectedUseThrottleRetries,
                                          int expectedReadTimeout) {
    Integer maxRetries = S3Repository.getValue(singleRepositorySettings, settings,
        S3Repository.Repository.MAX_RETRIES_SETTING, S3Repository.Repositories.MAX_RETRIES_SETTING);
    Boolean useThrottleRetries = S3Repository.getValue(singleRepositorySettings, settings,
        S3Repository.Repository.USE_THROTTLE_RETRIES_SETTING, S3Repository.Repositories.USE_THROTTLE_RETRIES_SETTING);

    ClientConfiguration configuration = InternalAwsS3Service.buildConfiguration(logger, singleRepositorySettings, settings,
        "default", maxRetries, null, useThrottleRetries);

    assertThat(configuration.getResponseMetadataCacheSize(), is(0));
    assertThat(configuration.getProtocol(), is(expectedProtocol));
    assertThat(configuration.getProxyHost(), is(expectedProxyHost));
    assertThat(configuration.getProxyPort(), is(expectedProxyPort));
    assertThat(configuration.getProxyUsername(), is(expectedProxyUsername));
    assertThat(configuration.getProxyPassword(), is(expectedProxyPassword));
    assertThat(configuration.getSignerOverride(), is(expectedSigner));
    assertThat(configuration.getMaxErrorRetry(), is(expectedMaxRetries));
    assertThat(configuration.useThrottledRetries(), is(expectedUseThrottleRetries));
    assertThat(configuration.getSocketTimeout(), is(expectedReadTimeout));
}
 
Example 26
Project: shabdiz   File: AmazonEC2HostProvider.java   View source code 5 votes vote down vote up
public AmazonEC2HostProvider(final AWSCredentials credentials, final ClientConfiguration configuration, String endpoint, Function<Instance, Host> instance_converter) {

        this.instance_converter = instance_converter;
        ec2_client = new AmazonEC2Client(credentials, configuration);
        ec2_client.setEndpoint(endpoint);
        next_host_index = new AtomicInteger();
    }
 
Example 27
Project: secrets-locker   File: KmsEncryptionService.java   View source code 5 votes vote down vote up
private MasterKeyProvider<?> masterKeyProvider() {

        final AWSCredentialsProvider credentials
                = new DefaultAWSCredentialsProviderChain();

        List<KmsMasterKey> masterKeys
                = new LinkedList<>();

        for (String region : this.regions) {
            KmsMasterKeyProvider provider
                    = new KmsMasterKeyProvider(
                            credentials,
                            Region.getRegion(
                                    Regions.fromName(
                                            region)),
                            new ClientConfiguration(),
                            this.keyId);



            masterKeys.add(
                    provider.getMasterKey(
                            this.keyId));
        }

        return MultipleProviderFactory
                .buildMultiProvider(
                        masterKeys);
    }
 
Example 28
Project: ibm-cos-sdk-java   File: DummySuccessfulResponseServerIntegrationTests.java   View source code 5 votes vote down vote up
@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());
}
 
Example 29
Project: aem-orchestrator   File: AwsConfig.java   View source code 5 votes vote down vote up
@Bean
public AmazonEC2 amazonEC2Client(final AWSCredentialsProvider awsCredentialsProvider,
    final ClientConfiguration awsClientConfig, final Region awsRegion) {
    return AmazonEC2ClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(awsClientConfig)
        .withRegion(awsRegion.getName())
        .build();
}
 
Example 30
Project: jenkins-aws-bucket-credentials   File: AwsKmsClientBuilderTest.java   View source code 5 votes vote down vote up
@Test
public void regionAndProxyShouldBeReflectedInClient(){
    AwsKmsClientBuilder clientBuilder = new AwsKmsClientBuilder();
    clientBuilder.region("eu-west-1").proxyHost("host").proxyPort(8080);
    AWSKMSClient amazonKmsClient = clientBuilder.build();
    {
        ClientConfiguration configuration = (ClientConfiguration) Whitebox.getInternalState(amazonKmsClient,"clientConfiguration");
        assertThat(configuration.getProxyHost()).isEqualTo("host");
        assertThat(configuration.getProxyPort()).isEqualTo(8080);
    }
}
 
Example 31
Project: S3Mock   File: S3MockRule.java   View source code 5 votes vote down vote up
/**
 * @return An {@link AmazonS3} client instance that is configured to call the started S3Mock
 *         server using HTTPS.
 */
public AmazonS3 createS3Client() {
  final BasicAWSCredentials credentials = new BasicAWSCredentials("foo", "bar");

  return AmazonS3ClientBuilder.standard()
      .withCredentials(new AWSStaticCredentialsProvider(credentials))
      .withClientConfiguration(
          configureClientToIgnoreInvalidSslCertificates(new ClientConfiguration()))
      .withEndpointConfiguration(
          new EndpointConfiguration("https://localhost:" + getPort(), "us-east-1"))
      .enablePathStyleAccess()
      .build();
}
 
Example 32
Project: aem-orchestrator   File: AwsConfig.java   View source code 5 votes vote down vote up
@Bean
public AmazonCloudFormation amazonCloudFormationClient(final AWSCredentialsProvider awsCredentialsProvider,
    final ClientConfiguration awsClientConfig, final Region awsRegion) {
    return AmazonCloudFormationClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(awsClientConfig)
        .withRegion(awsRegion.getName())
        .build();
}
 
Example 33
Project: aem-orchestrator   File: AwsConfig.java   View source code 5 votes vote down vote up
@Bean
public AmazonS3 amazonS3Client(final AWSCredentialsProvider awsCredentialsProvider, 
    final ClientConfiguration awsClientConfig, final Region awsRegion) {
    return AmazonS3ClientBuilder.standard()
        .withCredentials(awsCredentialsProvider)
        .withClientConfiguration(awsClientConfig)
        .withRegion(awsRegion.getName())
        .build();
}
 
Example 34
Project: jenkins-aws-bucket-credentials   File: AwsS3ClientBuilderTest.java   View source code 5 votes vote down vote up
@Test
public void regionSetButHostFilledWithSpaces() {
    AwsS3ClientBuilder clientBuilder = new AwsS3ClientBuilder();
    clientBuilder.region("eu-west-1").proxyHost("    ").proxyPort(8080);
    AmazonS3Client amazonS3Client = clientBuilder.build();
    assertThat(amazonS3Client.getRegion().toString()).isEqualTo(Region.getRegion(Regions.EU_WEST_1).toString());
    {
        ClientConfiguration configuration = (ClientConfiguration)Whitebox.getInternalState(amazonS3Client,"clientConfiguration");
        assertThat(configuration.getProxyHost()).isNull();
        assertThat(configuration.getProxyPort()).isEqualTo(-1);
    }
}
 
Example 35
Project: aem-stack-manager   File: AwsConfig.java   View source code 5 votes vote down vote up
@Bean
public ClientConfiguration awsClientConfig() {
    ClientConfiguration clientConfig = new ClientConfiguration();

    if (useProxy) {
        clientConfig.setProxyHost(clientProxyHost);
        clientConfig.setProxyPort(clientProxyPort);
    }

    clientConfig.setProtocol(Protocol.valueOf(clientProtocol.toUpperCase()));
    clientConfig.setConnectionTimeout(clientConnectionTimeout);
    clientConfig.setMaxErrorRetry(clientMaxErrorRetry);

    return clientConfig;
}
 
Example 36
Project: radosgw-admin4j   File: BaseTest.java   View source code 5 votes vote down vote up
protected static AmazonS3 createS3(String accessKey, String secretKey) {
  AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
  ClientConfiguration clientConfig = new ClientConfiguration();
  clientConfig.setProtocol(Protocol.HTTP);
  clientConfig.withSignerOverride("S3SignerType");
  //noinspection deprecation
  AmazonS3 s3 = new AmazonS3Client(credentials, clientConfig);
  s3.setEndpoint(s3Endpoint);
  return s3;
}
 
Example 37
Project: oscm   File: EC2Communication.java   View source code 5 votes vote down vote up
/**
 * Return amazon interface
 * 
 * @return AmazonEC2 client ec2
 */

AmazonEC2 getEC2() {
    if (ec2 == null) {
        String endpoint = ENDPOINT_PREFIX + ph.getRegion()
                + ENDPOINT_SUFFIX;
        String proxyHost = System.getProperty(HTTPS_PROXY_HOST);
        String proxyPort = System.getProperty(HTTPS_PROXY_PORT);
        String proxyUser = System.getProperty(HTTPS_PROXY_USER);
        String proxyPassword = System.getProperty(HTTPS_PROXY_PASSWORD);

        int proxyPortInt = 0;
        try {
            proxyPortInt = Integer.parseInt(proxyPort);
        } catch (NumberFormatException e) {
            // ignore
        }
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        if (!isNonProxySet(endpoint)) {
            if (proxyHost != null) {
                clientConfiguration.setProxyHost(proxyHost);
            }
            if (proxyPortInt > 0) {
                clientConfiguration.setProxyPort(proxyPortInt);
            }
            if (proxyUser != null && proxyUser.length() > 0) {
                clientConfiguration.setProxyUsername(proxyUser);
            }
            if (proxyPassword != null && proxyPassword.length() > 0) {
                clientConfiguration.setProxyPassword(proxyPassword);
            }
        }
        ec2 = getEC2(credentialsProvider, clientConfiguration);
        ec2.setEndpoint(endpoint);
    }
    return ec2;
}
 
Example 38
Project: oscm   File: EC2Communication.java   View source code 5 votes vote down vote up
/**
 * Allow mocking of EC2 client by having it in separate creation method
 * 
 * @param credentialsProvider
 * @param clientConfiguration
 */
AmazonEC2Client getEC2(AWSCredentialsProvider credentialsProvider,
        ClientConfiguration clientConfiguration) {
    if (ec2 == null) {
        ec2 = (ec2_stub != null) ? ec2_stub : new AmazonEC2Client(
                credentialsProvider, clientConfiguration);
    }
    return ec2;
}
 
Example 39
Project: circus-train   File: SnsConfiguration.java   View source code 5 votes vote down vote up
@Bean
AmazonSNSAsyncClient amazonSNS(ListenerConfig config, AWSCredentialsProvider awsCredentialsProvider) {
  AmazonSNSAsyncClient client = new AmazonSNSAsyncClient(awsCredentialsProvider,
      new ClientConfiguration().withRetryPolicy(PredefinedRetryPolicies.getDefaultRetryPolicy()),
      Executors.newSingleThreadScheduledExecutor());
  client.setRegion(Region.getRegion(Regions.fromName(config.getRegion())));
  return client;
}
 
Example 40
Project: ibm-cos-sdk-java   File: DummySuccessfulResponseServerIntegrationTests.java   View source code 5 votes vote down vote up
@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());
}