Example usage for com.amazonaws.services.s3.model ObjectMetadata setCacheControl

List of usage examples for com.amazonaws.services.s3.model ObjectMetadata setCacheControl

Introduction

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

Prototype

public void setCacheControl(String cacheControl) 

Source Link

Document

<p> Sets the optional Cache-Control HTTP header which allows the user to specify caching behavior along the HTTP request/reply chain.

Usage

From source file:localdomain.localhost.ProductImageUploadServlet.java

License:Apache License

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from  w w w .j a  v  a 2s . co m
        String itemName = request.getParameter("productName");
        String credits = request.getParameter("imageCredits");

        InputStream is = request.getPart("imageFile").getInputStream();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(request.getPart("imageFile").getSize());
        objectMetadata.setContentType(request.getPart("imageFile").getContentType());
        objectMetadata.setCacheControl("public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS));

        String imageName = getFileNameFromHeader(request.getPart("imageFile").getHeader("content-disposition"));

        ServletContext context = request.getSession().getServletContext();
        AmazonS3Resources s3Resources = (AmazonS3Resources) context
                .getAttribute(AmazonS3Resources.class.getName());

        String imageUrl = s3Resources.uploadImage(is, objectMetadata, imageName);

        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();
        em.persist(new Product(itemName, imageUrl, credits));
        em.getTransaction().commit();

        response.sendRedirect(request.getContextPath() + "/product/list");
    } catch (Exception e) {
        request.setAttribute("throwable", e);
        request.getRequestDispatcher("/WEB-INF/jsp/products.jsp").forward(request, response);
    }

}

From source file:org.apache.camel.component.aws.s3.S3Producer.java

License:Apache License

@Override
public void process(final Exchange exchange) throws Exception {
    ObjectMetadata objectMetadata = new ObjectMetadata();

    Long contentLength = exchange.getIn().getHeader(S3Constants.CONTENT_LENGTH, Long.class);
    if (contentLength != null) {
        objectMetadata.setContentLength(contentLength);
    }//from   w  ww .  j  a  v  a 2s .  co m

    String contentType = exchange.getIn().getHeader(S3Constants.CONTENT_TYPE, String.class);
    if (contentType != null) {
        objectMetadata.setContentType(contentType);
    }

    String cacheControl = exchange.getIn().getHeader(S3Constants.CACHE_CONTROL, String.class);
    if (cacheControl != null) {
        objectMetadata.setCacheControl(cacheControl);
    }

    String contentDisposition = exchange.getIn().getHeader(S3Constants.CONTENT_DISPOSITION, String.class);
    if (contentDisposition != null) {
        objectMetadata.setContentDisposition(contentDisposition);
    }

    String contentEncoding = exchange.getIn().getHeader(S3Constants.CONTENT_ENCODING, String.class);
    if (contentEncoding != null) {
        objectMetadata.setContentEncoding(contentEncoding);
    }

    String contentMD5 = exchange.getIn().getHeader(S3Constants.CONTENT_MD5, String.class);
    if (contentMD5 != null) {
        objectMetadata.setContentMD5(contentMD5);
    }

    Date lastModified = exchange.getIn().getHeader(S3Constants.LAST_MODIFIED, Date.class);
    if (lastModified != null) {
        objectMetadata.setLastModified(lastModified);
    }

    Map<String, String> userMetadata = exchange.getIn().getHeader(S3Constants.USER_METADATA, Map.class);
    if (userMetadata != null) {
        objectMetadata.setUserMetadata(userMetadata);
    }

    File filePayload = null;

    Object obj = exchange.getIn().getMandatoryBody();
    if (obj instanceof File) {
        filePayload = (File) obj;
    }
    PutObjectRequest putObjectRequest = new PutObjectRequest(getConfiguration().getBucketName(),
            determineKey(exchange), exchange.getIn().getMandatoryBody(InputStream.class), objectMetadata);

    String storageClass = determineStorageClass(exchange);
    if (storageClass != null) {
        putObjectRequest.setStorageClass(storageClass);
    }

    String cannedAcl = exchange.getIn().getHeader(S3Constants.CANNED_ACL, String.class);
    if (cannedAcl != null) {
        CannedAccessControlList objectAcl = CannedAccessControlList.valueOf(cannedAcl);
        putObjectRequest.setCannedAcl(objectAcl);
    }

    AccessControlList acl = exchange.getIn().getHeader(S3Constants.ACL, AccessControlList.class);
    if (acl != null) {
        // note: if cannedacl and acl are both specified the last one will be used. refer to
        // PutObjectRequest#setAccessControlList for more details
        putObjectRequest.setAccessControlList(acl);
    }
    LOG.trace("Put object [{}] from exchange [{}]...", putObjectRequest, exchange);

    PutObjectResult putObjectResult = getEndpoint().getS3Client().putObject(putObjectRequest);

    LOG.trace("Received result [{}]", putObjectResult);

    Message message = getMessageForResponse(exchange);
    message.setHeader(S3Constants.E_TAG, putObjectResult.getETag());
    if (putObjectResult.getVersionId() != null) {
        message.setHeader(S3Constants.VERSION_ID, putObjectResult.getVersionId());
    }

    if (getConfiguration().isDeleteAfterWrite() && filePayload != null) {
        IOHelper.close(putObjectRequest.getInputStream());
        FileUtil.deleteFile(filePayload);
    }
}

From source file:org.apereo.portal.portlets.dynamicskin.storage.s3.AwsS3DynamicSkinService.java

License:Apache License

private void addContentMetadata(final ObjectMetadata metadata, final String content) {
    metadata.setContentMD5(this.calculateBase64EncodedMd5Digest(content));
    metadata.setContentLength(content.length());
    metadata.setContentType("text/css");
    final String cacheControl = this.awsS3BucketConfig.getObjectCacheControl();
    if (StringUtils.isNotEmpty(cacheControl)) {
        metadata.setCacheControl(cacheControl);
    }/* w  w w. j a v a 2  s  .  com*/
}

From source file:org.apereo.portal.portlets.dynamicskin.storage.s3.AwsS3DynamicSkinService.java

License:Apache License

private void addPortletPreferenceMetadata(final ObjectMetadata metadata,
        final PortletPreferences portletPreferences) {
    final String contentCacheControl = portletPreferences.getValue(CONTENT_CACHE_CONTROL_PORTLET_PREF_NAME,
            null);//from ww  w .  j a v a2  s.com
    if (contentCacheControl != null) {
        metadata.setCacheControl(contentCacheControl);
    }
}

From source file:squash.booking.lambdas.core.PageManager.java

License:Apache License

private void copyJsonDataToS3(String keyName, String jsonToCopy) throws Exception {

    logger.log("About to copy cached json data to S3");

    try {/*from  w  ww .  j a va  2s.c  o  m*/
        logger.log("Uploading json data to S3 bucket: " + websiteBucketName + " and key: " + keyName + ".json");
        byte[] jsonAsBytes = jsonToCopy.getBytes(StandardCharsets.UTF_8);
        ByteArrayInputStream jsonAsStream = new ByteArrayInputStream(jsonAsBytes);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(jsonAsBytes.length);
        metadata.setContentType("application/json");
        // Direct caches not to satisfy future requests with this data without
        // revalidation.
        if (keyName.contains("famousplayers")) {
            // Famousplayers list is good for a year
            metadata.setCacheControl("max-age=31536000");
        } else {
            metadata.setCacheControl("no-cache, must-revalidate");
        }
        PutObjectRequest putObjectRequest = new PutObjectRequest(websiteBucketName, keyName + ".json",
                jsonAsStream, metadata);
        // Data must be public so it can be served from the website
        putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
        IS3TransferManager transferManager = getS3TransferManager();
        TransferUtils.waitForS3Transfer(transferManager.upload(putObjectRequest), logger);
        logger.log("Uploaded cached json data to S3 bucket");
    } catch (AmazonServiceException ase) {
        ExceptionUtils.logAmazonServiceException(ase, logger);
        throw new Exception("Exception caught while copying json data to S3");
    } catch (AmazonClientException ace) {
        ExceptionUtils.logAmazonClientException(ace, logger);
        throw new Exception("Exception caught while copying json data to S3");
    } catch (InterruptedException e) {
        logger.log("Caught interrupted exception: ");
        logger.log("Error Message: " + e.getMessage());
        throw new Exception("Exception caught while copying json data to S3");
    }
}

From source file:squash.booking.lambdas.core.PageManager.java

License:Apache License

private void copyUpdatedBookingPageToS3(String pageBaseName, String page, String uidSuffix, boolean usePrefix)
        throws Exception {

    logger.log("About to copy booking page to S3");

    String pageBaseNameWithPrefix = usePrefix ? "NoScript/" + pageBaseName : pageBaseName;
    try {//from ww w. j av  a 2 s .  c om
        logger.log("Uploading booking page to S3 bucket: " + websiteBucketName + "s3websitebucketname"
                + " and key: " + pageBaseNameWithPrefix + uidSuffix + ".html");
        byte[] pageAsGzippedBytes = FileUtils.gzip(page.getBytes(StandardCharsets.UTF_8), logger);

        ByteArrayInputStream pageAsStream = new ByteArrayInputStream(pageAsGzippedBytes);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(pageAsGzippedBytes.length);
        metadata.setContentEncoding("gzip");
        metadata.setContentType("text/html");
        // Direct caches not to satisfy future requests with this data without
        // revalidation.
        metadata.setCacheControl("no-cache, must-revalidate");
        PutObjectRequest putObjectRequest = new PutObjectRequest(websiteBucketName,
                pageBaseNameWithPrefix + uidSuffix + ".html", pageAsStream, metadata);
        // Page must be public so it can be served from the website
        putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
        IS3TransferManager transferManager = getS3TransferManager();
        TransferUtils.waitForS3Transfer(transferManager.upload(putObjectRequest), logger);
        logger.log("Uploaded booking page to S3 bucket");

        if (uidSuffix.equals("")) {
            // Nothing to copy - so return
            logger.log("UidSuffix is empty - so not creating duplicate page");
            return;
        }

        // N.B. We copy from hashed key to non-hashed (and not vice versa)
        // to ensure consistency
        logger.log("Copying booking page in S3 bucket: " + websiteBucketName + " and key: "
                + pageBaseNameWithPrefix + ".html");
        CopyObjectRequest copyObjectRequest = new CopyObjectRequest(websiteBucketName,
                pageBaseNameWithPrefix + uidSuffix + ".html", websiteBucketName,
                pageBaseNameWithPrefix + ".html");
        copyObjectRequest.setCannedAccessControlList(CannedAccessControlList.PublicRead);
        // N.B. Copied object will get same metadata as the source (e.g. the
        // cache-control header etc.)
        TransferUtils.waitForS3Transfer(transferManager.copy(copyObjectRequest), logger);
        logger.log("Copied booking page successfully in S3");
    } catch (AmazonServiceException ase) {
        ExceptionUtils.logAmazonServiceException(ase, logger);
        throw new Exception("Exception caught while copying booking page to S3");
    } catch (AmazonClientException ace) {
        ExceptionUtils.logAmazonClientException(ace, logger);
        throw new Exception("Exception caught while copying booking page to S3");
    } catch (InterruptedException e) {
        logger.log("Caught interrupted exception: ");
        logger.log("Error Message: " + e.getMessage());
        throw new Exception("Exception caught while copying booking page to S3");
    }
}

From source file:squash.deployment.lambdas.utils.TransferUtils.java

License:Apache License

/**
 * Adds cache-control header to S3 objects.
 * //from   ww  w .j  a  va  2s .c o  m
 * <p>Adds cache-control header to S3 objects. All objects
 *    beneath the specified prefix (i.e. folder), and with the
 *    specified extension will have the header added. When the
 *    bucket serves objects it will then add a suitable
 *    Cache-Control header.
 *
 *    @param headerValue value of the cache-control header
 *    @param bucketName the bucket to apply the header to.
 *    @param prefix prefix within the bucket, beneath which to apply the header.
 *    @param extension file extension to apply header to
 *    @param logger a CloudwatchLogs logger.
 */
public static void addCacheControlHeader(String headerValue, String bucketName, Optional<String> prefix,
        String extension, LambdaLogger logger) {

    // To add new metadata, we must copy each object to itself.
    ListObjectsRequest listObjectsRequest;
    if (prefix.isPresent()) {
        logger.log("Setting cache-control metadata: " + headerValue + ", on bucket: " + bucketName
                + " and prefix: " + prefix.get() + " and extension: " + extension);
        listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName).withPrefix(prefix.get());
    } else {
        logger.log("Setting cache-control metadata: " + headerValue + ", on bucket: " + bucketName
                + " and extension: " + extension);
        listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName);
    }

    ObjectListing objectListing;
    AmazonS3 client = TransferManagerBuilder.defaultTransferManager().getAmazonS3Client();
    do {
        objectListing = client.listObjects(listObjectsRequest);
        for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            String key = objectSummary.getKey();
            if (!key.endsWith(extension)) {
                continue;
            }
            logger.log("Setting metadata for S3 object: " + key);
            // We must specify ALL metadata - not just the one we're adding.
            ObjectMetadata objectMetadata = client.getObjectMetadata(bucketName, key);
            objectMetadata.setCacheControl(headerValue);
            CopyObjectRequest copyObjectRequest = new CopyObjectRequest(bucketName, key, bucketName, key)
                    .withNewObjectMetadata(objectMetadata)
                    .withCannedAccessControlList(CannedAccessControlList.PublicRead);
            client.copyObject(copyObjectRequest);
            logger.log("Set metadata for S3 object: " + key);
        }
        listObjectsRequest.setMarker(objectListing.getNextMarker());
    } while (objectListing.isTruncated());
    logger.log("Set cache-control metadata on bucket");
}