Example usage for com.amazonaws.services.s3 AmazonS3Client setRegion

List of usage examples for com.amazonaws.services.s3 AmazonS3Client setRegion

Introduction

In this page you can find the example usage for com.amazonaws.services.s3 AmazonS3Client setRegion.

Prototype

@Override
@Deprecated
public synchronized void setRegion(com.amazonaws.regions.Region region) 

Source Link

Usage

From source file:awslabs.lab21.Lab21.java

License:Open Source License

/**
 * Controls the flow of the lab code execution.
 *///from  w  w w.  j av  a  2s.c  o  m
public static void main(String[] args) {
    try {
        String bucketName = labBucketPrefix + UUID.randomUUID().toString().substring(0, 8);
        String testImage = "test-image.png";
        String publicTestImage = "public-test-image.png";
        String testImage2 = "test-image2.png";

        // Create an S3 client
        AmazonS3Client s3Client = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
        s3Client.setRegion(region);

        // Clean up leftovers from previous instances of this lab
        CleanupPreviousLabRuns(s3Client);

        // Create a bucket
        System.out.println("Creating bucket " + bucketName);
        labCode.createBucket(s3Client, bucketName, region);

        // Create an object in the bucket
        File sourceFile = new File(testImage);
        if (sourceFile.exists()) {
            System.out.println("Uploading object: " + testImage);
            labCode.putObject(s3Client, bucketName, testImage, testImage);
            System.out.println("Uploading complete.");
        } else {
            System.out.println("Source file " + testImage + " doesn't exist.");
            return;
        }

        sourceFile = new File(testImage2);
        if (sourceFile.exists()) {
            System.out
                    .println("Uploading another copy of the object (will be made publically available later).");
            labCode.putObject(s3Client, bucketName, testImage2, publicTestImage);
            System.out.println("Uploading complete.");
        } else {
            System.out.println("Source file " + testImage2 + " doesn't exist.");
            return;
        }

        // List objects in the bucket
        System.out.println("Listing items in bucket: " + bucketName);
        labCode.listObjects(s3Client, bucketName);
        System.out.println("Listing complete.");

        // Change the ACL on one of the objects to make it public
        System.out.println("Changing the ACL to make an object public");
        labCode.makeObjectPublic(s3Client, bucketName, publicTestImage);
        System.out.println("Done the object should be publically available now. Test this URL to confirm:");
        System.out.println("  http://" + bucketName + ".s3.amazonaws.com/" + publicTestImage);

        // Generate a pre-signed URL for an object to grant temporary access to the file.
        System.out.println("Generating presigned URL.");
        String presignedUrl = labCode.generatePreSignedUrl(s3Client, bucketName, testImage);
        System.out.println("Done. Test this URL to confirm:");
        System.out.println("  " + presignedUrl);

    } catch (Exception ex) {
        LabUtility.dumpError(ex);
    }

}

From source file:awslabs.lab41.Lab41.java

License:Open Source License

public static void main(String[] args) {
    LabVariables labVariables = null;/*from   www  .  j  a va  2 s .  c  o m*/
    Lab41 lab41 = new Lab41();
    try {
        // Start the "prep" mode operations to make sure that the resources are all in the expected state.
        System.out.println("Starting up in 'prep' mode.");
        labVariables = lab41.prepMode_Run();

        System.out.println("\nPrep complete. Transitioning to 'app' mode.");
        lab41.appMode_Run(labVariables);
    } catch (Exception ex) {
        LabUtility.dumpError(ex);
    } finally {
        try {
            if (labVariables != null) {
                System.out.println("");
                System.out.print("Lab run completed. Cleaning up buckets. ");
                AmazonS3Client s3Client = new AmazonS3Client(lab41.getCredentials("prepmode"));
                s3Client.setRegion(region);
                optionalLabCode.removeLabBuckets(s3Client, labVariables.getBucketNames());
                System.out.println("Done.");
            }
        } catch (Exception ex) {
            System.out.println("Attempt to clean up buckets failed. " + ex.getMessage());
        }
    }
}

From source file:awslabs.lab41.Lab41.java

License:Open Source License

public LabVariables prepMode_Run() throws IOException {
    LabVariables labVariables = new LabVariables();

    AWSCredentials credentials = getCredentials("prepmode");

    AmazonIdentityManagementClient iamClient = new AmazonIdentityManagementClient(credentials);
    //iamClient.setRegion(Lab41.region);

    String trustRelationshipSource = readTextFile("TrustRelationship.txt");
    String developmentPolicyText = readTextFile("development_role.txt");
    String productionPolicyText = readTextFile("production_role.txt");

    // Clean up environment by removing the roles if they exist. 
    optionalLabCode.prepMode_RemoveRoles(iamClient, "development_role", "production_role");

    // Trust relationships for roles (the way we're using them) require the ARN of the user.
    String userArn = labCode.prepMode_GetUserArn(iamClient, LabUserName);
    System.out.println("ARN for " + LabUserName + " is " + userArn);
    String trustRelationship = trustRelationshipSource.replaceAll("\\{userArn\\}", userArn);
    System.out.println("Trust relationship policy:\n" + trustRelationship);

    // Create the roles and store the role ARNs
    labVariables.setDevelopmentRoleArn(labCode.prepMode_CreateRole(iamClient, "development_role",
            developmentPolicyText, trustRelationship));
    labVariables.setProductionRoleArn(//  w  ww. ja v  a  2  s  .  c  o m
            labCode.prepMode_CreateRole(iamClient, "production_role", productionPolicyText, trustRelationship));

    System.out.println("Created development policy role: " + labVariables.getDevelopmentRoleArn());
    System.out.println("Created production policy role: " + labVariables.getProductionRoleArn());

    // Create the bucket names

    String identifier = UUID.randomUUID().toString().substring(0, 8);
    labVariables.getBucketNames().add("dev" + identifier);
    labVariables.getBucketNames().add("prod" + identifier);

    // Create the buckets
    AmazonS3Client s3Client = new AmazonS3Client(credentials);
    s3Client.setRegion(Lab41.region);
    for (String bucketName : labVariables.getBucketNames()) {
        optionalLabCode.prepMode_CreateBucket(s3Client, bucketName, region);
        System.out.println("Created bucket: " + bucketName);
    }

    return labVariables;
}

From source file:awslabs.lab41.SolutionCode.java

License:Open Source License

@Override
public AmazonS3Client appMode_CreateS3Client(Credentials credentials, Region region) {
    AmazonS3Client s3Client;
    //  Construct a BasicSessionCredentials object using the provided credentials.
    BasicSessionCredentials sessionCredentials = new BasicSessionCredentials(credentials.getAccessKeyId(),
            credentials.getSecretAccessKey(), credentials.getSessionToken());

    //  Construct an an AmazonS3Client object using the basic session credentials that you just created.
    s3Client = new AmazonS3Client(sessionCredentials);
    //  Set the region of the S3 client object to the provided region.
    s3Client.setRegion(region);

    //  Return the S3 client object.
    return s3Client;
}

From source file:awslabs.lab51.SolutionCode.java

License:Open Source License

@Override
public AmazonS3Client createS3Client(AWSCredentials credentials) {
    Region region = Region.getRegion(Regions.fromName(System.getProperty("REGION")));
    AmazonS3Client client = new AmazonS3Client();
    client.setRegion(region);

    return client;
}

From source file:com.digitalpebble.stormcrawler.aws.s3.AbstractS3CacheBolt.java

License:Apache License

/** Returns an S3 client given the configuration **/
public static AmazonS3Client getS3Client(Map conf) {
    AWSCredentialsProvider provider = new DefaultAWSCredentialsProviderChain();
    AWSCredentials credentials = provider.getCredentials();
    ClientConfiguration config = new ClientConfiguration();

    AmazonS3Client client = new AmazonS3Client(credentials, config);

    String regionName = ConfUtils.getString(conf, REGION);
    if (StringUtils.isNotBlank(regionName)) {
        client.setRegion(RegionUtils.getRegion(regionName));
    }/*ww w  .  ja v  a2s . c o  m*/

    String endpoint = ConfUtils.getString(conf, ENDPOINT);
    if (StringUtils.isNotBlank(endpoint)) {
        client.setEndpoint(endpoint);
    }
    return client;
}

From source file:com.facebook.presto.hive.s3.PrestoS3FileSystem.java

License:Apache License

private AmazonS3Client createAmazonS3Client(URI uri, Configuration hadoopConfig,
        ClientConfiguration clientConfig) {
    AWSCredentialsProvider credentials = getAwsCredentialsProvider(uri, hadoopConfig);
    Optional<EncryptionMaterialsProvider> emp = createEncryptionMaterialsProvider(hadoopConfig);
    AmazonS3Client client;
    String signerType = hadoopConfig.get(S3_SIGNER_TYPE);
    if (signerType != null) {
        clientConfig.withSignerOverride(signerType);
    }//from  www  .  j  a  v  a 2 s . c o m
    if (emp.isPresent()) {
        client = new AmazonS3EncryptionClient(credentials, emp.get(), clientConfig, new CryptoConfiguration(),
                METRIC_COLLECTOR);
    } else {
        client = new AmazonS3Client(credentials, clientConfig, METRIC_COLLECTOR);
    }

    if (isPathStyleAccess) {
        S3ClientOptions clientOptions = S3ClientOptions.builder().setPathStyleAccess(true).build();
        client.setS3ClientOptions(clientOptions);
    }

    // use local region when running inside of EC2
    if (pinS3ClientToCurrentRegion) {
        Region region = Regions.getCurrentRegion();
        if (region != null) {
            client.setRegion(region);
        }
    }

    String endpoint = hadoopConfig.get(S3_ENDPOINT);
    if (endpoint != null) {
        client.setEndpoint(endpoint);
    }

    return client;
}

From source file:com.kpbird.aws.Main.java

public void createS3() {

    try {// w  w w  .  ja v  a2  s .c o m
        AmazonS3Client s3 = new AmazonS3Client(credentials);
        s3.setEndpoint(endPoint);
        s3.setRegion(region);
        log.Info("Creating Bucket :" + BucketName);

        s3.createBucket(BucketName);
        log.Info("Policy :" + BucketPolicy);
        s3.setBucketPolicy(BucketName, BucketPolicy);

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
}

From source file:com.optimalbi.AmazonAccount.java

License:Apache License

private void populateS3() throws AmazonClientException {
    AmazonS3Client client = new AmazonS3Client(credentials.getCredentials());
    client.setRegion(regions.get(0));
    List<Bucket> buckets = client.listBuckets();
    for (Bucket bucket : buckets) {
        Service temp = new LocalS3Service(bucket.getName(), credentials, regions.get(0), bucket, logger);
        services.add(temp);//from w  ww .ja  v a  2 s  . c  o  m
    }
}

From source file:com.sludev.commons.vfs2.provider.s3.SS3FileProvider.java

License:Apache License

/**
 * Create FileSystem event hook//from w  w  w .  j  ava 2 s  .  c o  m
 * 
 * @param rootName
 * @param fileSystemOptions
 * @return
 * @throws FileSystemException 
 */
@Override
protected FileSystem doCreateFileSystem(FileName rootName, FileSystemOptions fileSystemOptions)
        throws FileSystemException {
    SS3FileSystem fileSystem = null;
    GenericFileName genRootName = (GenericFileName) rootName;

    AWSCredentials storageCreds;
    AmazonS3Client client;

    FileSystemOptions currFSO;
    UserAuthenticator ua;

    if (fileSystemOptions == null) {
        currFSO = getDefaultFileSystemOptions();
        ua = SS3FileSystemConfigBuilder.getInstance().getUserAuthenticator(currFSO);
    } else {
        currFSO = fileSystemOptions;
        ua = DefaultFileSystemConfigBuilder.getInstance().getUserAuthenticator(currFSO);
    }

    UserAuthenticationData authData = null;
    try {
        authData = ua.requestAuthentication(AUTHENTICATOR_TYPES);

        String currAcct = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(genRootName.getUserName())));

        String currKey = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(genRootName.getPassword())));

        storageCreds = new BasicAWSCredentials(currAcct, currKey);

        client = new AmazonS3Client(storageCreds);

        if (StringUtils.isNoneBlank(endpoint)) {
            client.setEndpoint(endpoint);
        }

        if (region != null) {
            client.setRegion(region);
        }

        fileSystem = new SS3FileSystem(genRootName, client, fileSystemOptions);
    } finally {
        UserAuthenticatorUtils.cleanup(authData);
    }

    return fileSystem;
}