Oct 24, 2013

AWS SDK for Java - Tutorial 5 : CloudFront

Standard

Introduction

Amazon CloudFront is a web service for content delivery. It integrates with other Amazon Web Services to give developers and businesses an easy way to distribute content to end users with low latency, high data transfer speeds, and no commitments.

Classes


Source Code

Step 1: Variables
// Cloud Front 
    private String cloudFrontDesc = "this is description";
    private String cloudFrontS3Origin= "aws-tutorials";
    private long cloudFrontMinTTL=36000;

Step 2: Create CloudFront with S3 bucket as origin
public void createCloudFront(){
  try {
    log.Info("Create CloudFront Distribution For Download");
    AmazonCloudFrontClient cloudfront = new AmazonCloudFrontClient(credentials);
    cloudfront.setEndpoint(endPoint);
    cloudfront.setRegion(region);

    DistributionConfig dc = new DistributionConfig();
    dc.withCallerReference(System.currentTimeMillis() + "");
    dc.withAliases(new Aliases().withQuantity(0));
    dc.withDefaultRootObject("");
    dc.withOrigins(new Origins().withItems(
      new Origin().withId(cloudFrontS3Origin).withDomainName(cloudFrontS3Origin+ ".s3.amazonaws.com").withS3OriginConfig(new S3OriginConfig().withOriginAccessIdentity("")))
      .withQuantity(1));
    dc.withDefaultCacheBehavior(new DefaultCacheBehavior()
      .withTargetOriginId(cloudFrontS3Origin)
      .withForwardedValues(new ForwardedValues().withQueryString(false).withCookies(new CookiePreference().withForward("none")))
      .withTrustedSigners(new TrustedSigners().withQuantity(0).withEnabled(false))
      .withViewerProtocolPolicy(ViewerProtocolPolicy.AllowAll)
      .withMinTTL(cloudFrontMinTTL));
    dc.withCacheBehaviors(new CacheBehaviors().withQuantity(0));
    dc.withComment(cloudFrontDesc);
    dc.withLogging(new LoggingConfig().withEnabled(false).withBucket("").withPrefix("").withIncludeCookies(false));
    dc.withEnabled(true);
    dc.withPriceClass(PriceClass.PriceClass_All);

    CreateDistributionRequest cdr = new CreateDistributionRequest().withDistributionConfig(dc);

    CreateDistributionResult distribution = cloudfront.createDistribution(cdr);

    boolean isWait = true;
    while (isWait) {
     Thread.sleep(5000);
     GetDistributionResult gdr = cloudfront.getDistribution(new GetDistributionRequest(distribution.getDistribution().getId()));
     String status = gdr.getDistribution().getStatus();
     log.Info("Status :" + status);
     if (status.equals("Deployed")) {
      isWait = false;
      log.Info("Domain Name :" + gdr.getDistribution().getDomainName());
     }
    }

   

  } catch (Exception e) {
   e.printStackTrace();
   System.exit(0);
  }
 }


Screen Shots

Source Code

1 comment:

  1. Seth Williams1:38 PM

    Hey Ketan, Thanks for sharing this tutorial on AWS SDK for Java. We have more advanced Java tutorials at http://www.fireboxtraining.com/java

    ReplyDelete