Oct 24, 2013

AWS SDK for Java - Tutorial 5 : CloudFront


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
continue reading AWS SDK for Java - Tutorial 5 : CloudFront

AWS SDK for Java - Tutorial 4 : S3

Introduction
Amazon S3 provides a simple web services interface that can be used to store and retrieve any amount of data, at any time, from anywhere on the web. It gives any developer access to the same highly scalable, reliable, secure, fast, inexpensive infrastructure that Amazon uses to run its own global network of web sites. The service aims to maximize benefits of scale and to pass those benefits on to developers.

Useful Classe
AmazonS3Client

Source Code
Step 1: Variables requires to create S3 bucket
 // S3 
 private String BucketName = "aws-tutorials";
 private String BucketPolicy ="{"Version": "2008-10-17","Statement": [{"Sid": "AddPerm","Effect": "Allow","Principal": {"AWS": "*"},"Action": "s3:GetObject","Resource": "arn:aws:s3:::aws-tutorials/*"}]}";



Step 2: Create s3 bucket with policy
public void createS3(){

  try {
   AmazonS3Client s3 = new AmazonS3Client(credentials);
   s3.setEndpoint(endPoint);
   s3.setRegion(region);
   log.Info("Creating Bucket :" + BucketName);
   
   s3.createBucket(BucketName);
   log.Info("Policy :" + BucketPolicy);
   s3.setBucketPolicy(BucketName, BucketPolicy);
   
  } catch (Exception e) {
   e.printStackTrace();
   System.exit(0);
  }
 }


Screenshots


Click here to download full source

continue reading AWS SDK for Java - Tutorial 4 : S3

Oct 2, 2013

AWS SDK for Java - Tutorial 3 : RDS



Introduction
Amazon Relational Database Service (Amazon RDS) is a web service that makes it easier to set up, operate, and scale a relational database in the cloud. It provides cost-efficient, resizable capacity for an industry-standard relational database and manages common database administration tasks.

RDS provides two type of instances 1. On Demand 2. Reserved, We can choose DB Instance type as per requirement, RDS offers micro db instance to the high memory db clusters. We can create MySQL, Oracle or MSSQL server under the RDS services.

I suggest to visit previous articles
1. AWS SDK for Java - Tutorial 1 : Introduction
2. AWS SDK for Java - Tutorial 2 : EC2


Classes used to create RDS instance

AmazonRDSClient
CreateDBParameterGroupRequest
ModifyDBParameterGroupRequest
CreateDBInstanceRequest
DBInstance
DescribeDBInstancesRequest
DescribeDBInstancesResult

Step1: Define variable requires to create RDS mysql instance, you need to change OwnerId to execute this code
 private AmazonRDSClient rdsclient;
 //RDS - MySql instance
 private String rdsengine = "MySQL";
 private String EngineVersion = "5.5.31";
 private String LicenseModel = "general-public-license";
 private boolean AutoMinorVersionUpgrade = true;
 private String DBInstanceClass ="db.t1.micro";
 private boolean MultiAZ =false;
 private int AllocatedStorage = 25;
 
 private String DBInstanceIdentifier = "kpbirdrdsmysql";
 private String MasterUsername = "kpbird_user";
 private String MasterUserPassword = "kpbird_pass";
 private String DBName = "kpbirddb";
 private int Port = 3306;
 private int BackupRetentionPeriod =1;
 private boolean PubliclyAccessible = true;
 
 // db security group parameters
 private String DBSecurityGroupName = "kpbirddbsecuritygroup";
 private String DBSsecurityGroupDescription = "this is db security group description";
 private String OwnerId = "YOUR OWNER ID";
 
 // db parameter group 
 private String DBParameterGroupName = "kpbirdrdsparametergroup";
 private String DBParameterGroupDescription = "this is db parameter group description";
 private String DBParameterGroupFamily = "mysql5.5";
 
 private String DBParameterName1 = "max_connections";
 private String DBParameterValue1 = "200";
 private String DBParameterApplyMethod1 = "immediate";
 
 private String DBParameterName2 = "max_allowed_packet";
 private String DBParameterValue2 = "33552384";
 private String DBParameterApplyMethod2 = "immediate";

Step 1: Add following code in init method
...
// RDSClient object
rdsclient = new AmazonRDSClient(credentials);
rdsclient.setRegion(region);
rdsclient.setEndpoint(endPoint);
...


Step 2: Create DB Security Group
public void createRDSSecurityGroup(){
try {
 
 log.Info("About to Launch RDS");
 
 CreateDBSecurityGroupRequest d = new CreateDBSecurityGroupRequest();
 d.setDBSecurityGroupName(DBSecurityGroupName);
 d.setDBSecurityGroupDescription(DBSsecurityGroupDescription);
 rdsclient.createDBSecurityGroup(d);
 
 
 AuthorizeDBSecurityGroupIngressRequest auth = new AuthorizeDBSecurityGroupIngressRequest();
 auth.setDBSecurityGroupName(DBSecurityGroupName);
 auth.setEC2SecurityGroupName(groupName);
 auth.setEC2SecurityGroupOwnerId(OwnerId);
 
 
 DBSecurityGroup dbsecuritygroup= rdsclient.authorizeDBSecurityGroupIngress(auth);
 
 } catch (Exception e) {
  e.printStackTrace();
  System.exit(0);
 }
}

Step 3: Create DB Instance
public void createRDS(){
try {
 log.Info("About to Launch RDS");
  
  
 log.Info("Createing DB Parameger Group");
 
 CreateDBParameterGroupRequest cdpgr = new CreateDBParameterGroupRequest();
 cdpgr.setDBParameterGroupName(DBParameterGroupName);
 cdpgr.setDescription(DBParameterGroupDescription);
 cdpgr.setDBParameterGroupFamily(DBParameterGroupFamily);
 rdsclient.createDBParameterGroup(cdpgr);
 
 
 Collection<Parameter> parameters = new ArrayList<Parameter>();
 parameters.add( new Parameter()
            .withParameterName(DBParameterName1)
            .withParameterValue(DBParameterValue1)
            .withApplyMethod(DBParameterApplyMethod1));
 parameters.add( new Parameter()
            .withParameterName(DBParameterName2)
            .withParameterValue(DBParameterValue2)
            .withApplyMethod(DBParameterApplyMethod2));


 rdsclient.modifyDBParameterGroup( new ModifyDBParameterGroupRequest().withDBParameterGroupName(DBParameterGroupName).withParameters(parameters));


 log.Info("Create DB Instance Request");
 /// create configuration of instance
 CreateDBInstanceRequest cdbir = new CreateDBInstanceRequest();
 cdbir.setEngine(rdsengine);
 cdbir.setEngineVersion(EngineVersion);
 cdbir.setLicenseModel(LicenseModel);
 cdbir.setAutoMinorVersionUpgrade(AutoMinorVersionUpgrade);
 cdbir.setDBInstanceClass(DBInstanceClass);
 cdbir.setMultiAZ(MultiAZ);
 cdbir.setAllocatedStorage(AllocatedStorage);
 cdbir.setDBInstanceIdentifier(DBInstanceIdentifier);
 cdbir.setMasterUsername(MasterUsername);
 cdbir.setMasterUserPassword(MasterUserPassword);
 cdbir.setDBName(DBName);
 cdbir.setPort(Port);
 cdbir.setBackupRetentionPeriod(BackupRetentionPeriod);
 cdbir.setPubliclyAccessible(PubliclyAccessible);
 cdbir.setDBParameterGroupName(DBParameterGroupName);
 ArrayList<String> arrDbSecur = new ArrayList<String>();
 arrDbSecur.add(DBSecurityGroupName);
 cdbir.setDBSecurityGroups(arrDbSecur);
  
 log.Info("Creating RDS DB Instance");
 // creating instance
 DBInstance dbi=  rdsclient.createDBInstance(cdbir);
 
 // wait till instance created
 boolean isWaiting = true;
 while(isWaiting){
  Thread.sleep(5000);
  DescribeDBInstancesRequest request = new DescribeDBInstancesRequest();
  request.setDBInstanceIdentifier(dbi.getDBInstanceIdentifier());
  DescribeDBInstancesResult result = rdsclient.describeDBInstances(request);
  List<DBInstance> d= result.getDBInstances();
  Iterator<DBInstance> i = d.iterator();
  
  while(i.hasNext()){
   DBInstance d1 = i.next();
   log.Info("RDS Status : " + d1.getDBInstanceStatus());
   if(d1.getDBInstanceStatus().equals("available")){
    isWaiting = false;
    log.Info("RDS Endpoint : " + d1.getEndpoint().getAddress());
   }
  }
 }
 } catch (Exception e) {
  e.printStackTrace();
  System.exit(0);
 }
}

Screen Shots
DB Security Group

DB Parameter Group

RDS Instance

Click here to download full source

continue reading AWS SDK for Java - Tutorial 3 : RDS