com.amazonaws.ClientConfiguration Java Examples

The following examples show how to use com.amazonaws.ClientConfiguration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GlueTestClientFactory.java    From aws-glue-data-catalog-client-for-apache-hive-metastore with Apache License 2.0 7 votes vote down vote up
private static ClientConfiguration createGatewayTimeoutRetryableConfiguration() {
  ClientConfiguration retryableConfig = new ClientConfiguration();
  RetryPolicy.RetryCondition retryCondition = new PredefinedRetryPolicies.SDKDefaultRetryCondition() {
    @Override
    public boolean shouldRetry(AmazonWebServiceRequest originalRequest, AmazonClientException exception,
                               int retriesAttempted) {
      if (super.shouldRetry(originalRequest, exception, retriesAttempted)) {
        return true;
      }
      if (exception != null && exception instanceof AmazonServiceException) {
        AmazonServiceException ase = (AmazonServiceException) exception;
        if (ase.getStatusCode() == SC_GATEWAY_TIMEOUT) {
          return true;
        }
      }
      return false;
    }
  };
  RetryPolicy retryPolicy = new RetryPolicy(retryCondition, PredefinedRetryPolicies.DEFAULT_BACKOFF_STRATEGY,
                                                   PredefinedRetryPolicies.DEFAULT_MAX_ERROR_RETRY, true);
  retryableConfig.setRetryPolicy(retryPolicy);
  return retryableConfig;
}
 
Example #2
Source File: S3URLConnection.java    From geowave with Apache License 2.0 6 votes vote down vote up
private ClientConfiguration buildClientConfig() {
  final String userAgent = System.getProperty(PROP_S3_HANDLER_USER_AGENT, null);
  final String protocol = System.getProperty(PROP_S3_HANDLER_PROTOCOL, "https");
  final String signerOverride = System.getProperty(PROP_S3_HANDLER_SIGNER_OVERRIDE, null);

  final ClientConfiguration clientConfig =
      new ClientConfiguration().withProtocol(
          "https".equalsIgnoreCase(protocol) ? Protocol.HTTPS : Protocol.HTTP);

  if (userAgent != null) {
    clientConfig.setUserAgent(userAgent);
  }
  if (signerOverride != null) {
    clientConfig.setSignerOverride(signerOverride);
  }

  return clientConfig;
}
 
Example #3
Source File: InvocationClientTest.java    From kafka-connect-lambda with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuilderReflexiveProperties() {
    ClientConfiguration clientConfiguration = new ClientConfiguration();
    AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();

    InvocationClient.Builder builder = new InvocationClient.Builder()
        .setFunctionArn("test-function-arn")
        .setRegion("us-test-region")
        .setInvocationMode(InvocationMode.ASYNC)
        .setFailureMode(InvocationFailure.DROP)
        .setInvocationTimeout(Duration.ofSeconds(123))
        .withClientConfiguration(clientConfiguration)
        .withCredentialsProvider(credentialsProvider);

    assertEquals("test-function-arn", builder.getFunctionArn());
    assertEquals("us-test-region", builder.getRegion());
    assertEquals(InvocationMode.ASYNC, builder.getInvocationMode());
    assertEquals(InvocationFailure.DROP, builder.getFailureMode());
    assertEquals(Duration.ofSeconds(123), builder.getInvocationTimeout());
    assertSame(clientConfiguration, builder.getClientConfiguration());
    assertSame(credentialsProvider, builder.getCredentialsProvider());
}
 
Example #4
Source File: TestAWSUtil.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetClientConfigurationNotUsing() {
  ProxyConfig proxyConfig = new ProxyConfig();
  proxyConfig.useProxy = false; // other values will be ignored because this is false
  proxyConfig.proxyHost = "host";
  proxyConfig.proxyPort = 1234;
  proxyConfig.proxyUser = () -> "user";
  proxyConfig.proxyPassword = () -> "password";
  proxyConfig.proxyDomain = "domain";
  proxyConfig.proxyWorkstation = "workstation";

  ClientConfiguration clientConfig = AWSUtil.getClientConfiguration(proxyConfig);
  Assert.assertNull(clientConfig.getProxyHost());
  Assert.assertEquals(-1, clientConfig.getProxyPort());
  Assert.assertNull(clientConfig.getProxyUsername());
  Assert.assertNull(clientConfig.getProxyPassword());
  Assert.assertNull(clientConfig.getProxyDomain());
  Assert.assertNull(clientConfig.getProxyWorkstation());
}
 
Example #5
Source File: KinesisConfig.java    From samza with Apache License 2.0 6 votes vote down vote up
/**
 * Get KCL config for a given system stream.
 * @param system name of the system
 * @param stream name of the stream
 * @param appName name of the application
 * @return Stream scoped KCL configs required to build
 *         {@link KinesisClientLibConfiguration}
 */
public KinesisClientLibConfiguration getKinesisClientLibConfig(String system, String stream, String appName) {
  ClientConfiguration clientConfig = getAWSClientConfig(system);
  String workerId = appName + "-" + UUID.randomUUID();
  InitialPositionInStream startPos = InitialPositionInStream.LATEST;
  AWSCredentialsProvider provider = credentialsProviderForStream(system, stream);
  KinesisClientLibConfiguration kinesisClientLibConfiguration =
      new KinesisClientLibConfiguration(appName, stream, provider, workerId)
          .withRegionName(getRegion(system, stream).getName())
          .withKinesisClientConfig(clientConfig)
          .withCloudWatchClientConfig(clientConfig)
          .withDynamoDBClientConfig(clientConfig)
          .withInitialPositionInStream(startPos)
          .withCallProcessRecordsEvenForEmptyRecordList(true); // For health monitoring metrics.
  // First, get system scoped configs for KCL and override with configs set at stream scope.
  setKinesisClientLibConfigs(
      subset(String.format(CONFIG_SYSTEM_KINESIS_CLIENT_LIB_CONFIG, system)), kinesisClientLibConfiguration);
  setKinesisClientLibConfigs(subset(String.format(CONFIG_STREAM_KINESIS_CLIENT_LIB_CONFIG, system, stream)),
      kinesisClientLibConfiguration);
  return kinesisClientLibConfiguration;
}
 
Example #6
Source File: AmazonAwsClientFactory.java    From primecloud-controller with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public AmazonElasticLoadBalancing createElbClient(String awsAccessId, String awsSecretKey) {
    AWSCredentials credentials = new BasicAWSCredentials(awsAccessId, awsSecretKey);
    ClientConfiguration configuration = createConfiguration();

    AmazonElasticLoadBalancing client = new AmazonElasticLoadBalancingClient(credentials, configuration);

    if (host != null) {
        client.setEndpoint(AmazonElasticLoadBalancing.ENDPOINT_PREFIX + "." + host);
    }

    client = new ExceptionHandleAwsClientWrapper().wrap(client);

    return client;
}
 
Example #7
Source File: AwsMetricsPublisher.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
private AmazonSNSAsync initSnsClient() {
  logger.log(Level.INFO, "Initializing SNS Client.");
  return AmazonSNSAsyncClientBuilder.standard()
      .withRegion(region)
      .withClientConfiguration(
          new ClientConfiguration().withMaxConnections(snsClientMaxConnections))
      .withCredentials(
          new AWSStaticCredentialsProvider(
              new AWSCredentials() {
                @Override
                public String getAWSAccessKeyId() {
                  return awsAccessKeyId;
                }

                @Override
                public String getAWSSecretKey() {
                  return awsSecretKey;
                }
              }))
      .build();
}
 
Example #8
Source File: AwsClientTracing.java    From zipkin-aws with Apache License 2.0 6 votes vote down vote up
public <Builder extends AwsClientBuilder, Client> Client build(
    AwsClientBuilder<Builder, Client> builder
) {
  if (builder == null) throw new NullPointerException("builder == null");
  if (builder instanceof AwsAsyncClientBuilder) {
    ExecutorFactory executorFactory = ((AwsAsyncClientBuilder) builder).getExecutorFactory();
    if (executorFactory == null) {
      ClientConfiguration clientConfiguration = builder.getClientConfiguration();
      if (clientConfiguration == null) {
        clientConfiguration = defaultClientConfigurationFactory.getConfig();
      }
      ((AwsAsyncClientBuilder) builder).setExecutorFactory(
          new TracingExecutorFactory(currentTraceContext, clientConfiguration)
      );
    } else {
      ((AwsAsyncClientBuilder) builder).setExecutorFactory(
          new TracingExecutorFactoryWrapper(currentTraceContext, executorFactory)
      );
    }
  }
  builder.withRequestHandlers(new TracingRequestHandler(httpTracing));
  return builder.build();
}
 
Example #9
Source File: FileClient.java    From file-service with Apache License 2.0 6 votes vote down vote up
private void initAmazonS3() {
    BasicAWSCredentials credentials = new BasicAWSCredentials(
            fileClientConfig.getAccessKey(), fileClientConfig.getSecretKey());
    ClientConfiguration clientConfig = new ClientConfiguration();
    clientConfig.setSignerOverride("S3SignerType");
    String region = fileClientConfig.getRegion() == null ? FileClientConfiguration.US_EAST_1 : fileClientConfig.getRegion();
    this.amazonS3 = AmazonS3ClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(credentials))
            .withClientConfiguration(clientConfig)
            .withEndpointConfiguration(
                    new AwsClientBuilder.EndpointConfiguration(
                            fileClientConfig.getEndpoint(),
                            region))
            .withPathStyleAccessEnabled(fileClientConfig.getWithPath())
            .build();

}
 
Example #10
Source File: ServiceSpringModuleConfig.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Gets a JMS connection factory.
 *
 * @return the JMS connection factory.
 */
@Bean
public ConnectionFactory jmsConnectionFactory()
{
    AwsParamsDto awsParamsDto = awsHelper.getAwsParamsDto();

    ClientConfiguration clientConfiguration = new ClientConfiguration();

    // Only set the proxy hostname and/or port if they're configured.
    if (StringUtils.isNotBlank(awsParamsDto.getHttpProxyHost()))
    {
        clientConfiguration.setProxyHost(awsParamsDto.getHttpProxyHost());
    }
    if (awsParamsDto.getHttpProxyPort() != null)
    {
        clientConfiguration.setProxyPort(awsParamsDto.getHttpProxyPort());
    }

    return SQSConnectionFactory.builder().withClientConfiguration(clientConfiguration).build();
}
 
Example #11
Source File: AWSOptionParser.java    From dlp-dataflow-deidentification with Apache License 2.0 6 votes vote down vote up
public static void formatOptions(S3ImportOptions options) {

    ClientConfiguration configuration =
        new ClientConfiguration()
            .withMaxConnections(options.getMaxConnections())
            .withConnectionTimeout(options.getConnectionTimeout())
            .withSocketTimeout(options.getSocketTimeout());

    options.setClientConfiguration(configuration);

    if (options.getS3BucketUrl().toLowerCase().startsWith(AWS_S3_PREFIX)) {
      setAwsCredentials(options);
    }

    if (options.getAwsRegion() == null) {
      setAwsDefaultRegion(options);
    }
  }
 
Example #12
Source File: AWSUtil.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an Amazon Kinesis Client.
 * @param configProps configuration properties containing the access key, secret key, and region
 * @param awsClientConfig preconfigured AWS SDK client configuration
 * @return a new Amazon Kinesis Client
 */
public static AmazonKinesis createKinesisClient(Properties configProps, ClientConfiguration awsClientConfig) {
	// set a Flink-specific user agent
	awsClientConfig.setUserAgentPrefix(String.format(USER_AGENT_FORMAT,
			EnvironmentInformation.getVersion(),
			EnvironmentInformation.getRevisionInformation().commitId));

	// utilize automatic refreshment of credentials by directly passing the AWSCredentialsProvider
	AmazonKinesisClientBuilder builder = AmazonKinesisClientBuilder.standard()
			.withCredentials(AWSUtil.getCredentialsProvider(configProps))
			.withClientConfiguration(awsClientConfig);

	if (configProps.containsKey(AWSConfigConstants.AWS_ENDPOINT)) {
		// Set signingRegion as null, to facilitate mocking Kinesis for local tests
		builder.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
												configProps.getProperty(AWSConfigConstants.AWS_ENDPOINT),
												null));
	} else {
		builder.withRegion(Regions.fromName(configProps.getProperty(AWSConfigConstants.AWS_REGION)));
	}
	return builder.build();
}
 
Example #13
Source File: ClientSideCEncryptionStrategy.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Create an encryption client.
 *
 * @param credentialsProvider AWS credentials provider.
 * @param clientConfiguration Client configuration
 * @param kmsRegion not used by this encryption strategy
 * @param keyIdOrMaterial client master key, always base64 encoded
 * @return AWS S3 client
 */
@Override
public AmazonS3Client createEncryptionClient(AWSCredentialsProvider credentialsProvider, ClientConfiguration clientConfiguration, String kmsRegion, String keyIdOrMaterial) {
    ValidationResult keyValidationResult = validateKey(keyIdOrMaterial);
    if (!keyValidationResult.isValid()) {
        throw new IllegalArgumentException("Invalid client key; " + keyValidationResult.getExplanation());
    }

    byte[] keyMaterial = Base64.decodeBase64(keyIdOrMaterial);
    SecretKeySpec symmetricKey = new SecretKeySpec(keyMaterial, "AES");
    StaticEncryptionMaterialsProvider encryptionMaterialsProvider = new StaticEncryptionMaterialsProvider(new EncryptionMaterials(symmetricKey));

    AmazonS3EncryptionClient client = new AmazonS3EncryptionClient(credentialsProvider, encryptionMaterialsProvider);

    return client;
}
 
Example #14
Source File: AwsClientFactory.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a client for accessing Amazon EC2 service.
 *
 * @param awsParamsDto the AWS related parameters DTO that includes optional AWS credentials and proxy information
 *
 * @return the Amazon EC2 client
 */
@Cacheable(DaoSpringModuleConfig.HERD_CACHE_NAME)
public AmazonEC2 getEc2Client(AwsParamsDto awsParamsDto)
{
    // Get client configuration.
    ClientConfiguration clientConfiguration = awsHelper.getClientConfiguration(awsParamsDto);

    // If specified, use the AWS credentials passed in.
    if (StringUtils.isNotBlank(awsParamsDto.getAwsAccessKeyId()))
    {
        return AmazonEC2ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(
            new BasicSessionCredentials(awsParamsDto.getAwsAccessKeyId(), awsParamsDto.getAwsSecretKey(), awsParamsDto.getSessionToken())))
            .withClientConfiguration(clientConfiguration).withRegion(awsParamsDto.getAwsRegionName()).build();
    }
    // Otherwise, use the default AWS credentials provider chain.
    else
    {
        return AmazonEC2ClientBuilder.standard().withClientConfiguration(clientConfiguration).withRegion(awsParamsDto.getAwsRegionName()).build();
    }
}
 
Example #15
Source File: DynamoDBReplicationEmitterTestsBase.java    From dynamodb-cross-region-library with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void modifyTest() throws Exception {
    // Set up the buffer and do sanity checks
    buffer.clear();
    buffer.consumeRecord(ITEM1_MODIFY, ITEM1_MODIFY.getDynamodb().getSizeBytes().intValue(), ITEM1_MODIFY.getDynamodb().getSequenceNumber());
    assertEquals(ITEM1_MODIFY.getDynamodb().getSequenceNumber(), buffer.getFirstSequenceNumber());
    assertEquals(ITEM1_MODIFY.getDynamodb().getSequenceNumber(), buffer.getLastSequenceNumber());
    List<Record> buffered = buffer.getRecords();
    assertEquals(1, buffered.size());
    assertTrue(buffered.contains(ITEM1_MODIFY));

    // Emit record
    resetAll(DYNAMODB);
    DYNAMODB.putItemAsync(EasyMock.anyObject(PutItemRequest.class), anyObject(AsyncHandler.class));
    expectLastCall().andAnswer(SUCCESS_ANSWER);
    expectNew(AmazonDynamoDBAsyncClient.class, new Class<?>[] {AWSCredentialsProvider.class, ClientConfiguration.class, ExecutorService.class}, anyObject(AWSCredentialsProvider.class), anyObject(ClientConfiguration.class), anyObject(ExecutorService.class)).andReturn(DYNAMODB);
    DYNAMODB.setEndpoint(EasyMock.anyString());
    EasyMock.expectLastCall().anyTimes();
    replayAll(DYNAMODB);
    IEmitter<Record> instance = createEmitterInstance();
    assertTrue(instance.emit(new UnmodifiableBuffer<Record>(buffer)).isEmpty());
    verifyAll();
}
 
Example #16
Source File: S3ConnectionBaseConfig.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private void createConnection(
    Stage.Context context,
    String configPrefix,
    ProxyConfig proxyConfig,
    List<Stage.ConfigIssue> issues,
    int maxErrorRetries
) throws StageException {
  AWSCredentialsProvider credentials = AWSUtil.getCredentialsProvider(awsConfig);
  ClientConfiguration clientConfig = AWSUtil.getClientConfiguration(proxyConfig);

  if (maxErrorRetries >= 0) {
    clientConfig.setMaxErrorRetry(maxErrorRetries);
  }

  AmazonS3ClientBuilder builder = AmazonS3ClientBuilder
      .standard()
      .withCredentials(credentials)
      .withClientConfiguration(clientConfig)
      .withChunkedEncodingDisabled(awsConfig.disableChunkedEncoding)
      .withPathStyleAccessEnabled(usePathAddressModel);

  if (region == AwsRegion.OTHER) {
    if (endpoint == null || endpoint.isEmpty()) {
      issues.add(context.createConfigIssue(Groups.S3.name(), configPrefix + "endpoint", Errors.S3_SPOOLDIR_10));
      return;
    }
    builder.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, null));
  } else {
    builder.withRegion(region.getId());
  }
  s3Client = builder.build();
}
 
Example #17
Source File: AwsTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
private static AmazonDynamoDB buildClient() {
  final EndpointConfiguration endpointConfiguration = new EndpointConfiguration("http://localhost:8000", "us-west-2");
  final BasicAWSCredentials awsCreds = new BasicAWSCredentials("access_key_id", "secret_key_id");
  return AmazonDynamoDBClientBuilder
    .standard()
    .withEndpointConfiguration(endpointConfiguration)
    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
    .withClientConfiguration(new ClientConfiguration().withConnectionTimeout(1))
    .build();
}
 
Example #18
Source File: MockAWSProcessor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Create client using AWSCredentials
 *
 * @deprecated use {@link #createClient(ProcessContext, AWSCredentialsProvider, ClientConfiguration)} instead
 */
@Override
protected AmazonS3Client createClient(final ProcessContext context, final AWSCredentials credentials, final ClientConfiguration config) {
    getLogger().info("Creating client with awd credentials");

    final AmazonS3Client s3 = new AmazonS3Client(credentials, config);

    return s3;
}
 
Example #19
Source File: S3ClientFactory.java    From front50 with Apache License 2.0 5 votes vote down vote up
public static AmazonS3 create(
    AWSCredentialsProvider awsCredentialsProvider, S3Properties s3Properties) {
  ClientConfiguration clientConfiguration = new ClientConfiguration();
  if (s3Properties.getProxyProtocol() != null) {
    if (s3Properties.getProxyProtocol().equalsIgnoreCase("HTTPS")) {
      clientConfiguration.setProtocol(Protocol.HTTPS);
    } else {
      clientConfiguration.setProtocol(Protocol.HTTP);
    }
    Optional.ofNullable(s3Properties.getProxyHost()).ifPresent(clientConfiguration::setProxyHost);
    Optional.ofNullable(s3Properties.getProxyPort())
        .map(Integer::parseInt)
        .ifPresent(clientConfiguration::setProxyPort);
  }

  AmazonS3Client client = new AmazonS3Client(awsCredentialsProvider, clientConfiguration);

  if (!StringUtils.isEmpty(s3Properties.getEndpoint())) {
    client.setEndpoint(s3Properties.getEndpoint());

    if (!StringUtils.isEmpty(s3Properties.getRegionOverride())) {
      client.setSignerRegionOverride(s3Properties.getRegionOverride());
    }

    client.setS3ClientOptions(
        S3ClientOptions.builder().setPathStyleAccess(s3Properties.getPathStyleAccess()).build());
  } else {
    Optional.ofNullable(s3Properties.getRegion())
        .map(Regions::fromName)
        .map(Region::getRegion)
        .ifPresent(client::setRegion);
  }

  return client;
}
 
Example #20
Source File: GenericApiGatewayClientBuilderTest.java    From apigateway-generic-java-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuild_happy() throws Exception {
    AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider(new BasicAWSCredentials("foo", "bar"));

    GenericApiGatewayClient client = new GenericApiGatewayClientBuilder()
            .withClientConfiguration(new ClientConfiguration())
            .withCredentials(credentials)
            .withEndpoint("https://foobar.execute-api.us-east-1.amazonaws.com")
            .withRegion(Region.getRegion(Regions.fromName("us-east-1")))
            .withApiKey("12345")
            .build();

    Assert.assertEquals("Wrong service name","execute-api", client.getServiceNameIntern());
}
 
Example #21
Source File: AwsHelperTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetClientConfiguration() throws Exception
{
    // Try to get AWS parameters using all possible permutations of HTTP proxy settings.
    for (String testHttpProxyHost : Arrays.asList(STRING_VALUE, BLANK_TEXT, null))
    {
        for (Integer testHttpProxyPort : Arrays.asList(INTEGER_VALUE, null))
        {
            // Create AWS parameters DTO.
            AwsParamsDto testAwsParamsDto = awsHelper.getAwsParamsDto();
            testAwsParamsDto.setHttpProxyHost(testHttpProxyHost);
            testAwsParamsDto.setHttpProxyPort(testHttpProxyPort);

            // Get client configuration.
            ClientConfiguration resultClientConfiguration = awsHelper.getClientConfiguration(testAwsParamsDto);

            // Validate the results.
            assertNotNull(resultClientConfiguration);
            // The proxy settings are set only when both host and port are specified in the AWS parameters DTO.
            if (STRING_VALUE.equals(testHttpProxyHost) && INTEGER_VALUE.equals(testHttpProxyPort))
            {
                assertEquals(testHttpProxyHost, resultClientConfiguration.getProxyHost());
                assertEquals(testHttpProxyPort, Integer.valueOf(resultClientConfiguration.getProxyPort()));
            }
            else
            {
                assertNull(resultClientConfiguration.getProxyHost());
                assertEquals(-1, resultClientConfiguration.getProxyPort());
            }
        }
    }
}
 
Example #22
Source File: AbstractSQSProcessor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Create client using AWSCredentials
 *
 * @deprecated use {@link #createClient(ProcessContext, AWSCredentialsProvider, ClientConfiguration)} instead
 */
@Override
protected AmazonSQSClient createClient(final ProcessContext context, final AWSCredentials credentials, final ClientConfiguration config) {
    getLogger().info("Creating client using aws credentials ");

    return new AmazonSQSClient(credentials, config);
}
 
Example #23
Source File: TestAWSUtil.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetClientConfigurationNotSet() {
  ProxyConfig proxyConfig = new ProxyConfig();
  proxyConfig.useProxy = true;

  ClientConfiguration clientConfig = AWSUtil.getClientConfiguration(proxyConfig);
  Assert.assertNull(clientConfig.getProxyHost());
  Assert.assertEquals(-1, clientConfig.getProxyPort());
  Assert.assertNull(clientConfig.getProxyUsername());
  Assert.assertNull(clientConfig.getProxyPassword());
  Assert.assertNull(clientConfig.getProxyDomain());
  Assert.assertNull(clientConfig.getProxyWorkstation());
}
 
Example #24
Source File: AbstractS3Processor.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void initializeSignerOverride(final ProcessContext context, final ClientConfiguration config) {
    String signer = context.getProperty(SIGNER_OVERRIDE).getValue();

    if (signer != null && !signer.equals(SIGNER_OVERRIDE.getDefaultValue())) {
        config.setSignerOverride(signer);
    }
}
 
Example #25
Source File: S3DaoTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAmazonS3AssertProxyIsNotSetWhenProxyPortIsNull()
{
    S3Operations originalS3Operations = (S3Operations) ReflectionTestUtils.getField(s3Dao, "s3Operations");
    S3Operations mockS3Operations = mock(S3Operations.class);
    ReflectionTestUtils.setField(s3Dao, "s3Operations", mockS3Operations);

    try
    {
        String s3BucketName = "s3BucketName";
        String s3KeyPrefix = "s3KeyPrefix";
        String httpProxyHost = "httpProxyHost";
        Integer httpProxyPort = null;

        S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto = new S3FileTransferRequestParamsDto();
        s3FileTransferRequestParamsDto.setS3BucketName(s3BucketName);
        s3FileTransferRequestParamsDto.setS3KeyPrefix(s3KeyPrefix);
        s3FileTransferRequestParamsDto.setHttpProxyHost(httpProxyHost);
        s3FileTransferRequestParamsDto.setHttpProxyPort(httpProxyPort);

        when(mockS3Operations.putObject(any(), any())).then(new Answer<PutObjectResult>()
        {
            @Override
            public PutObjectResult answer(InvocationOnMock invocation) throws Throwable
            {
                AmazonS3Client amazonS3Client = invocation.getArgument(1);
                ClientConfiguration clientConfiguration = (ClientConfiguration) ReflectionTestUtils.getField(amazonS3Client, "clientConfiguration");
                assertNull(clientConfiguration.getProxyHost());
                return new PutObjectResult();
            }
        });

        s3Dao.createDirectory(s3FileTransferRequestParamsDto);
    }
    finally
    {
        ReflectionTestUtils.setField(s3Dao, "s3Operations", originalS3Operations);
    }
}
 
Example #26
Source File: AWSDeviceFarm.java    From aws-device-farm-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Private AWSDeviceFarm constructor. Uses the roleArn to generate STS creds if the roleArn isn't null; otherwise
 * just uses the AWSCredentials creds.
 *
 * @param creds   AWSCredentials creds to use for authentication.
 * @param roleArn Role ARN to use for authentication.
 */
private AWSDeviceFarm(AWSCredentials creds, String roleArn) {
    if (roleArn != null) {
        STSAssumeRoleSessionCredentialsProvider sts = new STSAssumeRoleSessionCredentialsProvider
                .Builder(roleArn, RandomStringUtils.randomAlphanumeric(8))
                .withRoleSessionDurationSeconds(MAX_ROLE_SESSION_TIMEOUT)
                .build();
        creds = sts.getCredentials();
    }

    ClientConfiguration clientConfiguration = new ClientConfiguration().withUserAgent("AWS Device Farm - Jenkins v1.0");
    api = new AWSDeviceFarmClient(creds, clientConfiguration);
    api.setServiceNameIntern("devicefarm");
}
 
Example #27
Source File: ProxyTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetNonProxyHosts() throws Exception {
	EnvVars vars = new EnvVars();
	vars.put(ProxyConfiguration.NO_PROXY, "127.0.0.1,localhost");
	vars.put(ProxyConfiguration.HTTPS_PROXY, "http://127.0.0.1:8888/");
	ClientConfiguration config = new ClientConfiguration();
	config.setProtocol(Protocol.HTTPS);
	ProxyConfiguration.configure(vars, config);

	Assert.assertEquals("127.0.0.1|localhost", config.getNonProxyHosts());
}
 
Example #28
Source File: AbstractAWSLambdaProcessor.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Create client using AWSCredentials
 *
 * @deprecated use {@link #createClient(ProcessContext, AWSCredentialsProvider, ClientConfiguration)} instead
 */
@Override
protected AWSLambdaClient createClient(final ProcessContext context, final AWSCredentials credentials, final ClientConfiguration config) {
    getLogger().info("Creating client using aws credentials");

    return new AWSLambdaClient(credentials, config);
}
 
Example #29
Source File: GettingStarted.java    From getting-started with MIT License 5 votes vote down vote up
private static RequestExecutionBuilder buildRequest(final Request request) {
  try {
    return new AmazonHttpClient(new ClientConfiguration()).requestExecutionBuilder()
        .executionContext(new ExecutionContext(true)).request(request)
        .errorResponseHandler(new ErrorResponseHandler(false));
  } catch (AmazonServiceException exception) {
    System.out.println("Unexpected status code in response: " + exception.getStatusCode());
    System.out.println("Content: " + exception.getRawResponseContent());
    throw new RuntimeException("Failed request. Aborting.");
  }
}
 
Example #30
Source File: EC2Communication.java    From development with Apache License 2.0 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;
}