Thursday, September 18, 2014

Maven source plugin

The best way to generate the source jar along with the classes using maven is using the below plugin.

Just keep this plugin in the build tag as shown below:

    <build>
         <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.1.2</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>


Have fun!

Wednesday, September 17, 2014

Building the wso2 products

I was wondering how to build the wso2 products mainly IS and AM, I found them as very easy after talking to a friend Thanuja, one of the developers of IS in wso2.

There are 3 steps to follow to build:
  1. Build and install Kernal.
  2. Build and install Orbit.
  3. Build and install Chunk-11.
Do all those in order from the given below svn repo:
https://svn.wso2.org/repos/wso2/carbon

Most important thing is you have to do this with java: 1.6 and maven: 3.0.5.release versions only.


The 3rd step builds all the products by default, if you don't want all the products, then comment the unnecessary products in given files:
  1. components/pom.xml
  2. dependencies//pom.xml 
  3. features/pom.xml 
  4. products//pom.xml

Have fun :)

What is "final" keyword in java


The "final" is reserved keyword in java, hence can't be used it as a variable name or class name or any method name.
final is used at different places in different contexts. I illustrate the usage and essential meaning of this keyword in different contexts.

 There would be 4 different contexts, they are:

  1. Applying final keyword for a class, in class definition.
  2. Applying in a method definition.
  3. Using final keyword in a variable definition.
  4. It is used to access the variable inside an anonymous class.

Advantages of final keyword:
  • The "final" keyword is used for high performance.
  • Using final for caching the values of variables and objects.
  • It is used for static class binding.
  • It is used to variables which will be involving in multi-threading, since final resources can be accessed safely without any synchronization.
  • It helps the JVM in optimizing the classes, methods and variables.

Thursday, March 27, 2014

Free online education websites

There are many websites available for free education and learning. Really hats off to all of them..

When I searched the google for online free websites.. found alot... but I got a good link from Dunith D which has a good collection of websites.. Here is the list..


This is taken from Dunith.D .

Thanks to Dunith.

Sunday, March 23, 2014

Ant - downloading a file in ant.


<!-- To display the complete path of the files -->
<dirset id="dirs" dir="${maven_app_dir}" includes="*"/>
<pathconvert dirsep="/" pathsep="," property="dirs" refid="dirs"/>
<echo message="${dirs}"/>

<!-- <target name="bootstrap">
        <mkdir dir="${user.home}/.ant/lib"/>
        <get dest="${user.home}/.ant/lib/ant-contrib.jar" src="http://search.maven.org/remotecontent?filepath=ant-contrib/ant-contrib/1.0b3/ant-contrib-1.0b3.jar"/>
<echo message="ha ha " />
    </target> -->

Thursday, March 20, 2014

How to add custom html signature to the microsoft office outlook in 2007


If you are getting frustrated in adding a custom html message as a signature, then we both are same group... :)

This is the quickest and very powerful way of adding the signature.

Open C:\Users\{username}\AppData\Roaming\Microsoft\Signatures\{fileName} and select {fileName} and add the signature. Restart Office ... and enjoy.


Have fun.

Monday, November 18, 2013

== vs equals in java

/**
 *
 * TODO Description go here.
 *
 * @author <a href="mailto:varra@outlook.com">Rajakrishna V. Reddy</a>
 * @version 1.0
 *
 */
public class StringManual
{
   
    /**
     * The main method.
     *
     * @param args
     *            the arguments
     */
    public static void main(String[] args)
    {
        String s1 = "foo"; //Creates a string in String constant pool rather in heap. [Happens the same for all strings created as ""]
        String s2 = "foo"; // String constant pool will not create a new string as there is already a string with the same content S1, so s2 points to the s1 i.e s2=s1.
       
        System.out.println(s1 == s2); // TRUE: because s2=s1, both references are same i.e s1.
        System.out.println(s1.equals(s2)); // TRUE: based on content.
       
        String s3 = new String("foo"); //Creates a string in heap. [Happens the same for all strings created as new String.]
        System.out.println(s1 == s3); // FALSE: because both references are not same i.e s1 is in constant pool and s3 is in heap.
        System.out.println(s1.equals(s3)); // TRUE: based on content.
    }
}

Wednesday, June 19, 2013

Script to calculate the logIn time in linux

This is could be very useful when you need to calculate the logIn time for attendance/swipes. Here it goes.


#!/bin/bash

. ~/.bash_functions

function updateLogInTime()
{
    file=$1
    fullDate=`date +"%d-%m-%Y %H:%M:%S"`
    today=`date +"%d-%m-%Y"`;
    todayEntry=`grep $today $1`;
    now=`date +"%H:%M:%S"`;
    nowInSecs=`tounixtime`
    if [ -z "$todayEntry" ]; then
       echo "UpdatedAt: $fullDate, In: $now/$nowInSecs, Out: $now/$nowInSecs, Total: `date -u -d @"0" +'%-H:%-M:%-S'`" >> $file;
    else
       tokens=( `getTokens "$todayEntry" ,` )
       # use for loop read all fields
       for (( i=0; i<${#tokens[@]}; i++ ))
       do
           token=${tokens[i]}
           case $token in
                UpdatedAt:)
                        updatedTodayEntry="$updatedTodayEntry $token $fullDate";;
                In:)
                        inTimeToken=${tokens[i+1]};
                        inTimeTokens=( `getTokens "$inTimeToken" /` );
                        inTime=${inTimeTokens[1]};
                        updatedTodayEntry="$updatedTodayEntry, $token $inTimeToken";;
                Out:)
                        updatedTodayEntry="$updatedTodayEntry, $token $now/$nowInSecs";;
                Total:)
                        diff=`calc $nowInSecs-$inTime`;
                        updatedTodayEntry="$updatedTodayEntry, $token `date -u -d @"$diff" +'%-H:%-M:%-S'`";;
           esac
       done
       updatedTodayEntry=`trim $updatedTodayEntry`
       sed -i s%"${todayEntry}"%"${updatedTodayEntry}"%g $file
    fi
}

function main()
{
     screenLocked=`isScreenLocked`;
     if [ $screenLocked -eq 0 ]; then
        updateLogInTime /krishna/Misc/Notifications/data/logInTime.db
     fi
}

main

Happy Coding!

Thursday, April 4, 2013

Installing application sources jar to local maven repo.

I've been searching for a way to install my own application sources to my local maven repo along with the jar file, but couldn't found any where and not even in maven site.

But finally I got a way to do it when I was analyzing the maven plugins. Here it goes, just have this entry in ur pom.xml!!

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.1.2</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
 </build>

Fun to be coding!

Thursday, October 18, 2012

My CloudWatch Monitor for AWS

Amazon EC2 offers the CloudWatch service to monitor cloud instances as well as load balancers. While this service comes at some cost (0,015$/hour/instance) it offers useful infrastructure metrics about the performance of your EC2 infrastructure. While there are commercial and free tools out there which provide this service, you might not want to invest in them or add another tool to your monitoring infrastructure. This post will provide step-by-step guidance on how to extend your monitoring solution to retrieve cloud metrics. The code sample is based on the free and open-source dynaTrace plugin for agent-less cloud monitoring. Some parts however have been simplified or omitted in tutorial. The major parts that are missing in this sample are dynamic discovery of EC2 instances and an algorithm which is a bit more reliable and accurate in retrieving monitoring data.

Step 1 – Basic Infrastructure

So let’s get started by setting up our basic infrastructure. First we need to download the Java Library for Amazon CloudWatch . Alternatively you can create your own Web Service stubs or simply use the REST interface. For simplicity we rely on the ready-to-use library provided by Amazon. The we create a Java class for our cloud monitor which implements the basic functionality we need. For brevity I will omit any imports needed – in Eclipse CTRL – SHIFT – O will do the job :-)
public class CloudWatchMonitor {
 
 private static class MeasureSet{
   public Calendar timestamp;
   public HashMap&lt;String, Double&gt; measures = new HashMap&lt;String, Double&gt;();
 
   @Override
   public int compareTo(MeasureSet compare) {
     return (int) (timestamp.getTimeInMillis() - compare.timestamp.getTimeInMillis());
   }
 
   public void setMeasure(String measureName, double value) {
     measures.put(measureName, value);
   }
 
   public Set&lt;String&gt; getMeasureNames() {
     return measures.keySet();
   }
 
   public double getMeasure(String measureName) {
     return measures.get(measureName);
   }
 }
 
 private String instanceId;
 
 private AmazonCloudWatchClient cloudWatchClient;
 
   public static void main(String... args) throws Exception {
   CloudWatchMonitor monitor = new CloudWatchMonitor("&lt;instanceName&gt;", Credentials.accessKeyId, Credentials.secretAccessKey);
   for (;;) {
     MeasureSet measureSet = monitor.retrieveMeasureSet(measureNames);
     if (measureSet != null) {
     printMeasureSet(measureSet);
   }
   Thread.sleep(60000);
   }
 }
 
 public CloudWatchMonitor(String instanceId, String accessKeyId, String secretAccessKey) {
   cloudWatchClient = new AmazonCloudWatchClient(accessKeyId, secretAccessKey);
   this.instanceId = instanceId;
 }
}
So what have we done? We defined the CloudWatchMonitor which will contain all our logic. The main method simply queries every minute for new measures and prints them. We have chosen an interval of one minute as CloudWatch provides accuracy to one-minute intervals. Additionally, we defined the inner MeasureSet class which represent a set of measures collected for a given timestamp. We have used a HashMap to make the implementation more generic. The same is true for the retrieveMeasureSet method which takes the measures it retrieves as an input. Finally we defined the constructor of our monitor to create an instance of an AmazonCloudWatchClient – this is supplied by the Amazon library we use -  and store the instanceID of the EC2 instance to monitor.  The  accessKeyID and secretAccessKey are the credentials provided for your Amazon EC2 account.

Step 2 – Retrieve Monitoring Information

Now we have to implement the retrieveMeasureSet method which is the core of our implementation. As there are quite a number of things we have to do, I will split the implementation of this method into several parts. We start by creating a GetMetricStatisticsRequest object which contains all information which data we are going to request. First we set the namespace of the metrics which in our case is AWS/EC2 (in case we want to retrieve load balancer metrics it would be AWS/ELB). Next we define which statistical values we want to retrieve.  Then we define the period of the monitoring data. In our case this is one minute. If you want aggregated data you can specify any multiple of 60. Then we define which measure aggregates we want to retrieve. CloudWatch offers average, minimum and maximum values. As our aggregation will only contain one data point all of them will be the same. Therefore we only retrieve the average.
public MeasureSet retrieveMeasureSet(ArrayList&lt;String&gt; measureNames) throws AmazonCloudWatchException, ParseException {
 
  GetMetricStatisticsRequest getMetricRequest = new GetMetricStatisticsRequest();
  getMetricRequest.setNamespace("AWS/EC2");
  getMetricRequest.setPeriod(60);
  ArrayList&lt;String&gt; stats = new ArrayList&lt;String&gt;();
  stats.add("Average");
  getMetricRequest.setStatistics(stats);
  ArrayList&lt;Dimension&gt; dimensions = new ArrayList&lt;Dimension&gt;();
  dimensions.add(new Dimension("InstanceId", instanceId));
  getMetricRequest.setDimensions(dimensions);
Next we have to define the time frame for which we want to retrieve monitoring data. This code looks a bit complex simply because we have to do some number formatting here. CloudWatch expects the time in a special format and all date values in ISO 8601 format which use UTC and looks like this 2010-04-22T19:12:59Z. Therefore, we have to get the current UTC time and format the date strings in the proper format.  We take the current time as the end time and the start time is 10 minutes back in the past. Why are we doing this? The reason is that CloudWatch data is written asynchronously and the latest metrics we will get will be a couple of minutes in the past.  If we set the start time to one minute in the past we would not get any metrics.
 String dateFormatString = "%1$tY-%1$tm-%1$tdT%1tH:%1$tM:%1$tSZ";
 GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
 calendar.add(GregorianCalendar.SECOND, -1 * calendar.get(GregorianCalendar.SECOND));
 getMetricRequest.setEndTime(String.format(dateFormatString, calendar));
 calendar.add(GregorianCalendar.MINUTE, -10);
 getMetricRequest.setStartTime(String.format(dateFormatString, calendar));
Additionally we have to add the following code to the constructor to calculate our UTC offset and define the timezone member field.
  TimeZone zone = TimeZone.getDefault();
  timeOffset = zone.getOffset(new Date().getTime()) / (1000 * 3600);
The next thing we have to do now is retrieve the actual metrics. As we will get more than one measurement we have to store them to later on select the latest measurement. The inconvenient part here is that the CloudWatch API does not allow us to retrieve more than one timer at once.  Therefore we have to make a request for each metric we want to retrieve.  Additionally you will notice some possibly cryptic date parsing and calculation.  What we do here is parse the date string we get back from Amazon and create a calendar object.  The tricky part is that we will have to add (or subtract) the offset of our current timezone to UTC.  The formatter is defined as private DateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd’T'HH:mm:SS’Z'”);
HashMap&lt;Long, MeasureSet&gt; measureSets = new HashMap&lt;Long, MeasureSet&gt;();
for (String measureName : measureNames) {
  getMetricRequest.setMeasureName(measureName);
  GetMetricStatisticsResponse metricStatistics = cloudWatchClient.getMetricStatistics(getMetricRequest);
  if (metricStatistics.isSetGetMetricStatisticsResult()) {
    List&lt;Datapoint&gt; datapoints = metricStatistics.getGetMetricStatisticsResult().getDatapoints();
    for (Datapoint point : datapoints) {
    Calendar cal = new GregorianCalendar();
    cal.setTime(formatter.parse(point.getTimestamp()));
    cal.add(GregorianCalendar.HOUR, timeOffset);
    MeasureSet measureSet = measureSets.get(cal.getTimeInMillis());
    if (measureSet == null) {
      measureSet = new MeasureSet();
      measureSet.timestamp = cal;
      measureSets.put(cal.getTimeInMillis(), measureSet);
   }
   measureSet.setMeasure(measureName, point.getAverage());
}
The last part is to retrieve the latest available measurements and return them. Therefore we will simply sort the measurements and return the latest one.
 ArrayList&lt;MeasureSet&gt; sortedMeasureSets = new ArrayList&lt;MeasureSet&gt;(measureSets.values());
 if (sortedMeasureSets.size() == 0) {
   return null;
 } else {
   Collections.sort(sortedMeasureSets);
   return sortedMeasureSets.get(sortedMeasureSets.size() - 1);
 }
In order to make sorting work we have to make the MeasuresSet implement comparable
private static class MeasureSet implements Comparable&lt;MeasureSet&gt; {
 
  @Override
  public int compareTo(MeasureSet compare) {
    return (int) (timestamp.getTimeInMillis() - compare.timestamp.getTimeInMillis());
  }
 
  // other code omitted
}

Step 3 – Printing the Results

Last we have to print the results to the console.  This code here is pretty straightforward and shown below.
public static void printMeasureSet(MeasureSet measureSet) {
  System.out.println(String.format("%1$tY-%1$tm-%1$td %1tH:%1$tM:%1$tS", measureSet.timestamp));
  for (String measureName : measureSet.getMeasureNames()) {
    System.out.println(measureName + ": " + measureSet.getMeasure(measureName));
  }
}

Step 4 – Defining the Metrics to Retrieve

Our code is now nearly complete the only thing we have to do is define which metrics we want to retrieve. We can either pass them as command-line parameters or explicitly specify them. CloudWatch supports the following parameters for EC2 instances:
  • CPUUtilization
  • NetworkIn
  • NetworkOut
  • DiskReadBytes
  • DiskWriteBytes
  • DiskReadOperations

Step 5 – Visualizing and Storing the Data

As you most likely do not want to look at the data on your console, the final step is to visualize and store the data. How to implement this depends on the monitoring infrastructure you are using- Below you can see a sample of how this data looks in dynaTrace.
CloudWatch-based Instance Monitoring
CloudWatch-based Instance Monitoring in dynaTrace

Conclusion

Building your own CloudWatch monitoring is pretty easy. The metrics provided enable an initial understanding how your EC infrastructure is behaving. These metrics are also input to the Amazon EC2 Auto Scaling infrastructure.
If you want to read more articles like this visit dynaTrace 2010 Application Performance Almanac