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

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

Introduction

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

Prototype

@SdkInternalApi
AmazonS3Client(AmazonS3ClientParams s3ClientParams) 

Source Link

Document

Constructs a new client to invoke service methods on S3 using the specified parameters.

Usage

From source file:au.edu.unsw.cse.soc.federatedcloud.deployers.aws.s3.AWSS3Deployer.java

License:Open Source License

@Path("/deploy")
@POST//from   ww  w . j  a v  a2  s  .c  o  m
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
/*@Override*/
public Response deploy(@QueryParam("descriptionid") String descriptionid) throws Exception {
    //Reading the credentials
    Properties properties = new Properties();
    properties.load(this.getClass().getResourceAsStream("/AwsCredentials.properties"));
    String accessKey = properties.getProperty("accessKey");
    String secretKey = properties.getProperty("secretKey");

    AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

    AmazonS3Client client = new AmazonS3Client(credentials);

    //String name = description.getAttributes().get("name");
    String name = "ddweerasiri-test-bucket";
    //client.createBucket(name);

    log.info("Bucket was created with name:" + name);
    System.out.println("Helooooooo:" + descriptionid);

    JsonObject json = new JsonObject();
    json.addProperty("cloudResourceDescriptionId", descriptionid);
    return Response.status(Response.Status.OK).entity(json.toString()).build();
}

From source file:au.edu.unsw.cse.soc.federatedcloud.deployers.aws.s3.AWSS3Deployer.java

License:Open Source License

@Override
public void undeployResource(String resourceID) throws Exception {
    //Reading the credentials
    Properties properties = new Properties();
    properties.load(this.getClass().getResourceAsStream("/AwsCredentials.properties"));
    String accessKey = properties.getProperty("accessKey");
    String secretKey = properties.getProperty("secretKey");

    AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

    AmazonS3Client client = new AmazonS3Client(credentials);
    client.deleteBucket(resourceID);//from w  w w  . j  av  a 2  s  .com

    Response.status(Response.Status.OK).entity(json.toString()).build();

}

From source file:au.edu.unsw.cse.soc.federatedcloud.deployers.aws.s3.ClassForPaper.java

License:Open Source License

@Path("/deployResource")
@POST/*from  w ww. java 2  s  .  co  m*/
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response deployResource(@QueryParam("description") CRCD resourceDescription) throws Exception {
    //Reading the credentials
    Properties properties = new Properties();
    properties.load(this.getClass().getResourceAsStream("/AwsCredentials.properties"));
    String accessKey = properties.getProperty("accessKey");
    String secretKey = properties.getProperty("secretKey");
    AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    AmazonS3Client client = new AmazonS3Client(credentials);

    String name = resourceDescription.getAttribute("bucket-name");
    Bucket bucket = client.createBucket(name);

    JsonObject json = new JsonObject();
    json.addProperty("resourceID", bucket.getName());
    return Response.status(Response.Status.OK).entity(json.toString()).build();
}

From source file:au.edu.unsw.cse.soc.federatedcloud.deployers.aws.s3.ClassForPaper.java

License:Open Source License

@Path("/undeployResource")
@POST//ww  w  . j  a  va  2 s .co  m
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response undeployResource(@QueryParam("resourceID") String resourceID) throws Exception {
    //Reading the credentials
    Properties properties = new Properties();
    properties.load(this.getClass().getResourceAsStream("/AwsCredentials.properties"));
    String accessKey = properties.getProperty("accessKey");
    String secretKey = properties.getProperty("secretKey");
    AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    AmazonS3Client client = new AmazonS3Client(credentials);

    client.deleteBucket(resourceID);

    JsonObject json = new JsonObject();
    json.addProperty("result", "Bucket:" + resourceID + "undeployed.");
    return Response.status(Response.Status.OK).entity(json.toString()).build();
}

From source file:avreye.mytarotadvisor.utils.Util.java

License:Open Source License

/**
 * Gets an instance of a S3 client which is constructed using the given
 * Context.//  w ww  . j  a  v a 2s .  c om
 *
 * @param context An Context instance.
 * @return A default S3 client.
 */
public static AmazonS3Client getS3Client(Context context) {
    if (sS3Client == null) {
        sS3Client = new AmazonS3Client(getCredProvider(context.getApplicationContext()));
    }
    return sS3Client;
}

From source file:aws.sample.AwsConsoleApp.java

License:Open Source License

/**
 * The only information needed to create a client are security credentials consisting of the AWS Access Key ID and Secret Access Key. All other configuration, such as the service endpoints, are performed automatically. Client parameters, such as proxies, can be specified in an optional ClientConfiguration object when constructing a client.
 * //from w ww.j a  v  a2  s  .  c  o  m
 * @see com.amazonaws.auth.BasicAWSCredentials
 * @see com.amazonaws.auth.PropertiesCredentials
 * @see com.amazonaws.ClientConfiguration
 */
private static void init() throws Exception {
    AWSCredentials credentials = new PropertiesCredentials(
            AwsConsoleApp.class.getResourceAsStream("/AwsCredentials.properties"));

    ec2 = new AmazonEC2Client(credentials);
    s3 = new AmazonS3Client(credentials);
    sdb = new AmazonSimpleDBClient(credentials);
}

From source file:aws.sample.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*/*from   ww  w  .  j av  a  2  s.c  om*/
     * Important: Be sure to fill in your AWS access credentials in the AwsCredentials.properties file before you try to run this sample. http://aws.amazon.com/security-credentials
     */
    AmazonS3 s3 = new AmazonS3Client(
            new PropertiesCredentials(S3Sample.class.getResourceAsStream("/AwsCredentials.properties")));

    String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
    String key = "MyObjectKey";

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon S3");
    System.out.println("===========================================\n");

    try {
        /*
         * Create a new S3 bucket - Amazon S3 bucket names are globally unique, so once a bucket name has been taken by any user, you can't create another bucket with that same name.
         * 
         * You can optionally specify a location for your bucket if you want to keep your data closer to your applications or users.
         */
        System.out.println("Creating bucket " + bucketName + "\n");
        s3.createBucket(bucketName);

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();

        /*
         * Upload an object to your bucket - You can easily upload a file to S3, or upload directly an InputStream if you know the length of the data in the stream. You can also specify your own metadata when uploading to S3, which allows you set a variety of options like content-type and content-encoding, plus additional metadata specific to your applications.
         */
        System.out.println("Uploading a new object to S3 from a file\n");
        s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

        /*
         * Download an object - When you download an object, you get all of the object's metadata and a stream from which to read the contents. It's important to read the contents of the stream as quickly as possibly since the data is streamed directly from Amazon S3 and your network connection will remain open until you read all the data or close the input stream.
         * 
         * GetObjectRequest also supports several other options, including conditional downloading of objects based on modification times, ETags, and selectively downloading a range of an object.
         */
        System.out.println("Downloading an object");
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());

        /*
         * List objects in your bucket by prefix - There are many options for listing the objects in your bucket. Keep in mind that buckets with many objects might truncate their results when listing their objects, so be sure to check if the returned object listing is truncated, and use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve additional results.
         */
        System.out.println("Listing objects");
        ObjectListing objectListing = s3
                .listObjects(new ListObjectsRequest().withBucketName(bucketName).withPrefix("My"));
        for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(
                    " - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");
        }
        System.out.println();

        /*
         * Delete an object - Unless versioning has been turned on for your bucket, there is no way to undelete an object, so use caution when deleting objects.
         */
        System.out.println("Deleting an object\n");
        s3.deleteObject(bucketName, key);

        /*
         * Delete a bucket - A bucket must be completely empty before it can be deleted, so remember to delete any objects from your buckets before you try to delete them.
         */
        System.out.println("Deleting bucket " + bucketName + "\n");
        s3.deleteBucket(bucketName);
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon S3, but was rejected with an error response for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:awslabs.lab21.Lab21.java

License:Open Source License

/**
 * Controls the flow of the lab code execution.
 *//*w ww .j  ava 2 s  .c om*/
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;//  ww w .  j a  va2s  .c  om
    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(/*from  w ww  . j a  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;
}