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

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

Introduction

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

Prototype

public void setMethod(HttpMethod method) 

Source Link

Document

Sets the HTTP method (GET, PUT, DELETE, HEAD) to be used in this request.

Usage

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();
    }/*  w  ww.jav  a  2 s .com*/

    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:io.stallion.services.S3StorageService.java

License:Open Source License

public String getSignedDownloadUrl(String bucket, String fileKey) {
    GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucket, fileKey);
    req.setExpiration(Date.from(utcNow().plusMinutes(60).toInstant()));
    req.setMethod(HttpMethod.GET);
    return client.generatePresignedUrl(req).toString();
}

From source file:io.stallion.services.S3StorageService.java

License:Open Source License

public String getSignedUploadUrl(String bucket, String fileKey, String contentType, Map headers) {
    GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucket, fileKey);
    if (!empty(contentType)) {
        req.setContentType(contentType);
    }//from   w ww.j av  a2  s .  c om
    if (headers != null) {
        for (Object key : headers.keySet())
            req.addRequestParameter(key.toString(), headers.get(key).toString());
    }
    req.setExpiration(Date.from(utcNow().plusDays(2).toInstant()));
    req.setMethod(HttpMethod.PUT);
    return client.generatePresignedUrl(req).toString();
}

From source file:org.apache.flink.cloudsort.io.aws.AwsCurlInput.java

License:Apache License

@Override
public void open(String objectName) throws IOException {
    Preconditions.checkNotNull(bucket);/* w ww . j av  a  2  s  .  c om*/

    AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider());

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

    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucket,
            objectName);
    generatePresignedUrlRequest.setMethod(HttpMethod.GET);
    generatePresignedUrlRequest.setContentType(CONTENT_TYPE);
    generatePresignedUrlRequest.setExpiration(expiration);

    String url = s3Client.generatePresignedUrl(generatePresignedUrlRequest).toExternalForm();

    downloader = new ProcessBuilder("curl", "-s", "-X", "GET", "-H", "Content-Type: " + CONTENT_TYPE, url)
            .redirectError(Redirect.INHERIT).start();
}

From source file:org.apache.flink.cloudsort.io.aws.AwsCurlOutput.java

License:Apache License

@Override
public Process open(String filename, String taskId) throws IOException {
    Preconditions.checkNotNull(bucket);/*from   w  w  w .j a v  a2s.  c o  m*/
    Preconditions.checkNotNull(prefix);
    Preconditions.checkNotNull(filename);
    Preconditions.checkNotNull(taskId);

    String objectName = prefix + taskId;

    AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider());

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

    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucket,
            objectName);
    generatePresignedUrlRequest.setMethod(HttpMethod.PUT);
    generatePresignedUrlRequest.setContentType(CONTENT_TYPE);
    generatePresignedUrlRequest.setExpiration(expiration);

    String url = s3Client.generatePresignedUrl(generatePresignedUrlRequest).toExternalForm();

    return new ProcessBuilder("curl", "-s", "--max-time", "60", "--retry", "1024", "-X", "PUT", "-H",
            "Content-Type: " + CONTENT_TYPE, "--data-binary", "@" + filename, url)
                    .redirectError(Redirect.INHERIT).redirectOutput(Redirect.INHERIT).start();
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.AmazonS3Uploader.java

License:Open Source License

/**
 * Returns a pre-signed URL for accessing an Amazon S3 resource.
 * //from  w ww . j av a2 s.com
 * @param bucketName
 *            The bucket where the resource lies.
 * @param objectKey
 *            The key object.
 * @return A pre-signed URL for accessing an Amazon S3 resource.
 */
public String generatePresignedURL(final String bucketName, final String objectKey) {
    final Date expiration = new Date();
    expiration.setTime(System.currentTimeMillis() + ONE_DAY_IN_MILLIS);

    final GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName,
            objectKey);
    generatePresignedUrlRequest.setMethod(HttpMethod.GET); // Default.
    generatePresignedUrlRequest.setExpiration(expiration);

    URL generatePresignedObjectURL = s3client.generatePresignedUrl(generatePresignedUrlRequest);

    if (logger.isLoggable(Level.FINEST)) {
        logger.finest("Zip uploaded. Limited signed URL: " + generatePresignedObjectURL);
    }
    return generatePresignedObjectURL.toString();
}

From source file:org.mobicents.servlet.restcomm.amazonS3.S3AccessTool.java

License:Open Source License

public URI uploadFile(final String fileToUpload) {
    AWSCredentials credentials = new BasicAWSCredentials(accessKey, securityKey);
    AmazonS3 s3client = new AmazonS3Client(credentials);
    try {/*  ww  w.  ja v  a  2s.  c om*/
        StringBuffer bucket = new StringBuffer();
        bucket.append(bucketName);
        if (folder != null && !folder.isEmpty())
            bucket.append("/").append(folder);
        URI fileUri = URI.create(fileToUpload);
        logger.info("File to upload to S3: " + fileUri.toString());
        File file = new File(fileUri);
        //            while (!file.exists()){}
        //            logger.info("File exist: "+file.exists());
        //First generate the Presigned URL, buy some time for the file to be written on the disk
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        if (daysToRetainPublicUrl > 0) {
            cal.add(Calendar.DATE, daysToRetainPublicUrl);
        } else {
            //By default the Public URL will be valid for 180 days
            cal.add(Calendar.DATE, 180);
        }
        date = cal.getTime();
        GeneratePresignedUrlRequest generatePresignedUrlRequestGET = new GeneratePresignedUrlRequest(
                bucket.toString(), file.getName());
        generatePresignedUrlRequestGET.setMethod(HttpMethod.GET);
        generatePresignedUrlRequestGET.setExpiration(date);

        URL downloadUrl = s3client.generatePresignedUrl(generatePresignedUrlRequestGET);

        //Second upload the file to S3
        //            while (!file.exists()){}
        while (!FileUtils.waitFor(file, 30)) {
        }
        if (file.exists()) {
            PutObjectRequest putRequest = new PutObjectRequest(bucket.toString(), file.getName(), file);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(new MimetypesFileTypeMap().getContentType(file));
            putRequest.setMetadata(metadata);
            if (reducedRedundancy)
                putRequest.setStorageClass(StorageClass.ReducedRedundancy);
            s3client.putObject(putRequest);

            if (removeOriginalFile) {
                removeLocalFile(file);
            }
            return downloadUrl.toURI();
        } else {
            logger.error("Timeout waiting for the recording file: " + file.getAbsolutePath());
            return null;
        }
    } catch (AmazonServiceException ase) {
        logger.error("Caught an AmazonServiceException");
        logger.error("Error Message:    " + ase.getMessage());
        logger.error("HTTP Status Code: " + ase.getStatusCode());
        logger.error("AWS Error Code:   " + ase.getErrorCode());
        logger.error("Error Type:       " + ase.getErrorType());
        logger.error("Request ID:       " + ase.getRequestId());
        return null;
    } catch (AmazonClientException ace) {
        logger.error("Caught an AmazonClientException, which ");
        logger.error("Error Message: " + ace.getMessage());
        return null;
    } catch (URISyntaxException e) {
        logger.error("URISyntaxException: " + e.getMessage());
        return null;
    }
}

From source file:org.restcomm.connect.commons.amazonS3.S3AccessTool.java

License:Open Source License

public URI getPublicUrl(String fileName) throws URISyntaxException {
    if (s3client == null) {
        s3client = getS3client();//from   w w w .  ja  va  2  s  .c  om
    }
    Date date = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.MINUTE, minutesToRetainPublicUrl);
    if (logger.isInfoEnabled()) {
        final String msg = String.format("Prepared amazon s3 public url valid for %s minutes for recording: %s",
                minutesToRetainPublicUrl, fileName);
        logger.info(msg);
    }
    date = cal.getTime();
    String bucket = bucketName;
    if (folder != null && !folder.isEmpty()) {
        bucket = bucket.concat("/").concat(folder);
    }
    GeneratePresignedUrlRequest generatePresignedUrlRequestGET = new GeneratePresignedUrlRequest(bucket,
            fileName);
    generatePresignedUrlRequestGET.setMethod(HttpMethod.GET);
    generatePresignedUrlRequestGET.setExpiration(date);

    return s3client.generatePresignedUrl(generatePresignedUrlRequestGET).toURI();
}

From source file:servlet.FileUploadServlet.java

private void putInBucket(String fileName, String id) throws IOException {

    AWSCredentials awsCreds = new PropertiesCredentials(
            new File("/Users/paulamontojo/Desktop/AwsCredentials.properties"));
    AmazonS3 s3client = new AmazonS3Client(awsCreds);

    try {/*w  w w  . j  a  v  a 2 s .c om*/
        System.out.println("Uploading a new object to S3 from a file\n");
        File file = new File(uploadFileName);
        s3client.putObject(new PutObjectRequest(bucketName, fileName, file));

        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName,
                fileName);
        generatePresignedUrlRequest.setMethod(HttpMethod.GET); // Default.

        URL s = s3client.generatePresignedUrl(generatePresignedUrlRequest);
        insertUrl(s.toString(), id);
        System.out.println(s);

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

}