Example usage for com.amazonaws HttpMethod PUT

List of usage examples for com.amazonaws HttpMethod PUT

Introduction

In this page you can find the example usage for com.amazonaws HttpMethod PUT.

Prototype

HttpMethod PUT

To view the source code for com.amazonaws HttpMethod PUT.

Click Source Link

Usage

From source file:UploadUrlGenerator.java

License:Open Source License

public static void main(String[] args) throws Exception {
    Options opts = new Options();

    opts.addOption(Option.builder().longOpt(ENDPOINT_OPTION).required().hasArg().argName("url")
            .desc("Sets the ECS S3 endpoint to use, e.g. https://ecs.company.com:9021").build());
    opts.addOption(Option.builder().longOpt(ACCESS_KEY_OPTION).required().hasArg().argName("access-key")
            .desc("Sets the Access Key (user) to sign the request").build());
    opts.addOption(Option.builder().longOpt(SECRET_KEY_OPTION).required().hasArg().argName("secret")
            .desc("Sets the secret key to sign the request").build());
    opts.addOption(Option.builder().longOpt(BUCKET_OPTION).required().hasArg().argName("bucket-name")
            .desc("The bucket containing the object").build());
    opts.addOption(Option.builder().longOpt(KEY_OPTION).required().hasArg().argName("object-key")
            .desc("The object name (key) to access with the URL").build());
    opts.addOption(Option.builder().longOpt(EXPIRES_OPTION).hasArg().argName("minutes")
            .desc("Minutes from local time to expire the request.  1 day = 1440, 1 week=10080, "
                    + "1 month (30 days)=43200, 1 year=525600.  Defaults to 1 hour (60).")
            .build());//from w  w  w  .  j a va2  s. c  o m
    opts.addOption(Option.builder().longOpt(VERB_OPTION).hasArg().argName("http-verb").type(HttpMethod.class)
            .desc("The HTTP verb that will be used with the URL (PUT, GET, etc).  Defaults to GET.").build());
    opts.addOption(Option.builder().longOpt(CONTENT_TYPE_OPTION).hasArg().argName("mimetype")
            .desc("Sets the Content-Type header (e.g. image/jpeg) that will be used with the request.  "
                    + "Must match exactly.  Defaults to application/octet-stream for PUT/POST and "
                    + "null for all others")
            .build());

    DefaultParser dp = new DefaultParser();

    CommandLine cmd = null;
    try {
        cmd = dp.parse(opts, args);
    } catch (ParseException e) {
        System.err.println("Error: " + e.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar UploadUrlGenerator-xxx.jar", opts, true);
        System.exit(255);
    }

    URI endpoint = URI.create(cmd.getOptionValue(ENDPOINT_OPTION));
    String accessKey = cmd.getOptionValue(ACCESS_KEY_OPTION);
    String secretKey = cmd.getOptionValue(SECRET_KEY_OPTION);
    String bucket = cmd.getOptionValue(BUCKET_OPTION);
    String key = cmd.getOptionValue(KEY_OPTION);
    HttpMethod method = HttpMethod.GET;
    if (cmd.hasOption(VERB_OPTION)) {
        method = HttpMethod.valueOf(cmd.getOptionValue(VERB_OPTION).toUpperCase());
    }
    int expiresMinutes = 60;
    if (cmd.hasOption(EXPIRES_OPTION)) {
        expiresMinutes = Integer.parseInt(cmd.getOptionValue(EXPIRES_OPTION));
    }
    String contentType = null;
    if (method == HttpMethod.PUT || method == HttpMethod.POST) {
        contentType = "application/octet-stream";
    }

    if (cmd.hasOption(CONTENT_TYPE_OPTION)) {
        contentType = cmd.getOptionValue(CONTENT_TYPE_OPTION);
    }

    BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    ClientConfiguration cc = new ClientConfiguration();
    // Force use of v2 Signer.  ECS does not support v4 signatures yet.
    cc.setSignerOverride("S3SignerType");
    AmazonS3Client s3 = new AmazonS3Client(credentials, cc);
    s3.setEndpoint(endpoint.toString());
    S3ClientOptions s3c = new S3ClientOptions();
    s3c.setPathStyleAccess(true);
    s3.setS3ClientOptions(s3c);

    // Sign the URL
    Calendar c = Calendar.getInstance();
    c.add(Calendar.MINUTE, expiresMinutes);
    GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucket, key).withExpiration(c.getTime())
            .withMethod(method);
    if (contentType != null) {
        req = req.withContentType(contentType);
    }
    URL u = s3.generatePresignedUrl(req);
    System.out.printf("URL: %s\n", u.toURI().toASCIIString());
    System.out.printf("HTTP Verb: %s\n", method);
    System.out.printf("Expires: %s\n", c.getTime());
    System.out.println("To Upload with curl:");

    StringBuilder sb = new StringBuilder();
    sb.append("curl ");

    if (method != HttpMethod.GET) {
        sb.append("-X ");
        sb.append(method.toString());
        sb.append(" ");
    }

    if (contentType != null) {
        sb.append("-H \"Content-Type: ");
        sb.append(contentType);
        sb.append("\" ");
    }

    if (method == HttpMethod.POST || method == HttpMethod.PUT) {
        sb.append("-T <filename> ");
    }

    sb.append("\"");
    sb.append(u.toURI().toASCIIString());
    sb.append("\"");

    System.out.println(sb.toString());

    System.exit(0);
}

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 {// w  ww. j a va 2  s .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: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  w  w.j  av a2 s  .com
    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.AwsCurlOutput.java

License:Apache License

@Override
public Process open(String filename, String taskId) throws IOException {
    Preconditions.checkNotNull(bucket);/*from w w  w.ja  v  a2 s.  co  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.icgc.dcc.storage.server.repository.s3.S3URLGenerator.java

License:Open Source License

@Override
public String getUploadPartUrl(String bucketName, ObjectKey objectKey, String uploadId, Part part,
        Date expiration) {// w w w.  j  ava2 s . c  o  m
    GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectKey.getKey(),
            HttpMethod.PUT);
    req.setExpiration(expiration);

    req.addRequestParameter("partNumber", String.valueOf(part.getPartNumber()));
    req.addRequestParameter("uploadId", uploadId);

    return s3Client.generatePresignedUrl(req).toString();
}

From source file:org.whispersystems.textsecuregcm.controllers.AttachmentController.java

License:Open Source License

@Timed
@GET//  w ww .j a  va2s . com
@Produces(MediaType.APPLICATION_JSON)
public AttachmentDescriptor allocateAttachment(@Auth Account account) throws RateLimitExceededException {
    if (account.isRateLimited()) {
        rateLimiters.getAttachmentLimiter().validate(account.getNumber());
    }

    long attachmentId = generateAttachmentId();
    URL url = urlSigner.getPreSignedUrl(attachmentId, HttpMethod.PUT);

    return new AttachmentDescriptor(attachmentId, url.toExternalForm());

}