Monday, May 5, 2014

[java] Add or Delete CNAME Records with Amazon route 53 API

package com;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class Test {
    private static final String AWS_HOST = "route53.amazonaws.com";
    private static final String SECRECT_ACCESS_KEY = "xxxxxxxxxxxxxxxxxxxx";
    private static final String ACCESS_KEY_ID = "xxxxxxxxxxxxxxxxxxx";
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
    private static final String HOSTED_ZONE_ID = "xxxxxxxxxxxxxxx";

    /**
     * Computes RFC 2104-compliant HMAC signature.
     * * @param data
     * The data to be signed.
     *
     * @param key
     *            The signing key.
     * @return
     *         The Base64-encoded RFC 2104-compliant HMAC signature.
     * @throws java.security.SignatureException
     *             when signature generation fails
     */
    public static String calculateRFC2104HMAC(String stringToSign, String secrectAccessKey) {

        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey =
                                   new SecretKeySpec(secrectAccessKey.getBytes(),
                                                     HMAC_SHA1_ALGORITHM);

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = null;
        try {
            mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            mac.init(signingKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(stringToSign.getBytes());

        // base64-encode the hmac
        return new String(Base64.encodeBase64(rawHmac));

    }

    public static void main(String[] args) {
        String[] domainsAdd =
                              { "1.sample.cloudtest.com", "2.sample.cloudtest.com",
                               "3.sample.cloudtest.com", "4.sample.cloudtest.com",
                               "5.sample.cloudtest.com" };
        String name = "sample_pu.cloudtest.com";

        createResourceRecords(prepareCNAMERecordsReq("CREATE", name, domainsAdd));
        listResourceRecords();

        String[] domainsRemove = { "1.sample.cloudtest.com", "2.sample.cloudtest.com" };
        createResourceRecords(prepareCNAMERecordsReq("DELETE", name, domainsRemove));
        listResourceRecords();
    }

    private static void listResourceRecords() {
        // create a post request to addAPI.
        HttpClient httpclient = new DefaultHttpClient();
        String endPoint =
                          "https://route53.amazonaws.com/2013-04-01/hostedzone/" + HOSTED_ZONE_ID +
                                  "/rrset";
        HttpGet httpGet = new HttpGet(endPoint);
        try {
            authenticateAWS(httpGet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String responseString = null;
        try {
            HttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity, "UTF-8");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(responseString);
    }

    private static void createResourceRecords(String request) {
        // create a post request to addAPI.
        HttpClient httpclient = new DefaultHttpClient();
        String endPoint =
                          "https://route53.amazonaws.com/2013-04-01/hostedzone/" + HOSTED_ZONE_ID +
                                  "/rrset";
        HttpPost httpAction = new HttpPost(endPoint);
        try {
            authenticateAWS(httpAction);

            httpAction.setEntity(new StringEntity(request, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        String responseString = null;
        try {
            HttpResponse response = httpclient.execute(httpAction);
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity, "UTF-8");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(responseString);
    }

    private static void authenticateAWS(HttpRequestBase httpAction) {

        String stringToSign = getGMTTime();
        httpAction.setHeader("Content-Type", "text/xml");
        httpAction.setHeader("Host", AWS_HOST);
        httpAction.setHeader("x-amz-date", stringToSign);
        String authHeaderval =
                               "AWS3-HTTPS AWSAccessKeyId=" + ACCESS_KEY_ID + ",Algorithm=" +
                                       HMAC_SHA1_ALGORITHM + ",Signature=" +
                                       calculateRFC2104HMAC(stringToSign, SECRECT_ACCESS_KEY);
        httpAction.setHeader("X-Amzn-Authorization", authHeaderval);

    }

    /*
     * Get the current date from the Amazon Route 53 server
     */
    private static String getGMTTime() {

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("https://route53.amazonaws.com/date");

        HttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String date = response.getFirstHeader("Date").getValue();
        return date;

    }

    private static String prepareCNAMERecordsReq(String action, String name, String[] domains) {
        StringBuffer request =
                               new StringBuffer(
                                                "<ChangeResourceRecordSetsRequest xmlns=\"https://route53.amazonaws.com/doc/2013-04-01/\">"
                                                        + "<ChangeBatch>" + "<Changes>");
        for (int i = 0; i < domains.length; i++) {
            request.append("<Change><Action>" + action + "</Action>" + "<ResourceRecordSet>" +
                           "<Name>" + domains[i] + "</Name>" + "<Type>CNAME</Type>" +
                           "<TTL>100000</TTL>" + "<ResourceRecords>" + "<ResourceRecord>" +
                           "<Value>" + name + "</Value>" + "</ResourceRecord>" +
                           "</ResourceRecords>" + "</ResourceRecordSet>" + "</Change>");
        }
        request.append("</Changes>" + "</ChangeBatch>" + "</ChangeResourceRecordSetsRequest>");
        return request.toString();
    }

}

Sunday, May 4, 2014

[java] Listing Resource Record Sets Using the Amazon Route 53 API


import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class Test {
    private static final String AWS_HOST = "route53.amazonaws.com";
    private static final String SECRECT_ACCESS_KEY = "xxxxxxxxxxxxxxxxxxxx";
    private static final String ACCESS_KEY_ID = "xxxxxxxxxxxxxxx";
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
    private static final String HOSTED_ZONE_ID = "xxxxxxxxxxxxxxxxxxx";

    /**
     * Computes RFC 2104-compliant HMAC signature.
     * * @param data
     * The data to be signed.
     *
     * @param key
     *            The signing key.
     * @return
     *         The Base64-encoded RFC 2104-compliant HMAC signature.
     * @throws java.security.SignatureException
     *             when signature generation fails
     */
    public static String calculateRFC2104HMAC(String stringToSign, String secrectAccessKey) {

        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey =
                                   new SecretKeySpec(secrectAccessKey.getBytes(),
                                                     HMAC_SHA1_ALGORITHM);

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = null;
        try {
            mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            mac.init(signingKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(stringToSign.getBytes());

        // base64-encode the hmac
        return new String(Base64.encodeBase64(rawHmac));

    }

    public static void main(String[] args) {
        listResourceRecords();
    }

    private static void listResourceRecords() {
        // create a post request to addAPI.
        HttpClient httpclient = new DefaultHttpClient();
        String endPoint =
                          "https://route53.amazonaws.com/2013-04-01/hostedzone/" + HOSTED_ZONE_ID +
                                  "/rrset";
        HttpGet httpGet = new HttpGet(endPoint);
        try {
            authenticateAWS(httpGet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String responseString = null;
        try {
            HttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity, "UTF-8");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(responseString);
    }

    private static void authenticateAWS(HttpGet httpGet) {

        String stringToSign = getGMTTime();
        httpGet.setHeader("Content-Type", "text/xml");
        httpGet.setHeader("Host", AWS_HOST);
        httpGet.setHeader("x-amz-date", stringToSign);
        String authHeaderval =
                               "AWS3-HTTPS AWSAccessKeyId=" + ACCESS_KEY_ID + ",Algorithm=" +
                                       HMAC_SHA1_ALGORITHM + ",Signature=" +
                                       calculateRFC2104HMAC(stringToSign, SECRECT_ACCESS_KEY);
        httpGet.setHeader("X-Amzn-Authorization", authHeaderval);

    }

    /*
     * Get the current date from the Amazon Route 53 server
     */
    private static String getGMTTime() {

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("https://route53.amazonaws.com/date");

        HttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String date = response.getFirstHeader("Date").getValue();
        System.out.println(date);
        return date;

    }

}

Thursday, May 1, 2014

How to refere a WAR module as dependency in Maven

You can add type tag as follows:

<dependency>
    <groupId>org.apache.stratos</groupId>
    <artifactId>org.apache.stratos.rest.endpoint</artifactId>
    <version>4.0.0-SNAPSHOT</version>
    <type>war</type>
</dependency>