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: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  ww  .  j av  a 2 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: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:awslabs.lab51.SolutionCode.java

License:Open Source License

@Override
public String getUrlForItem(AmazonS3Client s3Client, String key, String bucket) {
    Date nowPlusTwoMinutes = new Date(System.currentTimeMillis() + 120000L);

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

    // 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:br.org.fiscal65.amazonaws.AWSPictureUpload.java

License:Open Source License

public AWSPictureUpload(Context context, OnPictureUploadS3PostExecuteListener uploadListener,
        String picturePath, String slugFiscalizacao, String zonaFiscalizacao, Long idFiscalizacao,
        Integer posicaoFoto, Integer podeEnviarRedeDados, Integer sleep) {
    super(context);

    this.uploadListener = uploadListener;

    this.picturePath = picturePath;

    this.slugFiscalizacao = slugFiscalizacao;

    this.zonaFiscalizacao = zonaFiscalizacao;

    this.idFiscalizacao = idFiscalizacao;

    this.posicaoFoto = posicaoFoto;

    this.podeEnviarRedeDados = podeEnviarRedeDados;

    this.sleep = sleep;

    mStatus = Status.IN_PROGRESS;/*from w w w. j  av a 2  s. co  m*/

    progressListener = new ProgressListener() {
        @Override
        public void progressChanged(ProgressEvent event) {
            if (event.getEventCode() == ProgressEvent.COMPLETED_EVENT_CODE) {
                boolean hasInternet = CommunicationUtils.verifyConnectivity(getContext());

                if (hasInternet) {
                    boolean isOnWiFi = CommunicationUtils.isWifi(getContext());

                    if (isOnWiFi || (AWSPictureUpload.this.podeEnviarRedeDados != null
                            && AWSPictureUpload.this.podeEnviarRedeDados.equals(1))) {
                        try {
                            ResponseHeaderOverrides override = new ResponseHeaderOverrides();
                            override.setContentType("image/jpeg");

                            GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(
                                    CommunicationConstants.PICTURE_BUCKET_NAME,
                                    AWSUtil.getPrefix(getContext()) + AWSPictureUpload.this.slugFiscalizacao
                                            + "/zona-" + AWSPictureUpload.this.zonaFiscalizacao + "/"
                                            + pictureName);
                            urlRequest.setResponseHeaders(override);

                            URL urlDaFoto = AWSUtil.getS3Client(getContext()).generatePresignedUrl(urlRequest);

                            if (urlDaFoto != null) {
                                String string = urlDaFoto.toString();
                                String[] parts = string.split("\\?");
                                String url = parts[0];

                                S3UploadPictureResult result = new S3UploadPictureResult();
                                result.setUrlDaFoto(url);
                                result.setPosicaoFoto(AWSPictureUpload.this.posicaoFoto);
                                result.setIdFiscalizacao(AWSPictureUpload.this.idFiscalizacao);
                                result.setSlugFiscalizacao(AWSPictureUpload.this.slugFiscalizacao);
                                result.setZonaFiscalizacao(AWSPictureUpload.this.zonaFiscalizacao);

                                mStatus = Status.COMPLETED;
                                AWSPictureUpload.this.uploadListener
                                        .finishedPictureUploadS3ComResultado(result);
                            } else {
                                mStatus = Status.CANCELED;

                                if (mUpload != null) {
                                    mUpload.abort();
                                }

                                AWSPictureUpload.this.uploadListener.finishedPictureUploadS3ComError(
                                        AWSPictureUpload.this.slugFiscalizacao,
                                        AWSPictureUpload.this.zonaFiscalizacao,
                                        AWSPictureUpload.this.idFiscalizacao,
                                        AWSPictureUpload.this.posicaoFoto);
                            }
                        } catch (Exception e) {
                            mStatus = Status.CANCELED;

                            if (mUpload != null) {
                                mUpload.abort();
                            }

                            AWSPictureUpload.this.uploadListener.finishedPictureUploadS3ComError(
                                    AWSPictureUpload.this.slugFiscalizacao,
                                    AWSPictureUpload.this.zonaFiscalizacao,
                                    AWSPictureUpload.this.idFiscalizacao, AWSPictureUpload.this.posicaoFoto);
                        }
                    } else {
                        mStatus = Status.CANCELED;

                        if (mUpload != null) {
                            mUpload.abort();
                        }

                        AWSPictureUpload.this.uploadListener.finishedPictureUploadS3ComError(
                                AWSPictureUpload.this.slugFiscalizacao, AWSPictureUpload.this.zonaFiscalizacao,
                                AWSPictureUpload.this.idFiscalizacao, AWSPictureUpload.this.posicaoFoto);
                    }
                } else {
                    mStatus = Status.CANCELED;

                    if (mUpload != null) {
                        mUpload.abort();
                    }

                    AWSPictureUpload.this.uploadListener.finishedPictureUploadS3ComError(
                            AWSPictureUpload.this.slugFiscalizacao, AWSPictureUpload.this.zonaFiscalizacao,
                            AWSPictureUpload.this.idFiscalizacao, AWSPictureUpload.this.posicaoFoto);
                }
            } else if (event.getEventCode() == ProgressEvent.FAILED_EVENT_CODE) {
                mStatus = Status.CANCELED;

                if (mUpload != null) {
                    mUpload.abort();
                }

                AWSPictureUpload.this.uploadListener.finishedPictureUploadS3ComError(
                        AWSPictureUpload.this.slugFiscalizacao, AWSPictureUpload.this.zonaFiscalizacao,
                        AWSPictureUpload.this.idFiscalizacao, AWSPictureUpload.this.posicaoFoto);
            }
        }
    };
}

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 .  java 2 s . co 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.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);
            });/*w  w w . java  2s . c om*/
            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.amazon.photosharing.utils.ContentHelper.java

License:Open Source License

public URL getSignedUrl(String p_s3_bucket, String p_s3_file, Date p_exires) {

    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(p_s3_bucket,
            p_s3_file);/*  w  w w.j a v  a  2 s . c  om*/
    generatePresignedUrlRequest.setMethod(HttpMethod.GET); // Default.
    generatePresignedUrlRequest.setExpiration(p_exires);

    return s3Client.generatePresignedUrl(generatePresignedUrlRequest);
}

From source file:com.amediamanager.service.VideoServiceImpl.java

License:Apache License

@Override
public Video generateExpiringUrl(Video video, long expirationInMillis) {

    Date expiration = new java.util.Date();
    long msec = expiration.getTime();
    msec += expirationInMillis;/*w  w w  . ja  v  a2s .  c  om*/
    expiration.setTime(msec);

    // Expiring URL for original video
    GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(video.getBucket(),
            video.getOriginalKey());
    generatePresignedUrlRequest.setMethod(HttpMethod.GET);
    generatePresignedUrlRequest.setExpiration(expiration);
    video.setExpiringUrl(s3Client.generatePresignedUrl(generatePresignedUrlRequest));

    // Expiring URL for preview video
    if (video.getPreviewKey() != null) {
        generatePresignedUrlRequest = new GeneratePresignedUrlRequest(video.getBucket(), video.getPreviewKey());
        generatePresignedUrlRequest.setMethod(HttpMethod.GET);
        generatePresignedUrlRequest.setExpiration(expiration);
        video.setExpiringPreviewKey(s3Client.generatePresignedUrl(generatePresignedUrlRequest));
    }

    // Expiring URL for original video
    if (video.getThumbnailKey() != null) {
        generatePresignedUrlRequest = new GeneratePresignedUrlRequest(video.getBucket(),
                video.getThumbnailKey());
        generatePresignedUrlRequest.setMethod(HttpMethod.GET);
        generatePresignedUrlRequest.setExpiration(expiration);
        video.setExpiringThumbnailKey(s3Client.generatePresignedUrl(generatePresignedUrlRequest));
    }

    return video;
}

From source file:com.athena.dolly.web.aws.s3.S3Service.java

License:Open Source License

/**
 *  This generates a signed download URL for key(file) that will work for 1 hour.
 * @param bucketName/*  w  w w.  ja  v a  2  s . co m*/
 * @param key
 * @return
 */
public URL presignedUrl(String bucketName, String key) {
    GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, key);
    URL url = s3.generatePresignedUrl(request);
    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 {/* w w  w .  j a v  a2  s . com*/
        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;
}