Thursday, October 28, 2010

Java - Enum Type Sample usage

Recently I got problem where i need to use, the type enum which i never used before,

The Problem: We have clustered DataBase Setup, So the Automation test should connect to the DataBase server based on some requirement. (Say it has an Activation pair, and DataStorage pairs.)

So here the typical way is we need to define the connection properties for each pair and connect then accordingly. But when we need to repeat this in a lot of tests, So here the use of the type enum comes.

Usage:

1. Define public enum DataBaseServer
2. Define the connection properties

      private String dbDriver ;
      private String dbServerUrl ;
      private String userName ;
      private String password ;
      private String port;

3. Now initialize the DataBaseServer based on the Type For example for a primary activation server.

PRIMARY_ACTIVATION_SERVER("Primary Registry Database Server"){

       public String getDbDriver() {
           return "PrimaryRegistryDBDriver";
       }
       public String getDbServerUrl() {
           return "PrimaryRegistryDBUrl";
       }
       public String getPort() {
           return "PrimaryRegistryDBPort";
       }
       public String getUserName() {
              return "PrimaryRegistryDBUsername";
       }
       public String getPassword() {
         return "PrimaryRegistryDBPassword";
       }
}, SECONDARY_ACTIVATION_SERVER("Primary Registry Database Server"){ //init code here, check the primary code},
PRIMARY_DATA_SERVER("Primary Registry Database Server"){ //init code here},
SECONDARY_DATA_SERVER("Primary Registry Database Server"){ //init code here} ;

4. In your data base connection call you can just specify the type like this

  DBConnector.connect(DataBaseServer.PRIMARY_DATA_SERVER);

note that the connect will accept the DataBaseServer Type and based on it will get the properties..

-------

Wednesday, March 10, 2010

Defining and Using Custom Java Annotations

When we look in to java annotation definition it will say like this “Annotations provide data about a program that is not part of the program itself or Annotations are java’s way to provide some information to the java compiler”. For example when we look in to @Deprecated annotation, we can see that it says to the compiler that the annotated type is deprecated. That’s fine, great but in reality where I can use my own annotations and what are the scenarios? Recently I came in to a situation where I could see the right use of Custom annotation. When I searched for this it was pretty difficult to find out the right it formation, all tutorials talk about how to write custom annotation and what are the features and syntax but the information I wanted was when to write custom annotation or why do I write a custom annotation. So I just thought of posting one of the most important use of Custom annotation.

The requirement: I have a set of classes which are of 2 types, say example “DBUpdate” classes and “DBInsert” Classes. When run time I need to do actions based on which type of class is executing

Solutions:

    1. Use a super class and do a type check in run time. But here the issue is both classes are extending  from   same super class “DataBase.”

    2. Define a marker interface “DataBaseUpdate” and implement this interface for the classes which are doing “DataUpdate”. (This works fine..!!!) But need to define 2 interfaces and should be careful about implementing right Interface etc

   3. The alternative solution is define a custom annotation “DataBase” and mark your classes with this. (We will see how to do this”)

Define the Custom Annotation:

   @Target(ElementType.TYPE)
   @Retention(RetentionPolicy.RUNTIME)
    public @interface DataBase {
        String dbTask() default “”;
    }

Use @Interface before the annotation name.(dOwe see any relationship between the solution number 2 and the keyword @iInterface!!!!!!) Note that there are 2 other annotations used for defining an Annotation .. :). @Target will define the scope of the annotation (method, class, constructor..etc. Refer Javadoc for all the Target element Types and to know the RetentionPolicy)

Process the Annotation at Runtime:

Here a method which will process when it found our annotation

@SuppressWarnings("unchecked")
public static String processAnnotation()
{
    // getting the classes in execution
   // getAllClassesInExecution definition is not added here

    Class[] classesInExecution = getAllClassesInExecution();
    for(int i=0; i<classesInExecution.length; i++)
    {
          if(classesInExecution[i].isAnnotationPresent(DataBase.class)){
               DataBase db = classesInExecution[i].getAnnotation(DataBase.class);
               String dbTask = db.dbTask();
               if (dbTask.equalsIgnoreCase(“update”) {
                          //Do db update here.
               }
               else if (dbTask.equalsIgnoreCase(“insert”) {
                        //Do db isert here.
         }
   }
}

Using the Annotation:

Now Use this Annotation at class level. (We used Target(ElementType.TYPE))
   @DataBase(dbTask =”update”)
   Public class MyDBTest{
        processSQL();
    }

Now we are ready with our own annotation when the code is executed based on the dbTask we provided the system will do the task accordingly. Now keep defining your custom annotations and start enjoying.
(Don’t forget to refer the performance issues and other things while using the runtime processing)

Thursday, February 18, 2010

Reading a config XML file from Ant Build

      Yesterday I was breaking my head to figure out how can I access the properties defined in and XML file. We used to define a config.properies file and access this property file in ANT. But these days writing configuration file in XML is useful we need to communicate with other applications.

       I was working on developing a SeleniumTestFrameWork in java, so I defined an XML file "testconfig.xml" to store my properties for the test framework. But for the ANT build to execute the test cases, I need to get the property of the testNG group "testgroup" which is defiend in the testconfig.xml file. Finally I found the solution which as simple as accessing config.properties file in ANT.

Here the example and sample build file for it.

Sample XML File: samplconfig.xml

<root>
<parent1>
<child1>child value </child1>
</parent1>
<parent2>parent2 value</parent2>
<parent3>parent3 value</parent3>
<root>

Now Here the ANT Build is,

<project basedir="." name="XML Property Test">
<xmlproperty collapseattributes="true" file="${basedir}/config/samplconfig.xml">
<target name="Sample xml properties">
<echo>Parent2 Value is: ${root.parent2} </echo>
<echo>chile1 Value is: ${root.parent1.child1} </echo>
</target>
</project>

When you run the build the output will be like this...

Buildfile: E:\workspace\mytest\build.xml
Sample xml properties:
[echo] Parent2 Value is: Parent2 value
BUILD SUCCESSFUL
Total time: 141 milliseconds

Now start defining your property files as XMLs, and start enjoying.... :)