Example usage for com.amazonaws.services.s3.model GeneratePresignedUrlRequest GeneratePresignedUrlRequest

List of usage examples for com.amazonaws.services.s3.model GeneratePresignedUrlRequest GeneratePresignedUrlRequest

Introduction

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

Prototype

public GeneratePresignedUrlRequest(String bucketName, String key) 

Source Link

Document

Creates a new request for generating a pre-signed URL that can be used as part of an HTTP GET request to access the Amazon S3 object stored under the specified key in the specified bucket.

Usage

From source file:com.emc.vipr.s3.sample._07_PresignedURL.java

License:Open Source License

public static void main(String[] args) throws Exception {
    // create the ViPR S3 Client
    ViPRS3Client s3 = ViPRS3Factory.getS3Client();

    // retrieve the key value from user
    System.out.println("Enter the object key:");
    String key = new BufferedReader(new InputStreamReader(System.in)).readLine();

    // retrieve the expiration time for the object from user
    System.out.print("How many hours should this URL be valid? ");
    String hours = new BufferedReader(new InputStreamReader(System.in)).readLine();

    // convert hours to a date
    Date expiration = new Date();
    long curTime_msec = expiration.getTime();
    long nHours = Long.valueOf(hours);
    curTime_msec += 60 * 60 * 1000 * nHours;
    expiration.setTime(curTime_msec);/*from ww  w. ja  v  a 2  s  .  co m*/

    // generate the object's pre-signed URL
    GeneratePresignedUrlRequest presignedUrl = new GeneratePresignedUrlRequest(ViPRS3Factory.S3_BUCKET, key);
    presignedUrl.setMethod(HttpMethod.GET);
    presignedUrl.setExpiration(expiration);

    URL url = s3.generatePresignedUrl(presignedUrl);

    // print object's pre-signed URL
    System.out.println(
            String.format("object [%s/%s] pre-signed URL: [%s]", ViPRS3Factory.S3_BUCKET, key, url.toString()));
}

From source file:com.github.abhinavmishra14.aws.s3.service.impl.AwsS3IamServiceImpl.java

License:Open Source License

@Override
public URL generateObjectURL(final String bucketName, final String fileName)
        throws AmazonClientException, AmazonServiceException {
    LOGGER.info("generateObjectURL invoked, bucketName: {}, fileName: {}", bucketName, fileName);
    final GeneratePresignedUrlRequest presignedUrlReq = new GeneratePresignedUrlRequest(bucketName, fileName);
    return s3client.generatePresignedUrl(presignedUrlReq);
}

From source file:com.github.abhinavmishra14.aws.s3.service.impl.AwsS3IamServiceImpl.java

License:Open Source License

@Override
public URL generateObjectURL(final String bucketName, final String fileName, final Date expires)
        throws AmazonClientException, AmazonServiceException {
    LOGGER.info("generateObjectURL invoked, bucketName: {}, fileName: {} and expires: {}", bucketName, fileName,
            expires);//from w  ww . j a v  a 2 s.  co  m
    final GeneratePresignedUrlRequest presignedUrlReq = new GeneratePresignedUrlRequest(bucketName, fileName);
    presignedUrlReq.setExpiration(expires);
    return s3client.generatePresignedUrl(presignedUrlReq);
}

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);/*w  w  w . j  a  v a 2 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.jeet.s3.AmazonS3ClientWrapper.java

License:Open Source License

public String generatePresignedURLForContent(String key) {
    try {/*from   w  ww.j a va  2 s  . c o  m*/
        java.util.Date expiration = new java.util.Date();
        long msec = expiration.getTime();
        msec += 1000 * 60 * 60; // 1 hour.
        expiration.setTime(msec);
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                Constants.BUCKET_NAME, key);
        generatePresignedUrlRequest.setMethod(HttpMethod.GET); // Default.
        generatePresignedUrlRequest.setExpiration(expiration);

        URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
        return s.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";

}

From source file:com.jeet.s3.AmazonS3ClientWrapper.java

License:Open Source License

public String generatePresignedURL(String key) {
    try {//from   w w  w  .jav  a  2 s  . co  m
        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(
                Constants.BUCKET_NAME, key);
        generatePresignedUrlRequest.setMethod(HttpMethod.GET); // Default.
        URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
        return s.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

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 w  w w . j a v a  2s .  c  o  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.mycompany.mytubeaws.DownloadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w  ww . java 2s  . com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String result = "";
    String downloadLink = "";

    String inputKey = request.getParameter("downloadKey");

    if (inputKey == null)
        result += "inputKey is null; ";
    else if (inputKey.length() == 0)
        result += "inputKey is blank; ";
    else {
        result += "Downloading an object; ";

        try {
            //            S3Object object = s3.getObject(new GetObjectRequest(bucketName, inputKey));
            //            S3ObjectInputStream objectContent = object.getObjectContent();
            //            
            //            File f = File.createTempFile("aws-java-sdk-download", "");
            //            FileOutputStream fos = new FileOutputStream(f);
            //            IOUtils.copy(objectContent, fos);
            //            fos.close();
            //            
            //            result += "Content-Type: '" + object.getObjectMetadata().getContentType() + "'; ";
            //            result += "Mime '" + new MimetypesFileTypeMap().getContentType(f) + "'; ";
            //            
            //            response.setContentType(new MimetypesFileTypeMap().getContentType(f));
            //            response.setHeader("Content-Disposition","attachment;filename="+inputKey);
            //            
            //            ServletOutputStream out = response.getOutputStream();
            //            
            //            
            //            f.delete();

            GeneratePresignedUrlRequest requestUrl = new GeneratePresignedUrlRequest(bucketName, inputKey);
            downloadLink = s3.generatePresignedUrl(requestUrl).toString();
            System.out.println(downloadLink);
            //result += downloadLink + " ; ";
        } 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());

            result += "AmazonServiceException thrown; ";
        } 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());

            result += "AmazonClientException thrown; ";
        }
    }

    System.out.println(result);

    request.setAttribute("resultText", result);
    request.setAttribute("downloadLink", downloadLink);
    request.getRequestDispatcher("/DownloadResult.jsp").forward(request, response);
    //response.sendRedirect("UploadResult.jsp");
}

From source file:com.zhang.aws.s3.S3Sample.java

License:Open Source License

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

    /*/*from   ww w. j av  a2 s  .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:edu.upenn.library.fcrepo.connector.annex.S3AnnexResolverFactory.java

License:Apache License

public URI getObjectURI(String annexId, Map<String, String> remoteResponseHeaderHints) {
    GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucket, annexId);
    request.addRequestParameter(ResponseHeaderOverrides.RESPONSE_HEADER_CONTENT_TYPE,
            remoteResponseHeaderHints.get(Headers.CONTENT_TYPE));
    request.addRequestParameter(ResponseHeaderOverrides.RESPONSE_HEADER_CONTENT_DISPOSITION,
            remoteResponseHeaderHints.get(Headers.CONTENT_DISPOSITION));
    try {/*from   w w  w .  j av  a2  s . com*/
        return conn.generatePresignedUrl(request).toURI();
    } catch (URISyntaxException ex) {
        throw null;
    }
}