Example usage for com.amazonaws.services.s3 AmazonS3 listBuckets

List of usage examples for com.amazonaws.services.s3 AmazonS3 listBuckets

Introduction

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

Prototype

public List<Bucket> listBuckets() throws SdkClientException, AmazonServiceException;

Source Link

Document

Returns a list of all Amazon S3 buckets that the authenticated sender of the request owns.

Usage

From source file:ics.uci.edu.amazons3.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*/*from   w w  w .  ja  v  a  2s  .  c o m*/
     * This credentials provider implementation loads your AWS credentials
     * from a properties file at the root of your classpath.
     * 
     * 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
     */
    final AmazonS3 s3 = new AmazonS3Client(
            new BasicAWSCredentials("AKIAJTW5BOY6EXOGV2YQ", "PDcnFYIf9Hdo9GsKTEjLXretZ3yEg4mRCDQKjxu6"));

    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:iit.edu.supadyay.s3.S3upload.java

public static List listOfBuckets() {
    List bucketNames = new ArrayList();
    //AWSCredentials credentials = new BasicAWSCredentials(access, secret);
    //AmazonS3 s3client = new AmazonS3Client(getCredentials());
    AmazonS3 s3client = new AmazonS3Client(new InstanceProfileCredentialsProvider());

    for (Bucket bucket : s3client.listBuckets()) {
        bucketNames.add(bucket.getName());
        s3client.listObjects(bucket.getName());
    }/*from  w  w w.  ja va  2s  . c  o  m*/
    //bucketNames.addAll(s3client.listBuckets());
    bucketNames.toString();
    return bucketNames;
}

From source file:io.konig.camel.aws.s3.DeleteObjectComponentVerifierExtension.java

License:Apache License

@Override
protected Result verifyConnectivity(Map<String, Object> parameters) {
    ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY);

    try {//from   ww  w.j a va  2 s.  c  o  m
        S3Configuration configuration = setProperties(new S3Configuration(), parameters);
        AWSCredentials credentials = new BasicAWSCredentials(configuration.getAccessKey(),
                configuration.getSecretKey());
        AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
        AmazonS3 client = AmazonS3ClientBuilder.standard().withCredentials(credentialsProvider)
                .withRegion(Regions.valueOf(configuration.getRegion())).build();
        client.listBuckets();
    } catch (SdkClientException e) {
        ResultErrorBuilder errorBuilder = ResultErrorBuilder
                .withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage())
                .detail("aws_s3_exception_message", e.getMessage())
                .detail(VerificationError.ExceptionAttribute.EXCEPTION_CLASS, e.getClass().getName())
                .detail(VerificationError.ExceptionAttribute.EXCEPTION_INSTANCE, e);

        builder.error(errorBuilder.build());
    } catch (Exception e) {
        builder.error(ResultErrorBuilder.withException(e).build());
    }
    return builder.build();
}

From source file:io.konig.camel.aws.s3.DeleteObjectProducer.java

License:Apache License

private void listBuckets(AmazonS3 s3Client, Exchange exchange) {
    List<Bucket> bucketsList = s3Client.listBuckets();

    Message message = getMessageForResponse(exchange);
    message.setBody(bucketsList);/*  w w  w . j a  v  a 2  s .  c om*/
}

From source file:javafxawss3sample.FXMLDocumentController.java

@Override
public void initialize(URL url, ResourceBundle rb) {
    AmazonS3 s3 = new AmazonS3Client();
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);/*from  w  ww  .  j a  va  2  s .  c om*/
    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon S3");
    System.out.println("===========================================");
    s3.listBuckets().forEach(bucket -> {
        // creating tab for each bucket
        Tab tab = new Tab();
        String bucketNm = bucket.getName();
        tab.setText(bucketNm);
        tabPane.getTabs().add(tab);
        VBox vbox = new VBox(10);
        vbox.setPadding(new Insets(10));
        vbox.setStyle("-fx-background-color: #ffc9ae");
        // Owner
        HBox hbox1 = new HBox(10);
        Label ownerLabel = new Label("Owner:");
        String owner = bucket.getOwner().getDisplayName();
        Text ownerText = new Text(owner);
        hbox1.getChildren().addAll(ownerLabel, ownerText);
        // Create Date
        HBox hbox2 = new HBox(10);
        Label dateLabel = new Label("Create Date:");
        String createDate = bucket.getCreationDate().toString();
        Text dateText = new Text(createDate);
        hbox2.getChildren().addAll(dateLabel, dateText);
        tab.setContent(vbox);
        tab.setStyle("-fx-background-color: #ffc9ae;");
        // ListView for file path
        ObservableList<String> items = FXCollections.observableArrayList("file path");
        ListView view = new ListView(items);
        ObjectListing objList = s3
                .listObjects(new ListObjectsRequest().withBucketName(bucketNm).withPrefix(""));
        objList.getObjectSummaries().forEach(obj -> {
            String filePath = obj.getKey();
            items.add(filePath);
        });
        vbox.getChildren().addAll(hbox1, hbox2, view);
    });
}

From source file:md.djembe.aws.AmazonS3WebClient.java

License:Apache License

public static void listBucket() {
    AmazonS3 s3Client = getS3Client();
    List<Bucket> buckets = s3Client.listBuckets();
    for (Bucket bucket : buckets) {
        LOGGER.info("bucket : " + bucket.getName() + "\t" + StringUtils.fromDate(bucket.getCreationDate()));
    }//  w ww  .j  a  v a2  s .co  m
}

From source file:org.alanwilliamson.amazon.s3.ListBuckets.java

License:Open Source License

public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {

    AmazonKey amazonKey = getAmazonKey(_session, argStruct);
    AmazonS3 s3Client = getAmazonS3(amazonKey);

    try {/*from  ww w  . ja v  a 2 s  .  c o  m*/
        //Create the results
        cfQueryResultData qD = new cfQueryResultData(new String[] { "bucket", "createdate" }, null);
        qD.setQuerySource("AmazonS3." + amazonKey.getDataSource());

        List<Bucket> bucketList = s3Client.listBuckets();

        for (Iterator<Bucket> it = bucketList.iterator(); it.hasNext();) {
            Bucket bucket = it.next();

            qD.addRow(1);
            qD.setCurrentRow(qD.getSize());
            qD.setCell(1, new cfStringData(bucket.getName()));
            qD.setCell(2, new cfDateData(bucket.getCreationDate()));
        }

        return qD;
    } catch (Exception e) {
        throwException(_session, "AmazonS3: " + e.getMessage());
        return cfBooleanData.FALSE;
    }
}

From source file:org.boriken.s3fileuploader.S3SampleRefactored.java

License:Open Source License

public static void listBuckets(AmazonS3 s3) {
    /*/*from   w  ww. ja v  a  2 s .com*/
     * List the buckets in your account
     */
    System.out.println("Listing buckets");
    for (Bucket bucket : s3.listBuckets()) {
        System.out.println(" - " + bucket.getName());
    }
    System.out.println();
}

From source file:org.caboclo.clients.AmazonClient.java

License:Open Source License

private AmazonS3 getS3_() throws AmazonClientException {
    AmazonS3 s3_;
    S3ClientOptions s3ClientOptions;/*from   w ww.  ja  v a2s . c o  m*/
    //        AWSCredentials credentials = new BasicAWSCredentials(Constants.EC2_ACCESS_KEY, Constants.EC2_SECRET_KEY);

    AWSCredentials credentials = new BasicAWSCredentials(getAuthenticationParameter(ACCESS_KEY),
            getAuthenticationParameter(SECRET_KEY));

    s3_ = new AmazonS3Client(credentials);
    s3ClientOptions = new S3ClientOptions();
    //s3_.setEndpoint(Constants.EC2_END_POINT);
    s3ClientOptions.setPathStyleAccess(true);
    s3_.setS3ClientOptions(s3ClientOptions);
    System.out.println(s3_.listBuckets());
    return s3_;
}

From source file:org.clothocad.phagebook.adaptors.S3Adapter.java

public static void initializeUserFolder(Person pers) {
    String clothoId = pers.getId();

    AWSCredentials credentials = new BasicAWSCredentials(S3Credentials.getUsername(),
            S3Credentials.getPassword());
    AmazonS3 s3client = new AmazonS3Client(credentials);
    System.out.println("Login Complete");

    // list buckets
    for (Bucket bucket : s3client.listBuckets()) {
        System.out.println(" - " + bucket.getName());
    }//from ww  w.  j a va 2s .  c  o m

    System.out.println("Clotho id " + clothoId);
    createS3Folder("phagebookaws", clothoId, s3client);

    //------------TESTING BEFORE INTEGRATED INTO PROFILE------------
    /*String fileName = clothoId + "/" + "profilePicture.jpg";
    String picturePath = "C:\\Users\\azula\\Pictures\\AllisonDurkan.jpg";
    s3client.putObject(new PutObjectRequest("phagebookaws", fileName,
        new File(picturePath))
        .withCannedAcl(CannedAccessControlList.PublicRead));*/

}