Example usage for com.amazonaws.services.s3.model S3ObjectSummary getKey

List of usage examples for com.amazonaws.services.s3.model S3ObjectSummary getKey

Introduction

In this page you can find the example usage for com.amazonaws.services.s3.model S3ObjectSummary getKey.

Prototype

public String getKey() 

Source Link

Document

Gets the key under which this object is stored in Amazon S3.

Usage

From source file:cloudExplorer.BucketClass.java

License:Open Source License

String listBucketContents(String access_key, String secret_key, String bucket, String endpoint) {
    objectlist = null;//from   w  w w . j  av  a2 s .com

    AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);
    AmazonS3 s3Client = new AmazonS3Client(credentials,
            new ClientConfiguration().withSignerOverride("S3SignerType"));
    s3Client.setEndpoint(endpoint);

    try {
        ObjectListing current = s3Client.listObjects((bucket));

        ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucket);
        ObjectListing objectListing;
        do {
            objectListing = s3Client.listObjects(listObjectsRequest);
            for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                objectlist = objectlist + "@@" + objectSummary.getKey();
            }
            listObjectsRequest.setMarker(objectListing.getNextMarker());
        } while (objectListing.isTruncated());

    } catch (Exception listBucket) {
        mainFrame.jTextArea1.append("\n" + listBucket.getMessage());
    }

    String parse = null;
    if (objectlist != null) {
        parse = objectlist;
    } else {
        parse = "No objects_found.";
    }
    return parse;
}

From source file:cloudExplorer.BucketClass.java

License:Open Source License

String getObjectInfo(String key, String access_key, String secret_key, String bucket, String endpoint,
        String process) {/* w  w  w  .  j  a v  a  2 s .co  m*/
    AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);
    AmazonS3 s3Client = new AmazonS3Client(credentials,
            new ClientConfiguration().withSignerOverride("S3SignerType"));
    s3Client.setEndpoint(endpoint);
    objectlist = null;

    try {
        ObjectListing current = s3Client.listObjects((bucket));

        ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucket);
        ObjectListing objectListing;
        do {
            objectListing = s3Client.listObjects(listObjectsRequest);

            for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {

                if (process.contains("objectsize")) {
                    if (objectSummary.getKey().contains(key)) {
                        objectlist = String.valueOf(objectSummary.getSize());
                        break;
                    }
                }

                if (process.contains("objectdate")) {
                    if (objectSummary.getKey().contains(key)) {
                        objectlist = String.valueOf(objectSummary.getLastModified());
                        break;
                    }

                }
            }
            listObjectsRequest.setMarker(objectListing.getNextMarker());
        } while (objectListing.isTruncated());

    } catch (Exception listBucket) {
        mainFrame.jTextArea1.append("\n" + listBucket.getMessage());
    }

    return objectlist;
}

From source file:cloudtrailviewer.components.S3FileChooserDialog.java

License:Open Source License

private void reloadContents() {

    List<String> tmp = new ArrayList<String>();
    this.files.setAll(tmp);

    String bucketName = PropertiesSingleton.getInstance().getProperty("Bucket");

    ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
    listObjectsRequest.setBucketName(bucketName);
    listObjectsRequest.setPrefix(prefix);
    listObjectsRequest.setDelimiter("/");

    AWSCredentials credentials = new BasicAWSCredentials(PropertiesSingleton.getInstance().getProperty("Key"),
            PropertiesSingleton.getInstance().getProperty("Secret"));

    AmazonS3 s3Client = new AmazonS3Client(credentials);

    ObjectListing objectListing = s3Client.listObjects(listObjectsRequest);

    // these are directories
    List<String> directories = objectListing.getCommonPrefixes();
    for (String directory : directories) {

        tmp.add(stripPrefix(directory));
    }// ww w .ja  va2 s  .com

    // these are files
    List<S3ObjectSummary> objectSummaries = objectListing.getObjectSummaries();
    for (final S3ObjectSummary objectSummary : objectSummaries) {

        tmp.add(stripPrefix(objectSummary.getKey()));
    }

    this.files.setAll(tmp);
}

From source file:com.ALC.SC2BOAserver.aws.S3StorageManager.java

License:Open Source License

/**
 * Deletes the specified S3 object from the S3 storage service.  If a
 * storage path is passed in that has child S3 objects, it will recursively
 * delete the underlying objects./* ww  w  .  ja v a2 s  .  c  om*/
 * @param s3Store the s3 object to be deleted
 */
public void delete(SC2BOAStorageObject s3Store) {

    if (s3Store.getStoragePath() == null || s3Store.getStoragePath().equals("")) {
        logger.log(Level.WARNING, "Empty storage path passed to delete method");
        return; // We don't want to delete everything in a path
    }

    // Go through the store structure and delete child objects
    ObjectListing listing = s3Client.listObjects(s3Store.getBucketName(), s3Store.getStoragePath());
    while (true) {
        List<S3ObjectSummary> objectList = listing.getObjectSummaries();
        for (S3ObjectSummary summary : objectList) {
            s3Client.deleteObject(s3Store.getBucketName(), summary.getKey());
        }
        if (listing.isTruncated()) {
            listing = s3Client.listNextBatchOfObjects(listing);
        } else {
            break;
        }
    }

}

From source file:com.altoukhov.svsync.fileviews.S3FileSpace.java

License:Apache License

@Override
protected Snapshot scan(List<Pattern> filters) {
    try {//  www .j a  v a2s.  c  o m
        Map<String, FileSnapshot> files = new LinkedHashMap<>();
        Set<String> dirs = new HashSet<>();

        ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName)
                .withPrefix(rootPath.isEmpty() ? "" : rootPath + "/");

        ObjectListing objectListing;

        do {
            objectListing = listObjects(listObjectsRequest);
            for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {

                if (isExcluded(objectSummary.getKey()) || isFiltered(objectSummary.getKey(), filters))
                    continue;

                if (objectSummary.getKey().endsWith("/")) {
                    String filePath = trimPath(objectSummary.getKey());
                    filePath = filePath.equals(rootPath) ? ""
                            : filePath.substring(rootPath.length() + (rootPath.isEmpty() ? 0 : 1));
                    dirs.add(filePath);
                    System.out
                            .println(String.format("Scanning s3://%s/%s", bucketName, objectSummary.getKey()));
                } else {
                    String fileName = objectSummary.getKey();
                    String filePath = "";

                    if (fileName.contains("/")) {
                        int fileNameSplitIndex = fileName.lastIndexOf("/");
                        filePath = fileName.substring(0, fileNameSplitIndex);
                        fileName = fileName.substring(fileNameSplitIndex + 1);

                        filePath = filePath.equals(rootPath) ? ""
                                : filePath.substring(rootPath.length() + (rootPath.isEmpty() ? 0 : 1));
                    }

                    if (filePath.equals("")) {
                        filePath = fileName;
                    } else {
                        filePath = filePath + "/" + fileName;
                    }

                    ObjectMetadata meta = getObjectInfo(objectSummary);
                    String lmd = meta.getUserMetaDataOf("lmd");

                    Date lastModified = (lmd == null) ? objectSummary.getLastModified()
                            : new Date(Long.parseLong(lmd));

                    FileSnapshot file = new FileSnapshot(fileName, objectSummary.getSize(),
                            new DateTime(lastModified), filePath);
                    files.put(filePath, file);
                }
            }
            listObjectsRequest.setMarker(objectListing.getNextMarker());
        } while (objectListing.isTruncated());

        Snapshot snapshot = new Snapshot(files, dirs);
        return snapshot;
    } catch (AmazonClientException ex) {
        System.out.println("Failed to scan file space");
        System.out.println(ex.getMessage());
    }

    return null;
}

From source file:com.altoukhov.svsync.fileviews.S3FileSpace.java

License:Apache License

private ObjectMetadata getObjectInfo(S3ObjectSummary objectSummary) throws AmazonClientException {

    ObjectMetadata meta = null;//from  w  w w.j  a v a  2  s . c o  m
    int attemptCount = 0;

    while ((meta == null) && (attemptCount < 3)) {
        try {
            meta = s3.getObjectMetadata(bucketName, objectSummary.getKey());
            attemptCount++;
        } catch (AmazonClientException ex) {
            if (attemptCount < 3) {
                System.out.println(String.format("Failed to get metadata for s3://%s/%s, retrying.", bucketName,
                        objectSummary.getKey()));
            } else {
                throw ex;
            }
        }
    }

    return meta;
}

From source file:com.amazon.aws.samplecode.travellog.aws.S3StorageManager.java

License:Open Source License

/**
 * Deletes the specified S3 object from the S3 storage service.  If a
 * storage path is passed in that has child S3 objects, it will recursively
 * delete the underlying objects.//from  w  w  w  . jav  a2  s  . c  o m
 * @param s3Store the s3 object to be deleted
 */
public void delete(TravelLogStorageObject s3Store) {

    if (s3Store.getStoragePath() == null || s3Store.getStoragePath().equals("")) {
        logger.log(Level.WARNING, "Empty storage path passed to delete method");
        return; //We don't want to delete everything in a path
    }

    //Go through the store structure and delete child objects
    ObjectListing listing = s3client.listObjects(s3Store.getBucketName(), s3Store.getStoragePath());
    while (true) {
        List<S3ObjectSummary> objectList = listing.getObjectSummaries();
        for (S3ObjectSummary summary : objectList) {
            s3client.deleteObject(s3Store.getBucketName(), summary.getKey());
        }
        if (listing.isTruncated()) {
            listing = s3client.listNextBatchOfObjects(listing);
        } else {
            break;
        }
    }

}

From source file:com.android.demo.notepad3.NoteList.java

License:Open Source License

/** Called when the activity is first created. */
@Override/* www.jav  a  2  s  .  c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);
    setTitle("Note list");
    // initialize the client
    mClient = Util.getS3Client(NoteList.this);

    mList = (ListView) findViewById(R.id.list);

    mAdapter = new ObjectAdapter(this);
    mList.setOnItemClickListener(new ItemClickListener());
    mList.setAdapter(mAdapter);

    mRefreshButton = (Button) findViewById(R.id.refresh);

    findViewById(R.id.download).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // download all the objects that were selected
            String[] keys = new String[mSelectedObjects.size()];
            int i = 0;
            for (S3ObjectSummary obj : mSelectedObjects) {
                keys[i] = obj.getKey();
                i++;
            }
            TransferController.download(NoteList.this, keys);
        }
    });

    findViewById(R.id.refresh).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            new RefreshTask().execute();
        }
    });

    new RefreshTask().execute();

    // make timer that will refresh all the transfer views
    mTimer = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            NoteList.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    syncModels();
                    refresh();
                }
            });
        }
    };
    //      mTimer.schedule(task, 0, REFRESH_DELAY);
}

From source file:com.android.demo.notepad3.Util.java

License:Open Source License

public static void deleteBucket() {
    String name = Constants.BUCKET_NAME.toLowerCase(Locale.US);
    List<S3ObjectSummary> objData = sS3Client.listObjects(name).getObjectSummaries();
    if (objData.size() > 0) {
        DeleteObjectsRequest emptyBucket = new DeleteObjectsRequest(name);
        List<KeyVersion> keyList = new ArrayList<KeyVersion>();
        for (S3ObjectSummary summary : objData) {
            keyList.add(new KeyVersion(summary.getKey()));
        }/*from w w w.  ja v a2 s .co  m*/
        emptyBucket.withKeys(keyList);
        sS3Client.deleteObjects(emptyBucket);
    }
    sS3Client.deleteBucket(name);
}

From source file:com.arc.cloud.aws.s3.S3Sample.java

License:Open Source License

public static void main(String[] args) throws IOException {

    /*//ww  w  .  j a  v a2s.  co m
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider().getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (~/.aws/credentials), and is in valid format.", e);
    }

    AmazonS3 s3 = new AmazonS3Client(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    s3.setRegion(usWest2);

    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());
    }
}