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

@Deprecated
public AmazonS3Client() 

Source Link

Document

Constructs a new client to invoke service methods on Amazon S3.

Usage

From source file:br.com.unb.aws.client.S3ClientV1.java

License:Open Source License

public static void main(String[] args) throws IOException {
    /*/*from  ww  w  . j a va2s. c o m*/
     * Create your credentials file at ~/.aws/credentials (C:\Users\USER_NAME\.aws\credentials for Windows users) 
     * and save the following lines after replacing the underlined values with your own.
     *
     * [default]
     * aws_access_key_id = YOUR_ACCESS_KEY_ID
     * aws_secret_access_key = YOUR_SECRET_ACCESS_KEY
     */

    AmazonS3 s3 = new AmazonS3Client();
    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());
    }
}

From source file:ch.admin.isb.hermes5.persistence.s3.S3ServiceFactory.java

License:Apache License

public AmazonS3 getAmazonS3() {
    return "".equals(accessKey.getStringValue()) ? new AmazonS3Client()
            : new AmazonS3Client(
                    new BasicAWSCredentials(accessKey.getStringValue(), secretKey.getStringValue()));

}

From source file:ch.admin.isb.hermes5.tools.filebackup.FileBackup.java

License:Apache License

private AmazonS3 s3(String accessKey, String secretKey, String s3Endpoint) {
    AmazonS3 s3 = accessKey == null || "".equals(accessKey) ? new AmazonS3Client()
            : new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey));
    s3.setEndpoint(s3Endpoint);//  w w  w.  j a  v  a 2 s . c  o m
    return s3;
}

From source file:com.adobe.acs.commons.mcp.impl.processes.asset.S3AssetIngestorFactory.java

License:Apache License

@Override
public boolean isAllowed(User user) {
    if (super.isAllowed(user)) {
        // check if S3 SDK is available
        try {//from w  w  w  . ja v  a2  s. co  m
            new AmazonS3Client();
            return true;
        } catch (NoClassDefFoundError e) {
            // ignore
        }
    }
    return false;
}

From source file:com.adobe.acs.commons.mcp.impl.processes.S3AssetIngestorFactory.java

License:Apache License

@Override
public boolean isAllowed(User user) {
    if (super.isAllowed(user)) {
        // check if S3 SDK is available
        try {/*  w  w  w .  j  a  v a2s  . c  o  m*/
            AmazonS3 s3Client = new AmazonS3Client();
            return true;
        } catch (NoClassDefFoundError e) {
        }
    }
    return false;
}

From source file:com.adobe.people.jedelson.rugsinlambda.GenerateHandler.java

License:Apache License

@Override
protected GenerationResultDTO handleRequest(GenerationRequestDTO input, Context context, Rugs rugs) {
    String generatorName = (String) input.getGeneratorName();
    log.info("Using {} as generator name from {}.", generatorName, input);

    Optional<ProjectGenerator> opt = asJavaCollection(rugs.generators()).stream()
            .filter(g -> g.name().equals(input.getGeneratorName())).findFirst();
    if (opt.isPresent()) {
        ProjectGenerator generator = opt.get();
        ParameterValues paramValues = input.toParameterValues();
        if (!generator.areValid(paramValues)) {
            GenerationResultDTO result = new GenerationResultDTO(false);
            asJavaCollection(generator.findInvalidParameterValues(paramValues)).forEach(p -> {
                result.addInvalidParameter(p);
            });/*ww  w  . ja v a2 s.  co  m*/
            asJavaCollection(generator.findMissingParameters(paramValues)).forEach(p -> {
                result.addMissingParameter(p);
            });
            return result;
        } else {
            String projectName = input.getParams().get("project_name");
            TempProjectManagement tpm = new TempProjectManagement(context.getAwsRequestId());
            tpm.generate(generator, paramValues, projectName);

            GenerationResultDTO result = new GenerationResultDTO(true);

            for (EditRequestDTO edit : input.getEditors()) {
                String editorName = edit.getName();
                log.info("Editing with {} using params {}.", editorName, edit.getParams());
                Optional<ProjectEditor> editorOpt = asJavaCollection(rugs.editors()).stream()
                        .filter(g -> g.name().equals(editorName)).findFirst();
                if (editorOpt.isPresent()) {
                    ProjectEditor editor = editorOpt.get();
                    ParameterValues editorParams = edit.toParameterValues(input.getParams());
                    if (!editor.areValid(editorParams)) {
                        asJavaCollection(generator.findInvalidParameterValues(paramValues)).forEach(p -> {
                            result.addInvalidParameter(editorName, p);
                        });
                        asJavaCollection(generator.findMissingParameters(paramValues)).forEach(p -> {
                            result.addMissingParameter(editorName, p);
                        });
                    } else {
                        tpm.edit(editor, editorParams, projectName);
                    }
                }
            }

            File zipFile = tpm.createZipFile();
            log.info("zip file is at {} length is {}.", zipFile.getAbsolutePath(), zipFile.length());

            AmazonS3Client s3Client = new AmazonS3Client();
            String keyName = context.getAwsRequestId() + "/project.zip";
            s3Client.putObject(BUCKET_NAME, keyName, zipFile);

            Date expiration = new Date();
            long msec = expiration.getTime();
            msec += 1000 * 60 * 60; // 1 hour.
            expiration.setTime(msec);

            GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                    BUCKET_NAME, keyName);
            generatePresignedUrlRequest.setMethod(HttpMethod.GET);
            generatePresignedUrlRequest.setExpiration(expiration);

            URL presignedUrl = s3Client.generatePresignedUrl(generatePresignedUrlRequest);

            result.setUrl(presignedUrl.toString());
            return result;
        }
    } else {
        throw new NoSuchGeneratorException(input.getGeneratorName());
    }
}

From source file:com.adobe.people.jedelson.rugsinlambda.helpers.RugWrapper.java

License:Apache License

public RugWrapper(String requestId) throws IOException {
    tmpRoot = new File(FileUtils.getTempDirectory().getAbsoluteFile(), requestId);
    tmpRoot.mkdirs();/* www . j  a v  a 2  s.c o m*/
    repo = new File(tmpRoot, "rugs");
    File archiveFolder = new File(repo, groupId + "/" + artifactId + "/" + version);
    archiveFolder.mkdirs();
    archive = new File(archiveFolder, artifactId + "-" + version + ".zip");

    AmazonS3Client s3Client = new AmazonS3Client();
    S3Object rugFile = s3Client.getObject(rugBucketName, rugObjectKey);

    FileUtils.copyToFile(rugFile.getObjectContent(), archive);
    log.info("Saved rug zip in {}", archive);
}

From source file:com.amediamanager.config.S3ConfigurationProvider.java

License:Apache License

@Override
public void persistNewProperty(String key, String value) {
    if (this.properties != null) {
        this.properties.put(key, value);
        AmazonS3 s3Client = new AmazonS3Client();
        try {// w  w w  .  j  av  a 2s  .  c o  m
            s3Client.putObject(this.bucket, this.key,
                    IOUtils.toInputStream(this.propsToString(this.properties)), null);
        } catch (AmazonS3Exception ase) {
            LOG.error("Error persisting config from s3://{}/{}", new Object[] { this.bucket, this.key, ase });
        }
    } else {
        LOG.error("Could not persist new property because this.properties is null.");
    }
}

From source file:com.BoomPi.ImageResizeHandlerFromS3.java

License:Apache License

private RawImage getOriginalImage(S3Event s3Event) throws Exception {

    S3EventNotificationRecord record = s3Event.getRecords().get(0);

    String srcBucket = record.getS3().getBucket().getName();
    String srcKey = record.getS3().getObject().getKey().replace('+', ' ');
    srcKey = URLDecoder.decode(srcKey, "UTF-8");

    if (!new FormatValidator(srcKey).isValid())
        throw new Exception("not valid file format");

    BufferedImage srcImage = null;
    AmazonS3 s3Client = new AmazonS3Client();

    try (S3Object s3Object = s3Client.getObject(new GetObjectRequest(srcBucket, srcKey));) {
        InputStream objectData = s3Object.getObjectContent();
        srcImage = ImageIO.read(objectData);
    }//ww  w.ja v a2  s  . co m

    // TODO implement other type of RawImage model
    JpegRawImage jpegRawImage = new JpegRawImage(srcImage.getWidth(), srcImage.getHeight(), srcBucket, srcKey,
            srcImage);

    return jpegRawImage;

}

From source file:com.BoomPi.ImageResizeHandlerFromS3.java

License:Apache License

private String putResizedImageToS3(ImageProcess jpegImageProcess, String s3ObjectKey, int width, int height)
        throws IOException {
    ByteArrayOutputStream os = jpegImageProcess.resize(width, height).getOutPutStream();
    try (InputStream is = new ByteArrayInputStream(os.toByteArray());) {

        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(os.size());
        meta.setContentType(jpegImageProcess.getImageMime());

        String dstKey = String.join("_", "resized", s3ObjectKey);

        AmazonS3 s3Client = new AmazonS3Client();

        System.out.println("Writing to: " + dstBucket + "/" + dstKey);
        s3Client.putObject(dstBucket, dstKey, is, meta);
    }/*from w ww  .  j a v a 2 s  .  c o m*/
    return "Ok";
}