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

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

Introduction

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

Prototype

public URL generatePresignedUrl(GeneratePresignedUrlRequest generatePresignedUrlRequest)
        throws SdkClientException;

Source Link

Document

Returns a pre-signed URL for accessing an Amazon S3 resource.

Usage

From source file:awslabs.lab21.SolutionCode.java

License:Open Source License

@Override
public String generatePreSignedUrl(AmazonS3 s3Client, String bucketName, String key) {
    Date nowPlusOneHour = new Date(System.currentTimeMillis() + 3600000L);

    // Construct a GeneratePresignedUrlRequest object for the provided object.
    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key);
    // Set the expiration value in the request to the nowPlusOneHour object 
    // (this specifies a time one hour from now). 
    generatePresignedUrlRequest.setExpiration(nowPlusOneHour);

    // Submit the request using the generatePresignedUrl method of the s3Client object.
    URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
    // Return the URL as a string.
    return url.toString();
}

From source file:cloudExplorer.Acl.java

License:Open Source License

String setACLurl(String object, String access_key, String secret_key, String endpoint, String bucket) {
    String URL = null;//from  w  ww .  j av  a 2 s.c  o m
    try {
        AWSCredentials credentials = new BasicAWSCredentials(access_key, secret_key);
        AmazonS3 s3Client = new AmazonS3Client(credentials,
                new ClientConfiguration().withSignerOverride("S3SignerType"));
        s3Client.setEndpoint(endpoint);
        java.util.Date expiration = new java.util.Date();
        long milliSeconds = expiration.getTime();
        milliSeconds += 1000 * 60 * 1000; // Add 1 hour.
        expiration.setTime(milliSeconds);
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucket,
                object);
        generatePresignedUrlRequest.setMethod(HttpMethod.GET);
        generatePresignedUrlRequest.setExpiration(expiration);
        URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
        URL = ("Pre-Signed URL = " + url.toString());
        StringSelection stringSelection = new StringSelection(url.toString());
        Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
        clpbrd.setContents(stringSelection, null);
    } catch (Exception setACLpublic) {
        mainFrame.jTextArea1.append("\nException occured in ACL");
    }
    return URL;
}

From source file:com.climate.oada.dao.impl.S3ResourceDAO.java

License:Open Source License

@Override
public List<FileResource> getFileUrls(Long userId, String type) {
    List<FileResource> retval = new ArrayList<FileResource>();
    long validfor = new Long(validHours).longValue() * HOURS_TO_MILLISECONDS;
    try {//from ww w .ja  v  a2  s .  c o m
        AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
        String prefix = userId.toString() + S3_SEPARATOR + type;

        LOG.debug("Listing objects from bucket " + bucketName + " with prefix " + prefix);

        ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName)
                .withPrefix(prefix);
        ObjectListing objectListing;
        do {
            objectListing = s3client.listObjects(listObjectsRequest);
            for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                LOG.debug(" - " + objectSummary.getKey() + "  " + "(size = " + objectSummary.getSize() + ")");

                Date expiration = new Date();
                long milliSeconds = expiration.getTime();
                milliSeconds += validfor;
                expiration.setTime(milliSeconds);

                GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                        bucketName, objectSummary.getKey());
                generatePresignedUrlRequest.setMethod(HttpMethod.GET);
                generatePresignedUrlRequest.setExpiration(expiration);

                FileResource res = new FileResource();
                res.setFileURL(s3client.generatePresignedUrl(generatePresignedUrlRequest));
                retval.add(res);
            }
            listObjectsRequest.setMarker(objectListing.getNextMarker());
        } while (objectListing.isTruncated());
    } catch (AmazonServiceException ase) {
        logAWSServiceException(ase);
    } catch (AmazonClientException ace) {
        logAWSClientException(ace);
    } catch (Exception e) {
        LOG.error("Unable to retrieve S3 file URLs " + e.getMessage());
    }
    return retval;
}

From source file:com.handywedge.binarystore.store.aws.BinaryStoreManagerImpl.java

License:MIT License

private URL getPresignedUrl(AmazonS3 s3client, String buckrtName, String key) {
    logger.info("getPresignedUrl start.");

    java.util.Date expiration = new java.util.Date();
    long milliSeconds = expiration.getTime();
    milliSeconds += Long.parseLong(PropertiesUtil.get("aws.presignedurl.expiration"));
    expiration.setTime(milliSeconds);//from w w  w  .  j av a2 s .  c  o  m

    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(buckrtName, key);
    generatePresignedUrlRequest.setMethod(HttpMethod.GET);
    generatePresignedUrlRequest.setExpiration(expiration);

    URL PresignedUrl = s3client.generatePresignedUrl(generatePresignedUrlRequest);

    logger.info("getPresignedUrl: end. url={}", PresignedUrl);
    return PresignedUrl;
}

From source file:com.kirana.utils.GeneratePresignedUrlAndUploadObject.java

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

    System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
    System.setProperty(SDKGlobalConfiguration.ACCESS_KEY_ENV_VAR, "AKIAJ666LALJZHA6THGQ");
    System.setProperty(SDKGlobalConfiguration.SECRET_KEY_ENV_VAR, "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");
    //      AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider("kirana"));

    ProfilesConfigFile profile = new ProfilesConfigFile("AwsCredentials.properties");
    AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
    s3client.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1));

    try {/*from  www.j a v  a 2s  . co m*/
        System.out.println("Generating pre-signed URL.");
        java.util.Date expiration = new java.util.Date();
        long milliSeconds = expiration.getTime();
        milliSeconds += 1000 * 60 * 60; // Add 1 hour.
        expiration.setTime(milliSeconds);

        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName,
                objectKey);
        generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
        generatePresignedUrlRequest.setExpiration(expiration);

        //                        s3client.putObject(bucketName, objectKey, null);

        URL url = s3client.generatePresignedUrl(generatePresignedUrlRequest);
        UploadObject(url);

        System.out.println("Pre-Signed URL = " + url.toString());
    } catch (AmazonServiceException exception) {
        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: " + exception.getMessage());
        System.out.println("HTTP  Code: " + exception.getStatusCode());
        System.out.println("AWS Error Code:" + exception.getErrorCode());
        System.out.println("Error Type:    " + exception.getErrorType());
        System.out.println("Request ID:    " + exception.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, " + "which means the client encountered "
                + "an internal error 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:com.zhang.aws.s3.S3Sample.java

License:Open Source License

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

    /*/*from w w  w. j  a va  2s.c  om*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (~/.aws/credentials).
     */
    ResourceBundle bundle = ResourceBundle.getBundle("credentials");
    AWSCredentials credentials = null;
    try {
        //            credentials = new ProfileCredentialsProvider().getCredentials();
        credentials = new BasicAWSCredentials(bundle.getString("aws_access_key_id"),
                bundle.getString("aws_secret_access_key"));
    } 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 = "elasticbeanstalk-us-west-2-948206320069";
    String key = "MyObjectKey2";

    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()));
        s3.putObject(new PutObjectRequest(bucketName, key, getFileFromDisk()));
        /***
         * 
         * ?url
         * */
        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, key);
        URL generatePresignedUrl = s3.generatePresignedUrl(urlRequest);
        System.out.println("public url:" + generatePresignedUrl.toString());
        /*
         * 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);
        System.out.println("------------------------------------------");
    } 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:eu.crowdrec.flume.plugins.source.DirectIdomaarSource.java

License:Apache License

private BufferedReader createReaderFromUrl() throws IOException {
    if (url.startsWith("s3://")) {
        logger.info("Reading resource {} from Amazon S3.", url);
        AmazonS3 s3 = new AmazonS3Client(createAWSCreditentials());
        AmazonS3URI amazonURI = new AmazonS3URI(url);
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(amazonURI.getBucket(),
                amazonURI.getKey());/*from   w ww.j  a  va 2 s.c om*/
        URL httpUrl = s3.generatePresignedUrl(request);
        InputStream inp = httpUrl.openStream();
        return new BufferedReader(new InputStreamReader(inp));
    }
    throw new RuntimeException("Can only handle s3:// scheme. Cannot use URL " + url);
}

From source file:hudson.plugins.ec2.EC2Cloud.java

License:Open Source License

/**
 * Computes the presigned URL for the given S3 resource.
 *
 * @param path//from  w w w. j a  v a 2 s .  com
 *      String like "/bucketName/folder/folder/abc.txt" that represents the resource to request.
 */
public URL buildPresignedURL(String path) throws AmazonClientException {
    AWSCredentials credentials = awsCredentialsProvider.getCredentials();
    long expires = System.currentTimeMillis() + 60 * 60 * 1000;
    GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(path, credentials.getAWSSecretKey());
    request.setExpiration(new Date(expires));
    AmazonS3 s3 = new AmazonS3Client(credentials);
    return s3.generatePresignedUrl(request);
}

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

License:Apache License

private void createDownloadLink(AmazonS3 s3Client, Exchange exchange) {
    String bucketName = exchange.getIn().getHeader(S3Constants.BUCKET_NAME, String.class);
    if (ObjectHelper.isEmpty(bucketName)) {
        bucketName = getConfiguration().getBucketName();
    }/*from w ww . j a va  2  s .  c  o m*/

    if (bucketName == null) {
        throw new IllegalArgumentException("AWS S3 Bucket name header is missing.");
    }

    String key = exchange.getIn().getHeader(S3Constants.KEY, String.class);
    if (key == null) {
        throw new IllegalArgumentException("AWS S3 Key header is missing.");
    }

    Date expiration = new Date();
    long milliSeconds = expiration.getTime();

    Long expirationMillis = exchange.getIn().getHeader(S3Constants.DOWNLOAD_LINK_EXPIRATION, Long.class);
    if (expirationMillis != null) {
        milliSeconds += expirationMillis;
    } else {
        milliSeconds += 1000 * 60 * 60; // Default: Add 1 hour.
    }

    expiration.setTime(milliSeconds);

    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key);
    generatePresignedUrlRequest.setMethod(HttpMethod.GET);
    generatePresignedUrlRequest.setExpiration(expiration);

    URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);

    Message message = getMessageForResponse(exchange);
    message.setHeader(S3Constants.DOWNLOAD_LINK, url.toString());
}

From source file:modules.storage.AmazonS3Storage.java

License:Open Source License

@Override
public F.Promise<Result> getDownload(String key, String name) {
    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key);
    ResponseHeaderOverrides responseHeaders = new ResponseHeaderOverrides();
    responseHeaders.setContentDisposition("attachment; filename=" + name);
    generatePresignedUrlRequest.setResponseHeaders(responseHeaders);

    AmazonS3 amazonS3 = new AmazonS3Client(credentials);

    try {//  ww  w .  j  a  va2  s.  co m
        URL url = amazonS3.generatePresignedUrl(generatePresignedUrlRequest);

        return F.Promise.pure(redirect(url.toString()));
    } catch (AmazonClientException ace) {
        logAmazonClientException(ace);
        return F.Promise.pure(internalServerError(error.render()));
    }
}