com.amazonaws.services.s3.model.GetObjectMetadataRequest#com.amazonaws.auth.BasicAWSCredentials源码实例Demo

下面列出了com.amazonaws.services.s3.model.GetObjectMetadataRequest#com.amazonaws.auth.BasicAWSCredentials 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * {@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;
}
 
源代码2 项目: ecs-sync   文件: AwsS3Test.java
@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();
}
 
源代码3 项目: presto   文件: PrestoS3FileSystem.java
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));
}
 
@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);
}
 
源代码5 项目: digdag   文件: S3StorageIT.java
@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);
}
 
源代码6 项目: zipkin-aws   文件: ITSQSCollector.java
@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");
}
 
源代码7 项目: s3mper   文件: AlertJanitor.java
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();
}
 
源代码8 项目: oodt   文件: S3DataTransfererFactory.java
@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);
}
 
源代码9 项目: datacollector   文件: TestAmazonS3Target.java
@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);
}
 
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);
    }
}
 
@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();
}
 
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;
}
 
源代码13 项目: dynamodb-geo   文件: Utilities.java
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);
	}
}
 
源代码14 项目: streams   文件: KinesisPersistReader.java
@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());
}
 
@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();
}
 
源代码16 项目: aws-xray-sdk-java   文件: TracingHandlerTest.java
@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"));
}
 
源代码17 项目: aws-mock   文件: TerminateInstancesExample.java
/**
 * 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();
}
 
源代码18 项目: aws-xray-sdk-java   文件: TracingHandlerTest.java
@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);
}
 
源代码19 项目: beam   文件: SqsIOTest.java
@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();
}
 
源代码20 项目: Cheddar   文件: AmazonMailSenderTest.java
@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));
}
 
源代码21 项目: beam   文件: AwsModuleTest.java
@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());
}
 
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();
        }
 
源代码23 项目: Android_Code_Arbiter   文件: AwsQueryInjection.java
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);
   }
}
 
源代码24 项目: Baragon   文件: BaragonServiceModule.java
@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;
}
 
源代码25 项目: usergrid   文件: WarehouseExport.java
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());
    }
 
源代码26 项目: cloudExplorer   文件: Acl.java
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;
}
 
源代码27 项目: presto   文件: PrestoS3ClientFactory.java
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));
}
 
源代码28 项目: cloudExplorer   文件: Acl.java
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");
    }
}
 
源代码29 项目: attic-apex-malhar   文件: S3FileMerger.java
/**
 * 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;
}
 
源代码30 项目: s3proxy   文件: S3ProxyRuleTest.java
@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);
}