Java Code Examples for com.amazonaws.auth.BasicAWSCredentials

The following examples show how to use com.amazonaws.auth.BasicAWSCredentials. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * {@inheritDoc}
 */
@Override
public AmazonEC2 createEc2Client(String awsAccessId, String awsSecretKey) {
    AWSCredentials credentials = new BasicAWSCredentials(awsAccessId, awsSecretKey);
    ClientConfiguration configuration = createConfiguration();

    AmazonEC2 client = new AmazonEC2Client(credentials, configuration);

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

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

    return client;
}
 
Example 2
Source Project: ecs-sync   Source File: AwsS3Test.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    Properties syncProperties = TestConfig.getProperties();
    endpoint = syncProperties.getProperty(TestConfig.PROP_S3_ENDPOINT);
    accessKey = syncProperties.getProperty(TestConfig.PROP_S3_ACCESS_KEY_ID);
    secretKey = syncProperties.getProperty(TestConfig.PROP_S3_SECRET_KEY);
    region = syncProperties.getProperty(TestConfig.PROP_S3_REGION);
    String proxyUri = syncProperties.getProperty(TestConfig.PROP_HTTP_PROXY_URI);
    Assume.assumeNotNull(endpoint, accessKey, secretKey);
    endpointUri = new URI(endpoint);

    ClientConfiguration config = new ClientConfiguration().withSignerOverride("S3SignerType");
    if (proxyUri != null) {
        URI uri = new URI(proxyUri);
        config.setProxyHost(uri.getHost());
        config.setProxyPort(uri.getPort());
    }

    AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
            .withClientConfiguration(config)
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, region));

    s3 = builder.build();
}
 
Example 3
Source Project: presto   Source File: PrestoS3FileSystem.java    License: Apache License 2.0 6 votes vote down vote up
private static Optional<AWSCredentials> getAwsCredentials(Configuration conf)
{
    String accessKey = conf.get(S3_ACCESS_KEY);
    String secretKey = conf.get(S3_SECRET_KEY);

    if (isNullOrEmpty(accessKey) || isNullOrEmpty(secretKey)) {
        return Optional.empty();
    }

    String sessionToken = conf.get(S3_SESSION_TOKEN);
    if (!isNullOrEmpty(sessionToken)) {
        return Optional.of(new BasicSessionCredentials(accessKey, secretKey, sessionToken));
    }

    return Optional.of(new BasicAWSCredentials(accessKey, secretKey));
}
 
Example 4
Source Project: tutorials   Source File: ProductInfoRepositoryIntegrationTest.java    License: MIT License 6 votes vote down vote up
@BeforeClass
public static void setupClass() {
    Properties testProperties = loadFromFileInClasspath("test.properties")
            .filter(properties -> !isEmpty(properties.getProperty(AWS_ACCESSKEY)))
            .filter(properties -> !isEmpty(properties.getProperty(AWS_SECRETKEY)))
            .filter(properties -> !isEmpty(properties.getProperty(DYNAMODB_ENDPOINT)))
            .orElseThrow(() -> new RuntimeException("Unable to get all of the required test property values"));

    String amazonAWSAccessKey = testProperties.getProperty(AWS_ACCESSKEY);
    String amazonAWSSecretKey = testProperties.getProperty(AWS_SECRETKEY);
    String amazonDynamoDBEndpoint = testProperties.getProperty(DYNAMODB_ENDPOINT);

    amazonDynamoDB = new AmazonDynamoDBClient(new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey));
    amazonDynamoDB.setEndpoint(amazonDynamoDBEndpoint);
    dynamoDBMapper = new DynamoDBMapper(amazonDynamoDB);
}
 
Example 5
Source Project: digdag   Source File: S3StorageIT.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp()
        throws Exception
{
    assumeThat(TEST_S3_ENDPOINT, not(isEmptyOrNullString()));

    projectDir = folder.getRoot().toPath().resolve("foobar");
    config = folder.newFile().toPath();

    client = DigdagClient.builder()
            .host(server.host())
            .port(server.port())
            .build();

    AWSCredentials credentials = new BasicAWSCredentials(TEST_S3_ACCESS_KEY_ID, TEST_S3_SECRET_ACCESS_KEY);
    s3 = new AmazonS3Client(credentials);
    s3.setEndpoint(TEST_S3_ENDPOINT);

    s3.createBucket(archiveBucket);
    s3.createBucket(logStorageBucket);
}
 
Example 6
Source Project: zipkin-aws   Source File: ITSQSCollector.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
  store = InMemoryStorage.newBuilder().build();
  metrics = new InMemoryCollectorMetrics();

  collector =
      new SQSCollector.Builder()
          .queueUrl(sqsRule.queueUrl())
          .parallelism(2)
          .waitTimeSeconds(1) // using short wait time to make test teardown faster
          .endpointConfiguration(new EndpointConfiguration(sqsRule.queueUrl(), "us-east-1"))
          .credentialsProvider(
              new AWSStaticCredentialsProvider(new BasicAWSCredentials("x", "x")))
          .metrics(metrics)
          .sampler(CollectorSampler.ALWAYS_SAMPLE)
          .storage(store)
          .build()
          .start();
  metrics = metrics.forTransport("sqs");
}
 
Example 7
Source Project: s3mper   Source File: AlertJanitor.java    License: Apache License 2.0 6 votes vote down vote up
public void initalize(URI uri, Configuration conf) {
    this.conf = conf;
    
    String keyId = conf.get("fs."+uri.getScheme()+".awsAccessKeyId");
    String keySecret = conf.get("fs."+uri.getScheme()+".awsSecretAccessKey");
    
    //An override option for accessing across accounts
    keyId = conf.get("fs."+uri.getScheme()+".override.awsAccessKeyId", keyId);
    keySecret = conf.get("fs."+uri.getScheme()+".override.awsSecretAccessKey", keySecret);
    
    sqs = new AmazonSQSClient(new BasicAWSCredentials(keyId, keySecret));
    
    //SQS Consistency Queue
    consistencyQueue = conf.get("fs"+uri.getScheme()+".alert.sqs.queue", consistencyQueue);
    consistencyQueue = sqs.getQueueUrl(new GetQueueUrlRequest(consistencyQueue)).getQueueUrl();
    
    //SQS Timeout Queue
    timeoutQueue = conf.get("fs"+uri.getScheme()+".timeout.sqs.queue", timeoutQueue);
    timeoutQueue = sqs.getQueueUrl(new GetQueueUrlRequest(timeoutQueue)).getQueueUrl();
}
 
Example 8
Source Project: oodt   Source File: S3DataTransfererFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public S3DataTransferer createDataTransfer() {
String bucketName = System.getProperty(BUCKET_NAME_PROPERTY);
String region = System.getProperty(REGION_PROPERTY);		
String accessKey = System.getProperty(ACCESS_KEY_PROPERTY);
  String secretKey = System.getProperty(SECRET_KEY_PROPERTY);
  boolean encrypt = Boolean.getBoolean(ENCRYPT_PROPERTY);

AmazonS3Client s3 = (AmazonS3Client) AmazonS3ClientBuilder.standard()
        .withRegion(region)
        .withCredentials(
                new AWSStaticCredentialsProvider(
                        new BasicAWSCredentials(accessKey, secretKey)))
        .build();

  return new S3DataTransferer(s3, bucketName, encrypt);
}
 
Example 9
Source Project: datacollector   Source File: TestAmazonS3Target.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setUpClass() throws IOException, InterruptedException {
  File dir = new File(new File("target", UUID.randomUUID().toString()), "fakes3_root").getAbsoluteFile();
  Assert.assertTrue(dir.mkdirs());
  fakeS3Root = dir.getAbsolutePath();
  port = TestUtil.getFreePort();
  fakeS3 = new FakeS3(fakeS3Root, port);
  Assume.assumeTrue("Please install fakes3 in your system", fakeS3.fakes3Installed());
  //Start the fakes3 server
  executorService = Executors.newSingleThreadExecutor();
  executorService.submit(fakeS3);

  BasicAWSCredentials credentials = new BasicAWSCredentials("foo", "bar");
  s3client = AmazonS3ClientBuilder
      .standard()
      .withCredentials(new AWSStaticCredentialsProvider(credentials))
      .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:" + port, null))
      .withPathStyleAccessEnabled(true)
      .withChunkedEncodingDisabled(true) // FakeS3 does not correctly calculate checksums with chunked encoding enabled.
      .build();

  TestUtil.createBucket(s3client, BUCKET_NAME);
  TestUtil.createBucket(s3client, SECOND_BUCKET_NAME);
}
 
Example 10
private static String getAWSAccountID() {
    try {
        String accessKey = AWS_ACCESS_KEY_ID;
        String secretKey = AWS_SECRET_KEY;

        if (Utilities.isEmpty(accessKey) || Utilities.isEmpty(secretKey)) {
            return null;
        }

        AWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey);
        AmazonIdentityManagementClient iam = new AmazonIdentityManagementClient(creds);
        return iam.getUser().getUser().getArn().split(":")[4];
    } catch (AmazonClientException e) {
        throw new RuntimeException("Failed to get AWS account id", e);
    }
}
 
Example 11
@Test
void shouldAuthenticate() {

	this.mockRest.expect(requestTo("/auth/aws/login")).andExpect(method(HttpMethod.POST))
			.andExpect(jsonPath("$.iam_http_request_method").value("POST"))
			.andExpect(jsonPath("$.iam_request_url").exists()).andExpect(jsonPath("$.iam_request_body").exists())
			.andExpect(jsonPath("$.iam_request_headers").exists()).andExpect(jsonPath("$.role").value("foo-role"))
			.andRespond(withSuccess().contentType(MediaType.APPLICATION_JSON).body(
					"{" + "\"auth\":{\"client_token\":\"my-token\", \"renewable\": true, \"lease_duration\": 10}"
							+ "}"));

	AwsIamAuthenticationOptions options = AwsIamAuthenticationOptions.builder().role("foo-role")
			.credentials(new BasicAWSCredentials("foo", "bar")).build();
	AwsIamAuthentication sut = new AwsIamAuthentication(options, this.restTemplate);

	VaultToken login = sut.login();

	assertThat(login).isInstanceOf(LoginToken.class);
	assertThat(login.getToken()).isEqualTo("my-token");
	assertThat(((LoginToken) login).getLeaseDuration()).isEqualTo(Duration.ofSeconds(10));
	assertThat(((LoginToken) login).isRenewable()).isTrue();
}
 
Example 12
private List<AWSCredentialsProvider> resolveCredentialsProviders(
		AwsCredentialsProperties properties) {
	List<AWSCredentialsProvider> providers = new ArrayList<>();

	if (StringUtils.hasText(properties.getAccessKey())
			&& StringUtils.hasText(properties.getSecretKey())) {
		providers.add(new AWSStaticCredentialsProvider(new BasicAWSCredentials(
				properties.getAccessKey(), properties.getSecretKey())));
	}

	if (properties.isInstanceProfile()) {
		providers.add(new EC2ContainerCredentialsProviderWrapper());
	}

	if (properties.getProfileName() != null) {
		providers.add(properties.getProfilePath() != null
				? new ProfileCredentialsProvider(properties.getProfilePath(),
						properties.getProfileName())
				: new ProfileCredentialsProvider(properties.getProfileName()));
	}

	return providers;
}
 
Example 13
Source Project: dynamodb-geo   Source File: Utilities.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized void setupGeoDataManager() {
	if (geoDataManager == null) {
		String accessKey = System.getProperty("AWS_ACCESS_KEY_ID");
		String secretKey = System.getProperty("AWS_SECRET_KEY");
		String tableName = System.getProperty("PARAM1");
		String regionName = System.getProperty("PARAM2");

		Region region = Region.getRegion(Regions.fromName(regionName));
		ClientConfiguration clientConfiguration = new ClientConfiguration().withMaxErrorRetry(20);
		AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

		AmazonDynamoDBClient ddb = new AmazonDynamoDBClient(credentials, clientConfiguration);
		ddb.setRegion(region);

		GeoDataManagerConfiguration config = new GeoDataManagerConfiguration(ddb, tableName);
		geoDataManager = new GeoDataManager(config);
	}
}
 
Example 14
Source Project: streams   Source File: KinesisPersistReader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void prepare(Object configurationObject) {
  // Connect to Kinesis
  synchronized (this) {
    // Create the credentials Object
    AWSCredentials credentials = new BasicAWSCredentials(config.getKey(), config.getSecretKey());

    ClientConfiguration clientConfig = new ClientConfiguration();
    clientConfig.setProtocol(Protocol.valueOf(config.getProtocol().toString()));

    this.client = new AmazonKinesisClient(credentials, clientConfig);
    if (StringUtils.isNotEmpty(config.getRegion()))
      this.client.setRegion(Region.getRegion(Regions.fromName(config.getRegion())));
  }
  streamNames = this.config.getStreams();
  executor = Executors.newFixedThreadPool(streamNames.size());
}
 
Example 15
@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();
}
 
Example 16
Source Project: aws-xray-sdk-java   Source File: TracingHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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();
    mockHttpClient(lambda, "null"); // Lambda returns "null" on successful fn. with no return value

    // Test logic
    Segment segment = AWSXRay.beginSegment("test");

    InvokeRequest request = new InvokeRequest();
    request.setFunctionName("testFunctionName");
    lambda.invoke(request);

    Assert.assertEquals(1, segment.getSubsegments().size());
    Assert.assertEquals("Invoke", segment.getSubsegments().get(0).getAws().get("operation"));
    Assert.assertEquals("testFunctionName", segment.getSubsegments().get(0).getAws().get("function_name"));
}
 
Example 17
Source Project: aws-mock   Source File: TerminateInstancesExample.java    License: MIT License 6 votes vote down vote up
/**
 * Terminate specified instances (power-on the instances).
 *
 * @param instanceIDs
 *            IDs of the instances to terminate
 * @return a list of state changes for the instances
 */
public static List<InstanceStateChange> terminateInstances(final List<String> instanceIDs) {
    // pass any credentials as aws-mock does not authenticate them at all
    AWSCredentials credentials = new BasicAWSCredentials("foo", "bar");
    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials);

    // the mock endpoint for ec2 which runs on your computer
    String ec2Endpoint = "http://localhost:8000/aws-mock/ec2-endpoint/";
    amazonEC2Client.setEndpoint(ec2Endpoint);

    // send the terminate request with args as instance IDs
    TerminateInstancesRequest request = new TerminateInstancesRequest();
    request.withInstanceIds(instanceIDs);
    TerminateInstancesResult result = amazonEC2Client.terminateInstances(request);

    return result.getTerminatingInstances();
}
 
Example 18
Source Project: aws-xray-sdk-java   Source File: TracingHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRaceConditionOnRecorderInitialization() {
    AWSXRay.setGlobalRecorder(null);
    // TracingHandler will not have the initialized recorder
    AWSLambda lambda = AWSLambdaClientBuilder
        .standard()
        .withRequestHandlers(new TracingHandler())
        .withRegion(Regions.US_EAST_1)
        .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("fake", "fake")))
        .build();

    mockHttpClient(lambda, "null");

    // Now init the global recorder
    AWSXRayRecorder recorder = AWSXRayRecorderBuilder.defaultRecorder();
    recorder.setContextMissingStrategy(new LogErrorContextMissingStrategy());
    AWSXRay.setGlobalRecorder(recorder);

    // Test logic
    InvokeRequest request = new InvokeRequest();
    request.setFunctionName("testFunctionName");
    lambda.invoke(request);
}
 
Example 19
Source Project: beam   Source File: SqsIOTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void before() {
  sqsRestServer = SQSRestServerBuilder.start();

  String endpoint = "http://localhost:9324";
  String region = "elasticmq";
  String accessKey = "x";
  String secretKey = "x";

  client =
      AmazonSQSClientBuilder.standard()
          .withCredentials(
              new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
          .withEndpointConfiguration(
              new AwsClientBuilder.EndpointConfiguration(endpoint, region))
          .build();
  final CreateQueueResult queue = client.createQueue("test");
  queueUrl = queue.getQueueUrl();
}
 
Example 20
Source Project: Cheddar   Source File: AmazonMailSenderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInitializeWithCredentialsAndTransport_givenAwsCredentials() {
    // Given
    final String awsAccessKeyId = randomString(10);
    final String awsAccessSecretId = randomString(10);
    final AWSCredentials awsCredentials = new BasicAWSCredentials(awsAccessKeyId, awsAccessSecretId);
    final AmazonMailSender mailSender = new AmazonMailSender(awsCredentials);

    // When
    mailSender.init();
    final Properties properties = mailSender.getJavaMailProperties();

    // Then
    assertEquals("aws", properties.getProperty("mail.transport.protocol"));
    assertEquals(awsAccessKeyId, properties.getProperty(AWSJavaMailTransport.AWS_ACCESS_KEY_PROPERTY));
    assertEquals(awsAccessSecretId, properties.getProperty(AWSJavaMailTransport.AWS_SECRET_KEY_PROPERTY));
}
 
Example 21
Source Project: beam   Source File: AwsModuleTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAWSStaticCredentialsProviderSerializationDeserialization() throws Exception {
  String awsKeyId = "key-id";
  String awsSecretKey = "secret-key";

  AWSStaticCredentialsProvider credentialsProvider =
      new AWSStaticCredentialsProvider(new BasicAWSCredentials(awsKeyId, awsSecretKey));

  String serializedCredentialsProvider = objectMapper.writeValueAsString(credentialsProvider);
  AWSCredentialsProvider deserializedCredentialsProvider =
      objectMapper.readValue(serializedCredentialsProvider, AWSCredentialsProvider.class);

  assertEquals(credentialsProvider.getClass(), deserializedCredentialsProvider.getClass());
  assertEquals(
      credentialsProvider.getCredentials().getAWSAccessKeyId(),
      deserializedCredentialsProvider.getCredentials().getAWSAccessKeyId());
  assertEquals(
      credentialsProvider.getCredentials().getAWSSecretKey(),
      deserializedCredentialsProvider.getCredentials().getAWSSecretKey());
}
 
Example 22
public com.amazonaws.services.kinesis.AmazonKinesis build(AmazonKinesis kinesisProperties) {

            com.amazonaws.services.kinesis.AmazonKinesisClientBuilder clientBuilder = com.amazonaws.services.kinesis.AmazonKinesisClientBuilder.standard();

            clientBuilder.setRegion(kinesisProperties.getRegion());
            clientBuilder.setCredentials(new AWSCredentialsProvider() {
                @Override
                public AWSCredentials getCredentials() {
                    return new BasicAWSCredentials(kinesisProperties.getKey(), kinesisProperties.getSecret());
                }
                @Override
                public void refresh() {
                }
            });
            clientBuilder.setClientConfiguration(new ClientConfiguration());

            return clientBuilder.build();
        }
 
Example 23
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
    try{
        String customerID = request.getParameter("customerID");
  BasicAWSCredentials awsCredentials = new BasicAWSCredentials("test", "test");
        AmazonSimpleDBClient sdbc = new AmazonSimpleDBClient(awsCredentials);
        
        String query = "select * from invoices where customerID = '"
            + customerID;
        SelectResult sdbResult = sdbc.select(new SelectRequest(query)); //BAD

        SelectResult sdbResult2 = sdbc.select(new SelectRequest(query, false)); //BAD

        SelectRequest sdbRequest = new SelectRequest();
        SelectResult sdbResult3 = sdbc.select(sdbRequest.withSelectExpression(query)); //BAD
        
        String query2 = "select * from invoices where customerID = 123";
        SelectResult sdbResult4 = sdbc.select(new SelectRequest(query2)); //OK

    }catch(Exception e){
        System.out.println(e);
   }
}
 
Example 24
Source Project: Baragon   Source File: BaragonServiceModule.java    License: Apache License 2.0 6 votes vote down vote up
@Provides
@Named(BARAGON_AWS_ELB_CLIENT_V2)
public com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancingClient providesAwsElbClientV2(Optional<ElbConfiguration> configuration) {
  com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancingClient elbClient;
  if (configuration.isPresent() && configuration.get().getAwsAccessKeyId() != null && configuration.get().getAwsAccessKeySecret() != null) {
    elbClient = new com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancingClient(new BasicAWSCredentials(configuration.get().getAwsAccessKeyId(), configuration.get().getAwsAccessKeySecret()));
  } else {
    elbClient = new com.amazonaws.services.elasticloadbalancingv2.AmazonElasticLoadBalancingClient();
  }

  if (configuration.isPresent() && configuration.get().getAwsEndpoint().isPresent()) {
    elbClient.setEndpoint(configuration.get().getAwsEndpoint().get());
  }
  if (configuration.isPresent() && configuration.get().getAwsRegion().isPresent()) {
    elbClient.configureRegion(Regions.fromName(configuration.get().getAwsRegion().get()));
  }

  return elbClient;
}
 
Example 25
Source Project: usergrid   Source File: WarehouseExport.java    License: Apache License 2.0 6 votes vote down vote up
private void copyToS3( String fileName ) {

        String bucketName = ( String ) properties.get( BUCKET_PROPNAME );
        String accessId = ( String ) properties.get( ACCESS_ID_PROPNAME );
        String secretKey = ( String ) properties.get( SECRET_KEY_PROPNAME );

        Properties overrides = new Properties();
        overrides.setProperty( "s3" + ".identity", accessId );
        overrides.setProperty( "s3" + ".credential", secretKey );

        final Iterable<? extends Module> MODULES = ImmutableSet
                .of( new JavaUrlHttpCommandExecutorServiceModule(), new Log4JLoggingModule(),
                        new NettyPayloadModule() );

        AWSCredentials credentials = new BasicAWSCredentials(accessId, secretKey);
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setProtocol( Protocol.HTTP);

        AmazonS3Client s3Client = new AmazonS3Client(credentials, clientConfig);

        s3Client.createBucket( bucketName );
        File uploadFile = new File( fileName );
        PutObjectResult putObjectResult = s3Client.putObject( bucketName, uploadFile.getName(), uploadFile );
        logger.info("Uploaded file etag={}", putObjectResult.getETag());
    }
 
Example 26
Source Project: cloudExplorer   Source File: Acl.java    License: GNU General Public License v3.0 5 votes vote down vote up
String setACLurl(String object, String access_key, String secret_key, String endpoint, String bucket) {
    String URL = null;
    try {
        AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);
        AmazonS3 s3Client = new AmazonS3Client(credentials,
                new ClientConfiguration());
         if (endpoint.contains("amazonaws.com")) {
            String aws_endpoint = s3Client.getBucketLocation(new GetBucketLocationRequest(bucket));
            if (aws_endpoint.contains("US")) {
                s3Client.setEndpoint("https://s3.amazonaws.com");
            } else if (aws_endpoint.contains("us-west")) {
                s3Client.setEndpoint("https://s3-" + aws_endpoint + ".amazonaws.com");
            } else if (aws_endpoint.contains("eu-west")) {
                s3Client.setEndpoint("https://s3-" + aws_endpoint + ".amazonaws.com");
            } else if (aws_endpoint.contains("ap-")) {
                s3Client.setEndpoint("https://s3-" + aws_endpoint + ".amazonaws.com");
            } else if (aws_endpoint.contains("sa-east-1")) {
                s3Client.setEndpoint("https://s3-" + aws_endpoint + ".amazonaws.com");
            } else {
                s3Client.setEndpoint("https://s3." + aws_endpoint + ".amazonaws.com");
            }
        } else {
            s3Client.setS3ClientOptions(S3ClientOptions.builder().setPathStyleAccess(true).build());
            s3Client.setEndpoint(endpoint);
        }
        java.util.Date expiration = new java.util.Date();
        long milliSeconds = expiration.getTime();
        milliSeconds += 1000 * 60 * 1000; // Add 1 hour.
        expiration.setTime(milliSeconds);
        GeneratePresignedUrlRequest generatePresignedUrlRequest
                = new GeneratePresignedUrlRequest(bucket, object);
        generatePresignedUrlRequest.setMethod(HttpMethod.GET);
        generatePresignedUrlRequest.setExpiration(expiration);
        URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
        URL = ("Pre-Signed URL = " + url.toString());
        StringSelection stringSelection = new StringSelection(url.toString());
    } catch (Exception setACLpublic) {
    }
    return URL;
}
 
Example 27
Source Project: presto   Source File: PrestoS3ClientFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static Optional<AWSCredentials> getAwsCredentials(Configuration conf)
{
    String accessKey = conf.get(S3_ACCESS_KEY);
    String secretKey = conf.get(S3_SECRET_KEY);

    if (isNullOrEmpty(accessKey) || isNullOrEmpty(secretKey)) {
        return Optional.empty();
    }
    return Optional.of(new BasicAWSCredentials(accessKey, secretKey));
}
 
Example 28
Source Project: cloudExplorer   Source File: Acl.java    License: GNU General Public License v3.0 5 votes vote down vote up
void setBUCKETwebsite(String object, String access_key, String secret_key, String endpoint, String bucket) {
    try {
        AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);
        AmazonS3 s3Client = new AmazonS3Client(credentials,
                new ClientConfiguration());
        if (endpoint.contains("amazonaws.com")) {
            String aws_endpoint = s3Client.getBucketLocation(new GetBucketLocationRequest(bucket));
            if (aws_endpoint.contains("US")) {
                s3Client.setEndpoint("https://s3.amazonaws.com");
            } else if (aws_endpoint.contains("us-west")) {
                s3Client.setEndpoint("https://s3-" + aws_endpoint + ".amazonaws.com");
            } else if (aws_endpoint.contains("eu-west")) {
                s3Client.setEndpoint("https://s3-" + aws_endpoint + ".amazonaws.com");
            } else if (aws_endpoint.contains("ap-")) {
                s3Client.setEndpoint("https://s3-" + aws_endpoint + ".amazonaws.com");
            } else if (aws_endpoint.contains("sa-east-1")) {
                s3Client.setEndpoint("https://s3-" + aws_endpoint + ".amazonaws.com");
            } else {
                s3Client.setEndpoint("https://s3." + aws_endpoint + ".amazonaws.com");
            }
        } else {
            s3Client.setS3ClientOptions(S3ClientOptions.builder().setPathStyleAccess(true).build());
            s3Client.setEndpoint(endpoint);
        }
        BucketWebsiteConfiguration bucketWebsiteConfiguration = s3Client.getBucketWebsiteConfiguration(bucket);
        s3Client.setBucketAcl(bucket, CannedAccessControlList.PublicRead);
        s3Client.setBucketWebsiteConfiguration(bucket, new BucketWebsiteConfiguration("index.html", "error.html"));
    } catch (Exception setACLpublic) {
        mainFrame.jTextArea1.append("\nException occurred in ACL");
    }
}
 
Example 29
Source Project: attic-apex-malhar   Source File: S3FileMerger.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create AmazonS3 client using AWS credentials
 * @return AmazonS3
 */
protected AmazonS3 createClient()
{
  AmazonS3 client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretAccessKey));
  if (endPoint != null) {
    client.setEndpoint(endPoint);
  }
  return client;
}
 
Example 30
Source Project: s3proxy   Source File: S3ProxyRuleTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public final void setUp() throws Exception {
    s3Client = AmazonS3ClientBuilder
        .standard()
        .withCredentials(
            new AWSStaticCredentialsProvider(
                new BasicAWSCredentials(
                    s3Proxy.getAccessKey(), s3Proxy.getSecretKey())))
        .withEndpointConfiguration(
            new EndpointConfiguration(
                s3Proxy.getUri().toString(), Regions.US_EAST_1.getName()))
        .build();

    s3Client.createBucket(MY_TEST_BUCKET);
}