Decorator Pattern

Decorator Pattern is a structural Pattern. It is used to dynamically add or remove responsibilities from an object when sub-classing would result in creating unmanageable number of classes.

Classification – Structural Pattern.

Intent – Providing extra responsibility to an object at run-time.

Discussion – Extending behavior of a class can be done statically by inheritance.  But many times inheritance is not the best way to extend the behavior as it violates the Open Close Principle. Sub-classing also results in a more fragile code as and changes to super class may result in breaking all the subsequent sub classes.  The alternative to inheritance is composition which allows the object to be wrapped by one or more decorator objects. Decorator objects are of same type as original objects and works on composition and https://www.cialissansordonnancefr24.com/generique-cialis/ delegation.  Let see how decorator works using a class diagram.

Solution

decorator

decorator

Participants

  1. Component – Parent Interface for the class whose behavior is to be modified at runtime.
  2. ConcreteComponent – Main class whose behavior is to be modified at runtime.
  3. Decorator – Abstract class implementing Component  and also contains an instance of component.
  4. ConcreteDecorator – Extends decorator. We need to have as many decorators as there are number of behavior.

Main points

  1. Decorators implement the same interface as the original object.
  2. They have an instance of original object.
  3. They implement the same method which needs extra responsibility.
  4. They are wrapper around the original objects.
  5. They are composed of original object and other decorators. They use composition to change the behavior.
  6. They provide a way to follow Open Close Principle.

Example.

Consider a pizza shop which sells pizza with many different kind of toppings. The toppings are customizable and final price of pizza will depend on topping that are used. Now one way to calculate the cost of each combination will be to have a subclass for each of the pizza combination and implement the cost method for each combination. The drawbacks for above scenario.

  1. Lets say there are 20 combinations. Then combinations of all the components will be huge. So we have to write staggering number of classes.
  2. If someone wants double topping of a particular components the number of combination will become even more.
  3. Adding one new component will result in addition of many more classes.

Thus we see that sub-classing here is not an option. Let see how we can use Decorator for solving this.

  1. Create a Pizza interface with method cost() and description(aka component)
  2. Implement Pizza interface lets say we have Pan Pizza and classic hand tossed pizza. (aka ConcreteComponent)
  3. Create a PizzaDecorator abstract class which implements Pizza. Add a instance variable of type Pizza. (aka decorator)
  4. Extend PizzaDecorator with as many toppings you have and implement the cost and description methods (aka concrete decorator).

Let check out the code for more coherency.

Component

public interface Pizza {

    public double cost();
    public String description();
}

ConcreteComponents

public class ClassicPizza implements Pizza {
    @Override
    public double cost() {
        return 175;
    }

    @Override
    public String description() {
        return "This is classic hand tossed pizza";
    }
}

public class PanPizza implements Pizza {
    @Override
    public double cost() {
        return 200;
    }

    @Override
    public String description() {
        return "This is pan pizza";
    }
}

Decorator

public abstract class Toppings implements Pizza{
    public Pizza pizza;
}

ConcreteDecorator

public class Paneer extends Toppings{

    public Paneer(Pizza pizza){
          this.pizza = pizza;
    }
    @Override
    public double cost() {
        return pizza.cost() + 50;
    }

    @Override
    public String description() {
        return pizza.description() + " paneer";
    }
}

public class Cheese extends Toppings {

    public Cheese(Pizza pizza){
           this.pizza = pizza;
    }
    public double cost() {
        return pizza.cost() + 30;
    }

    @Override
    public String description() {
        return pizza.description() + " cheese ";
    }
}

public class Onion extends Toppings {
    public Onion(Pizza pizza){
           this.pizza = pizza;
    }
    public double cost() {
        return pizza.cost() + 15;
    }

    @Override
    public String description() {
        return pizza.description() + " onion ";
    }
}

public class Chicken extends Toppings{

    public Chicken(Pizza pizza){
        this.pizza = pizza;
    }
    @Override
    public double cost() {
        return pizza.cost() + 50;
    }

    @Override
    public String description() {
        return pizza.description() + " chicken";
    }
}

So here we are, we have all the components to create our own pizza as per our wish. Check out how the cost and description method of pizza are modified at runtime in our concrete decorators. So now lets see how our PizzaMachine looks

public static void main(String[] args){

        // i want classic pizza
        Pizza pizza = new ClassicPizza();

        //want double dose of cheese on it
        Cheese cheese = new Cheese(pizza);
        cheese = new Cheese(cheese);

        //want some chicken on it.
        Chicken chicken = new Chicken(cheese);

        //want some onion on it
        Onion onion = new Onion(chicken);

        System.out.println("Your pizza is ready");
        System.out.println("You have ordered a " + onion.description() + " pizza");
        System.out.println("Price of your pizza is : "  + onion.cost());
    }
}

So here we are, we have successfully created a PizzaMachine which calculates cost of Pizzas at run-time. We attained this by wrapping/decorating a Pizza Objects with all the toppings we required.

Famous example

In java IO streams use decorator patterns. We have a base class InputStream which is an abstract class.  Other classes FileInputStream, BufferedStream etc extends this class and keeps an instance of InputStream.

References

  1. http://www.tutorialspoint.com/design_pattern/decorator_pattern.htm
  2. http://www.javaworld.com/article/2076814/core-java/inheritance-versus-composition–which-one-should-you-choose-.html
  3. http://www.oodesign.com/decorator-pattern.html
  4. http://sourcemaking.com/design_patterns/decorator
Print Friendly, PDF & Email
Posted in Design | Tagged , , | Comments Off on Decorator Pattern

Java Basics – Modifiers

In Java when we write our classes, methods and fields then we need some have some some control over how and where these classes, methods and fields can be used. We can have this control by using Modifiers. Modifiers are special java keywords that allow us to fine grain the control over usage of class, methods and fields. Modifiers fall into two groups.

  1. Access Modifiers.
  2. Other Modifiers.

Access Modifiers

These modifiers let us control who can access the classes, methods and fields. There are three access modifiers namely

  1. public
  2. private
  3. protected

There is a 4th level of control which is popularly known as “default” access. When none of the access modifiers is used then the element (class, methods and fields) are said to have default access.

Private Access

Example – private void someMethod(){}

  1. This is most restrictive access modifier.
  2. Class cannot be declared private unless they are nested.
  3. A private method or field can be accessed only within the class they are declared.
  4. They cannot be inherited.

Public access

Example – public class Someclass{ }

  1. Least restrictive modifier.
  2. A public class, method or field can be access by any other piece of code in the system.

Protected Access

Example – protected int myInt;

  1. Also known as Inheritance access.
  2. Class cannot be declared protected unless it is a nested class.
  3. A protected member can be accessed by all the classes within the same package of containing class.
  4. A protected member can be accessed by all the subclasses which are not part of same package.

Default Access

Example class defaultClass

  1. default access is also known as package access.
  2. A default class can be accessed only within same package.
  3. A default method and field can be only accessed within same package.

To summarize

Same Class Package SubClass All
public yes yes yes yes
protected yes yes yes no
default yes yes no no
private yes no no no

Code Snippet

package com.aranin.corejava;

/**
 * Created by IntelliJ IDEA.
 * User: Niraj Singh
 * Date: 7/14/14
 * Time: 11:47 AM
 * To change this template use File | Settings | File Templates.
 */
public class AccessDemo {
    private int x = 10;

    protected void printx(){
        System.out.println(x);
    }

    void printdefaultx(){
        System.out.println(x*100);
    }

}

/*
This need to be commented. There can be only one public class per file.
Compiler Error -  Class 'SecondPublic is public, should be declared in file named SecondPublic.java'
public class SecondPublic{

}
 */

/**
 * it is ok to have a another class with default access
 */
class DefaultClass{
    public static void main(){
        AccessDemo ad =  new AccessDemo();
        /*
             ad.x will give compiler error in line below.
             x has private access in class com.aranin.corejava.AccessDemo
         */
        //System.out.println(ad.x);

        /*
        * can access protected in same package
        */

        ad.printx();

        /*
        * can access default in same package
        */

        ad.printdefaultx();

    }

}

Classes in another package

package com.aranin.corejava.another;

import com.aranin.corejava.AccessDemo;

/**
 * Created by IntelliJ IDEA.
 * User: Niraj Singh
 * Date: 7/14/14
 * Time: 11:58 AM
 * To change this template use File | Settings | File Templates.
 */
public class AnotherPackageClass extends AccessDemo{
    public int a = 100;

    public   AnotherPackageClass(){
        this.printx();
    }

    /*
    * Override and used protected is subclass allowed
     */
    protected void printx(){
        //can be access in subclass within other package
        super.printx();
        System.out.println(a);
    }

    /**
     * This is not overriding as printdefaultx in AccessDemo is not visible.
     */

    void printdefaultx(){
        System.out.println(a*100);
    }

    public static void main(String[] args){
        AccessDemo ad = new AccessDemo();
        AnotherPackageClass apd = new  AnotherPackageClass();

        //can't use here and printx is protected
        //ad.printx();

        //cant be done compiler error stating that  printdefaultx is not public
        //ad.printdefaultx();

        //can be done will print 100
        apd.printx();

        //can be done will print 10000
        apd.printdefaultx();

    }

}

Subclasses and overriding rules

In java a method cannot be overridden to be more private. So the rules are

  1. private method – Cannot be overridden.
  2. default method – Can be overridden by default, protected or public method.
  3. protected method – Can be overridden by protected or public method.
  4. public method – Can only be overridden by public method

Other Modifiers

Apart from access modifiers there are other modifiers which can be applied in java. They are

  1. final
  2. abstract
  3. static
  4. native
  5. transient
  6. volatile
  7. synchronized
  8. strictfp

final

final modifier can be applied to class, methods, fields and variables.

  1. final class cannot be inherited.
  2. final method cannot be overridden.
  3. final fields cannot be modified once initialized. They are know as constants.
  4. final methods and fields are inherited in same way as normal methods and fields however they cannot be modified or overridden.
package com.aranin.corejava;

/**
 * Created by IntelliJ IDEA.
 * User: Niraj Singh
 * Date: 7/14/14
 * Time: 12:11 PM
 * To change this template use File | Settings | File Templates.
 */
public class FinalDemo {
    public final int a;
    public final int b = 1;

    public FinalDemo(){
        // initialised once and now cannot be assigned another value
        a = 100;
       //variable a might already have been assigned
       //a++;

       System.out.println(a);
    }

    public final void doSomething(){
      System.out.println("final product : " + a*b);
    }

    public static void main(String[] args){
         FinalDemo finalDemo = new FinalDemo();
    }

}

class ExtendFinalDemo extends FinalDemo{

    /**
     *  doSomething() in com.aranin.corejava.ExtendFinalDemo cannot override doSomething() in 
     *  com.aranin.corejava.FinalDemo; overridden method is final
     */
    /*
    public final void doSomething(){
      System.out.println("final product : " + a*b);
    }   */

}

abstract

abstract modifier can be applied to class or method.

  1. abstract class cannot be instantiated.
  2. abstract method must be overridden.
  3. class containing abstract method must be declared abstract.
  4. child class must override the abstract methods of an abstract class else child class should be declared abstract.
  5. abstract method must not be private.
  6. constructor can not be abstract.
  7. fields cannot be abstract.

static

static modifier can be applied to methods, fields and code block. The only time static is applied for class is when they are nested class. Static members are not associated with any instance of class, at any time there is only one copy of the static member. They are initialized and created when the class is first loaded.

  1. static modifier can only be applied for methods and fields.
  2. Nested class can be static.
  3. Static members does not belong to instance of class. They belong to class only.
  4. There is only copy of static method and field. They are created when class is first loaded in JVM.
  5. static method cannot be overridden. Overriding is run time operation and is related to object. Static methods on other hand are not owned by object hence they cannot be overridden.
  6. Static methods cannot access fields and methods of enclosing class directly. They should obtain instance of class to access the members.
  7. When a class is loaded into JVM then all its static members are initialized in order they appear in class.
package com.aranin.corejava;

/**
 * Created by IntelliJ IDEA.
 * User: Niraj Singh
 * Date: 7/14/14
 * Time: 12:20 PM
 * To change this template use File | Settings | File Templates.
 */
public class StaticDemo {
    /**
     * static statments are run one by one when class is firt loaded. In this case the belore static block will run
     * before main is executed
     */
    static{
        System.out.println("I will be printed before main");
    }
    //final static int
    public static final int a;
    public static int b = 10;
    public int i = 100;

    /**
     * static intitializer block for intitializing a
     */
    static{
          a = 100;
    }

    public static void printi(){

        /**
         * non static variable i cannot be referenced from a static context
         */
        //System.out.println("i = " + i);
    }
    public static void prints(){
       System.out.println("I am prints in StaticDemo");
    }

    public static void main(String[] args){
        System.out.println("I am main i am the boss");
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        StaticDemo.prints();
        StaticDemoSub.prints();
    }

    /**
     * can have static nested class
     */
    public static class StaticInner{

    }
}

/**
 * cant do
 * Modifier 'static' not allowed here
 */
/*
static class TopStatic{

}
*/

/**
 * demo for static method cannot be overridden
  */
class StaticDemoSub extends StaticDemo{

    /**
     * this appears to override prints in  StaticDemo but that is not the case.
     *  They are both different method
     */
    public static void prints(){
       System.out.println("I am prints in StaticDemoSub");
    }
}

native

  1. native modifier is applied only to methods.
  2. Applying native implies that the method is written in code other than java like C or ,C++.
  3. It is mostly used to import C,C++ libraries or low level stuff into java code.

transient

  1. transient modifier can only be applied to variables and not methods or classes.
  2. transient variables cannot be serialized. i.e if an object is serialized then all its transient variables are not.
public class TransientDemo implements Serializable{
     public int a = 10;
     //This will not be serialized hence credit card number cannot be 
     //saved into file
     private transient String creditCardNum;
}

volatile

  1. Only variables can be volatile.
  2. When a variable is declared volatile then it can be modified asynchronously.
  3. If multiple threads modify a volatile variable then they all get same value. So the state of volatile variable is always consistent for all the threads. So if you want a variable whose value is same for all the thread at a time then use volatile.
  4. volatile is used in creating consistent singleton classes in a multi-threaded system

synchronized

synchronized is used to control the access of a piece of resource by multiple threads. This is beyond scope of this post.

Phew! writing on basic stuff is tough. I hope all you folks enjoyed this post.

if(somethingwrong){
     please drop a comment
}else{
      drop a comment
}

Warm Regards

Niraj

Print Friendly, PDF & Email
Posted in Core Java | Comments Off on Java Basics – Modifiers

Object Oriented Design Principles

In an Object Oriented System, poorly designed classes spell catastrophe. Robert Martin listed some of the basic design principles in early 2000’s. these principles were to act as guidelines for developers in order to avoid bad design. The first 5 of these were very basic and they are now generally accepted as  Object Oriented Design Principles and popularly known as S.O.L.I.D design principles.

Before delving into SOLID design principles let us list out characteristics of bad design

  1. Rigidity  -Making changes are difficult as to change one class requires us to modify lots of other classes.
  2. Fragility – One change breaks many parts of system.
  3. Immobility – It is hard to reuse classes as it is highly tangled with other part of system.

S.O.L.I.D Design Principle

SOLID stands for SRP, OCP, LSP, ISP and DIP

  1. Single Responsibility Principle (SRP) –  A class should have only one reason to change. Each class should have only one responsibility and hence only one reason to change. If it has more than one reason to change then it should be split into two classes. The reason behind this is that if class with more than one responsibility needs to change then it will affect a larger part of system.
  2. Open Close Principle (OCP) – A class should be open to extension but close for modification. When ever you want to change behavior of your classes, library or packages etc then instead of modifying them just extend them. This ensures backward compatibility.
  3. Liskov Substitution Principle (LSP) – Substitutibility is a principle of Object Oriented design. This means that is S is a subtype of T then any object of type T can be replaced by objects of type S without any alteration of code. This is basis of Liksov Substitution Principle. In other words a Derived class should be written in such a way that it should be able to be used instead of Base class without changing the code.
  4. Interface segregation Principle (ISP) – ISP states that no client should be forced to use an interface that is has no use of.  This principle helps us in designing our interfaces. So we should add only those methods in an interface which has to be used by client. ISP tells us to break a large interface into smaller one so that client has to worry about only those methods which it will use. This keeps the code clean, decoupled and easily maintainable.
  5. Dependency Inversion Principle (DIP) – A high level module should not depend upon low level modules. Both should depend upon abstractions and abstraction should not depend on details, details should depend on abstraction. DIP states that high level module should be decoupled from low level modules by creating a layer of abstraction. Layer of abstraction is a wrapper on low level modules. This layer is created by taking into account the needs of high level modules. Thus abstraction(idea) drives the details and not vice-versa.

These are the famous SOLID design principles. Apart from SOLID there are few other notable designs which are mentions now and then.

YAGNI (You aren’t gonna need it) – This is not a object oriented design per se. This is rather a agile principle for software implementation. You should write only that amount of code what you need. If you write code thinking about your future need then you will end up with bloated, unusable code. And who knows how the design will change in future.

DRY (Don’t repeat yourself) – This is another neat design principle which says that do not write duplicate code. So if you see yourself writing duplicate code then wrap that code in a class (or a method) and start reusing it.

KISS(Keep it simple,stupid) – This is more generic and not a OOP design. This to me is a simple way of rephrasing SRP principle. Your classes should be simple and should do only what it is suppose to do. If it is complicated then break it into multiple classes unless you achieve simplicity.

That is all folks. Do remember to follow these guidelines while designing your classes. This will often make you a coder.  As it is understood, all the comments, negative or positive are most welcome.

And all the spammers STFU.

Warm Regards

Niraj

Print Friendly, PDF & Email
Posted in Design | Tagged , , | Comments Off on Object Oriented Design Principles

Java Basics – Nested or Inner Class

Inner classes are classes that are declared within another class.

Types of Inner Classes

Inner classes comes in 4 flavors.

  1. Member Inner Class – These classes are declared at member level of the outer class.
  2. Local Inner Class – They are declared within a method of outer class.
  3. Anonymous Class – They are also declared within a method but they don’t have a name.
  4. Static Inner Class – They are static member of the outer class.

Now we know the types of inner classes so now we can focus on describing them in details.

Member Inner Class

These classes are declared within a outer class as a member of the class (just like fields and methods). They fulfill following criteria.

  1.  Member Inner class can be declared private, protected, public or with default access.
  2. They can extend any class and can implement any number of interfaces.
  3. A member inner class can be abstract and final.
  4. A member inner class cannot declare static field or method.
  5. Member inner class has access to all the members of Outer class even the private ones.
  6. Inner class instance is associated with exactly one outer class instance. This association is is created when the inner class is created using new keyword.
  7. You cannot create an inner class without instance of outer class.

Let us look at code snippet to better understand how to declare and use Member inner class.

public class Outer {
    private int x = 10;

    public class Inner{
        private int x = 20;

        public void print(){            
             System.out.println("x : " + x);
             System.out.println("this.x : " + this.x);
             System.out.println("Outer.this.x : " + Outer.this.x);           
        }
    }

    /**
     * invoking inner class from constructor
     */

    public Outer(){
        //notice use of this.new
        Outer.Inner inner = this.new Inner();
        inner.print();
    }

    /**
     * instantiating inner from out side  the enclosing class
     */

    public static void main(String[] args){
        Outer outer = new Outer();
        //notice use of outer.new
        Outer.Inner inner = outer.new Inner();
        inner.print();
    }
}

Output of this code.

x : 20
this.x : 20
Outer.this.x : 10
x : 20
this.x : 20
Outer.this.x : 10

Observations

  1. The inner class in main is instantiated using outer.new operator. This way we associate a inner class with outer class instance.
  2. Inside outer class constructor we used this.new operator. This is a way we instantiate the inner class from within the outer class object.
  3. Use of Outer.this.x – The variable x is common to both inner and outer class. To access the outer x within the inner class you have to use OuterClassName.this.x operator. This syntax is used only within inner class.

Local Inner Class

Local Inner Class are declared within a member method of class. They are instantiated when the method is called and it goes out of scope when method returns. The Local Inner class can be instantiated only within the method. Properties of local inner class are

  1. They do not have access specifier.
  2. They cannot be declared static or have static members.
  3. They cannot access any local variable of the defined in the method unless they are final.
  4. They can access all the members of outer class.

Code Snippet for local Inner Class

public class LocalOuter {
    double radius;
    String property;

    public LocalOuter (double radius,
                       String property){

        this.radius = radius;
        this.property = property;
    }

    public double calculateProperty(){
        class Area{
              public double compute(){
                    return 3.14*radius*radius;
              }
        }

        class Circumference{
                 public double compute(){
                    return 2*3.14*radius;
              }
        }

        if(this.property.equals("area")){
            Area a = new Area();
            return a.compute();
        }else{
            Circumference c = new Circumference();
            return c.compute();
        }
    }

    public static void main(String[] args){
        LocalOuter lo = new LocalOuter(1, "area");
        double area = lo.calculateProperty();
        System.out.println("area : " + area);

        lo = new LocalOuter(1, "circumference");
        double circumference = lo.calculateProperty();
        System.out.println("circumference : " + circumference);
    }
}

You can see the declaration of two local inner class within calculateProperty() method. Notice how they can access the radius and property members of LocalOuter class.

We mentioned in properties of Local Inner Class that they can’t access the local variables of calling method. Why?

We know that JVM does not understand the concept of inner class. Inner Classes are compile time constructs. Whenever compiler encounters a inner class it creates bytecode of a top level class. So in essence it creates two top level class i.e. Outer Class and inner class. Now there is no way by which a object can be aware of local variables of a method of another class. However if the variable is declared final then a copy of it is stored in outer class from where the inner class can get its handle.

Anonymous Class

Anonymous Class is a Local Inner Class that has no name. Anonymous Inner Class is declared and instantiated in one single statement. Anonymous class class has to extend a class or implement interfaces.  Like any other inner classes when a class containing anonymous class is compiled then two top level class is created.

Code Example

public class AnonOuter {
    public boolean flag = true;
    public void doSomething(final int n){

         Thread t = new Thread(){
           public void run(){

               while(flag){
                  int random = (int)(Math.random() * 10) + 1;

                  if(random == n){
                      System.out.println("Password is : " + random);
                      flag = false;
                  }else{
                       System.out.println("bogus try : " + random);
                  }
               }

           }
         };
        t.start();
    }

    public static void main(String[] args){
        AnonOuter ao = new AnonOuter();
        ao.doSomething(9);

    }
}

You can see how we extended the Thread to create a new local thread in method.

Advantages of using Inner classes

So we have seen three flavors of inner classes. Why would be want to the?

  1. Makes code more object oriented – Sometimes a method inside a class becomes too complicated and it makes sense to put the logic inside a class construct. Thus making code more readable and object oriented.
  2. Utility classes – Utility or helper classes which are to be used by only one class can be created as inner class.  For example comparators for an object in collection.
  3. Creating local event handlers.

Static Nested Class

– This is the final type of nested class. They are static classes defined at member level of class.

  1. They don’t have access to members of outer class.
  2. They can be instantiated without an instance of outer class.
  3. Nesting creates a type of namespace. To denote nested class from outside you can suffix name of outside class to name of static nested class.
  4. Access to nested class can be controlled to access specifier. For example making a static nested class private ensures that it cannot be accessed outside the class.
  5. Enclosing class has access to all the fields of static nested class even if they are private.
  6. Static nested class can be imported using  a static import statement.

Code Snippet

public class StaticExample {
    public static class StaticInner{
        public int i = 10;
        public StaticInner(){
        }
        public void doSomething(){
           System.out.println(i);
        }
    }

    public static void main(String[] args){
        StaticExample.StaticInner si = new StaticInner();
        si.doSomething();
    }
}

This is simplest example of static nested class. Just look at main method. StaticInner is referenced using StaticExample.StaticInner, same as any static variable.

So thats all folk. I hope you enjoy this post. Please drop in a comment or two if you feel there is something is amiss.  And also drop in a comment or two if you find the post informative.

Warm Regards

Niraj

Print Friendly, PDF & Email
Posted in Core Java, Uncategorized | Tagged | Comments Off on Java Basics – Nested or Inner Class

Create a Simple Maven Java Project in Eclipse using m2eclispe

This is a brief tutorial on how to create a simple java project using m2eclipse.

Note – This post is for beginners and has been created on demand 🙂

Assumptions.

1. Maven downloaded and installed on machine.

2. m2eclipse  installed in eclipse

Follow following steps to create your maven java project

1. Go to File ->New-> Project

1

2. A New Project wizard will pop up. Drill down to Maven->Maven Project and click on next

2

3. On next screen check the keep the default values and Click on next.

three

4. On next screen you have to choose the artefact that will suit your need, since we need a simple project we will choose “Nexus Indexer” in catalog and “maven-archetype-quickstart” in filter. In the box below appropriate archetype will appear. Choose that and click on next.

four

5. On the next scree provide groupId, arctifactId, name, description and version. Please visit following link for more info on these http://maven.apache.org/guides/mini/guide-naming-conventions.html

five

5. Click on finish and your simple java project is done. On exploding the project in explorer it should look like this

six

6. Open and verify the contents of your pom.xml.

7. Try adding few other dependencies and add your code in src/main/java/your package. The dependencies should be added automatically.

Guys this post may have mistakes as done in hurry. If you find anything please holla and I will get it corrected. Have fun and bye for now.

Warm Regards

Niraj

 

 

 

Print Friendly, PDF & Email
Posted in Begineers Java, Uncategorized | Tagged , , | Comments Off on Create a Simple Maven Java Project in Eclipse using m2eclispe

Having Fun with Google Custom Search API and Java

Lets talk about the most awesome site of world, Google.  Google started as a search site and it supports over 100 billion searches a month. How does it do it? Here are some facts

  1. There are more than 60 Trillion individual Web Pages.
  2. Google navigates these pages by crawling.
  3. Once it crawls the pages it adds them to a massive index where the URL of page is stored with URL content as key.
  4. Now when you go and search on Google, it uses programs based on complicated algorithms to generate and produce search result.
  5. While ranking the URLs, Google considers more than 200 factors in consideration some of them are freshness, keyword density, site quality, relevance, synonyms etc.
  6. According to some estimate about 60% of internet traffic is non human and about 50% of this non human traffic is malicious. Also there are lots of malicious site which are intent on harming users. Google constantly works on blacklisting these pages and prevent spamming.
  7. For doing all these tasks, Google uses a total of 1 million servers approximately.

These are impressive stats.  Let us suppose that you want to have a Google like search feature on your site.  But instead of searching entire internet, you want to generate results only from a selected group of sites.

Lets say I want to create a search feature which indexes and searches only on Java Blogs. There are many tools and APIs available in different language that allows us to crawl, index and provide us the desired search result. In other words you can create your own search engine. But would your search engine be as available and robust as Google’s? Answer is,  perhaps, but it it will take lots of resources and time to do so. 

There is another approach and Google provides the alternative itself.

Google Custom Search API

Google Custom Search enables you to create a search engine for your website, your blog, or a collection of websites. You can configure your search engine to search both web pages and images. You can fine-tune the ranking, customize the look and feel of the search results, and invite your friends or trusted users to help you build your custom search engine. (Taken from google API tutorial doc).

In this post we will walk through how to create a custom Google search engine for a website and have some fun in turn. Without any further ado let us jump to the to-do steps.

As first step you need to actually create a search engine. There are two varieties

  1. Custom Google Search – This is free and can be accessed via https://www.google.com/cse/all
  2. Google Site Search – This is a more powerful and paid version of google search. The details can be found here. here http://www.google.com/enterprise/search/products/gss.html

For this tutorial we will use the free one and then we will try using api to create our own Custom search using it. Steps are below.

Step 1 – Create a search engine.

  1. For this visit the following link https://www.google.com/cse/manage/all
  2. Click on Add button. This will open create Custom Google Search Page
  3. First enter all the urls you wish to index and search against. You can choose as many as you want. I mostly choose java blogs like dzone, ibm, theserverside etc.
  4. Now enter the name of your search engine and save it.
  5. Now your search engine is created and you can go there and play with your searches.  Here is mine for your referral Weblog4j Search. Search for java and software related terms and you will get awesome results. You can customize the search page to some extent.

Steps 2 – Get the search engine id.

  1. Go to https://www.google.com/cse/manage/all.
  2. Click on the search engine you created.
  3. Go to Basic tab and find details. There is a button “Search Engine Id”. Click on the button and you will get the search engine id in the pop up. Save the id in a text file for later reference.

Step 3 – Getting the API key.

  1. Playing with json/atom custom search API requires an API key. 
  2. Go to Google Cloud Console.
  3. Create a new project and activate it. Now the project will be listed on console page. Click on the project created.
  4. On the page look at the left hand bar. Go to APIs and Auth -> API. This page list Google cloud APIs.  Find “Custom Search API” from the list and toggle it to ON.
  5. Now click on Credentials. You will find a Panel “Public API access”. Click on “Create New Key” button. On resultant popup click on Server Key.
  6. A new pop up opens. It will ask for IP which should be permitted to use the key. You can leave it empty and create the key.
  7. Copy and save the key at a secret location.

Google Custom Search API

So Now we have the search engine to play with, search engine id and API key and we are ready to get hands dirty with some code. API Overview.

  1. It is a REST api with a single method called list.
  2. The API method is GET.
  3. The response data is returned as a JSON or ATOM type.
  4. The response consists of 1. Actual search result 2. Metadata for search like number of  results, alternative search queries 3.Custom search engine metadata.
  5. The data model depends on OpenSearch 1.1 specification.

API URL – The rest url to invoke google custom search is 

https://www.googleapis.com/customsearch/v1?parameters

Parameters

  1. key – API key you saved in step 3 above
  2. cx – custom search engine id you got in step 2. In case of linked custom search engine use cref instead of cx
  3. q – the search engine query

For a complete reference of query parameter visit the following page https://developers.google.com/custom-search/json-api/v1/reference/cse/list.

Libraries and Dependencies

Since we are dealing with a third party API all we need is to make an ajax call from our front end and get resultant JSON response. But there are libraries in multiple languages available which makes the working with Google search API a breeze. For java we have following

google-api-java-client

You can download the search API library from here. Or you can use the following maven dependencies.

    <dependency>
      <groupId>com.google.apis</groupId>
      <artifactId>google-api-services-customsearch</artifactId>
      <version>v1-rev40-1.18.0-rc</version>
    </dependency>

    <dependency>
        <groupId>com.google.http-client</groupId>
        <artifactId>google-http-client-jackson</artifactId>
        <version>1.15.0-rc</version>
    </dependency>

Code for searching

We can use the normal rest APIs as there is nothing special about invoking Google custom search service url.  But for this tutorial we will be using the Google Client API for searching on our result set. Let check out the code.

package com.aranin.spring.googleapi.search;

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.customsearch.Customsearch;
import com.google.api.services.customsearch.model.Result;
import com.google.api.services.customsearch.model.Search;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Niraj Singh
 * Date: 6/3/14
 * Time: 12:42 PM
 * To change this template use File | Settings | File Templates.
 */
public class GoogleSearchClient {

    final private String GOOGLE_SEARCH_URL = "https://www.googleapis.com/customsearch/v1?";

    //api key
    final private String API_KEY = "your api key from step 3";
    //custom search engine ID
    final private String SEARCH_ENGINE_ID = "your search engine id from step 2";

    final private String FINAL_URL= GOOGLE_SEARCH_URL + "key=" + API_KEY + "&cx=" + SEARCH_ENGINE_ID;

    public static void main(String[] args){

        GoogleSearchClient gsc = new GoogleSearchClient();
        String searchKeyWord = "weblog4j";
        List<Result> resultList =    gsc.getSearchResult(searchKeyWord);
        if(resultList != null && resultList.size() > 0){
               for(Result result: resultList){
                   System.out.println(result.getHtmlTitle());
                   System.out.println(result.getFormattedUrl());
                   //System.out.println(result.getHtmlSnippet());
                   System.out.println("----------------------------------------");
               }
        }
    }

    public List<Result> getSearchResult(String keyword){
         // Set up the HTTP transport and JSON factory
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();
        //HttpRequestInitializer initializer = (HttpRequestInitializer)new CommonGoogleClientRequestInitializer(API_KEY);
        Customsearch customsearch = new Customsearch(httpTransport, jsonFactory,null);

        List<Result> resultList = null;
        try {
                Customsearch.Cse.List list = customsearch.cse().list(keyword);
                list.setKey(API_KEY);
                list.setCx(SEARCH_ENGINE_ID);
                //num results per page
                //list.setNum(2L);

                //for pagination
                list.setStart(10L);
                Search results = list.execute();
                resultList = results.getItems();

        }catch (Exception e) {
                e.printStackTrace();
        }

        return resultList;

    }
}

The code is very simple. We create a simple Customsearch object. From this object we get an Instance of CSE object which represents a search engine. Now we set our search engine properties like API Key, search engine id etc in the CSE. Then we go on to set the search criteria like search term, number of result, starting point (for pagination) for our resultset. Then execute it.

Finally we get a List of result objects. This contains all the search data and can be used to create our own search engine.

That is all folks. I hope you find this tutorial useful. Feel free to drop in couple of comments in case you like/dislike the post.

 

References

  1. https://www.google.co.in/insidesearch/howsearchworks/thestory/
  2. http://atkinsbookshelf.wordpress.com/tag/how-many-servers-does-google-have/
  3. http://www.google.co.in/about/datacenters/
  4. https://developers.google.com/custom-search/json-api/v1/overview
  5. https://developers.google.com/custom-search/docs/tutorial/creatingcse
  6. https://www.google.com/cse/manage/all
  7. https://cloud.google.com/console
  8. https://developers.google.com/custom-search/json-api/v1/introduction

 

Customsearch
Print Friendly, PDF & Email
Posted in General | Tagged , | 10 Comments

Becoming a Senior Java Engineer

Java is the one of the hottest skill in current job market. And hence lots and lots of aspiring software professional want to learn java. Through this post I want to discuss the tools, technologies and concepts that are required by a software professional to graduate from Junior Java Engineer to Senior Java Engineer. This post is more relevant to people developing web applications and hence are Backend Java Engineers. So let us create a list which could help aspiring Java Developer to become an awesome Senior Java Engineer.

1. OOPs concepts – Java is a object oriented language so without learning about OOPs you are not a java developer.

  1. So a java software engineer should be very very clear about class, Object, Encapsulation and Abstraction, Inheritance and Polymorphism.
  2. At any given point of time you should be able to explain these concepts and also reiterate how they are ingrained in java.

2. Core Java – This goes without saying, a java engineer should be an expert in core java language and should constantly be aware of new concepts and changes that take place in Java.  So keep learning core java folks, you can only know so much. 
3. JVM – As you grow as a senior developer, knowledge about JVM becomes a must. 

  • It helps you in writing better and more efficient code. 
  • Makes you programs faster through JVM tuning.
  • Adds awesome tools for debugging problems like memory leak.

4. Servlet and JSP – Servlets and JSPs form building blocks of all the modern java web framework. So even if you don’t use these directly, learning them is a must for sake of understanding, better programming and debugging.

5. Database  – You are writing a web application 99% of time you will be persisting data and getting it back for processing and displaying. So you should have knowledge about at-least one database. You should also know how to write database queries and tuning them in case need arise.

6. JDBC – Now most of the development house uses an ORM tools for their database connectivity needs but still as a java developer you should learn JDBC here is why

  • Many legacy application still uses JDBC.
  • Using JDBC is simpler for more complicated problem. So you can you use a mixture of solution, jdbc for complicated queries and ORM for simpler CRUD processes.
  • Last but not the least JDBC is the standard java api for connecting and working with database. It is easy to learn and provides us with basic understanding as to how java interacts with database. Even ORMs use JDBC internally to connect to database. So it is imperative that we learn JDBC.

7. ORM – Even though we should learn JDBC, most of the development houses use ORM tools now a days.

Examples of ORM – Hibernate, iBatis/MyBatis, JDO, JPA, Cayenne etc

  • They are a wrapper over JDBC and hence they reduces amount of code to be written for connecting and working with database.
  • ORM stands for Object Relational Mapping. It helps us working directly with objects ie, database results are directly stored in object and object is directly persisted in database. So our code becomes more object oriented we are saved the effort of mapping an object with database columns.
  • Makes repetitive CRUD operations a breeze.
  • Most ORMs supports transactions, caching and concurrency hence we don’t have to write extra code to support these as is required in JDBC.
  •  Easily unit tested.

8. Spring Framework – Learn Spring period. Foundation of Spring is based on decoupling and dependency injection. Two of the most basic OOPs design princeples. So learning and applying Spring in your project makes your code decoupled and more reusable. These two reasons are enough to  use Spring in your project. Apart from this Spring Framework comes with plethora of libraries and projects which can easily be plugged with your project and make your development breeze. No wonder spring has emerged as one of the most important technologies in java world and almost all software team uses it. So all the java developers should learn spring.

9. Web Framework – We have wide varieties of Web Framework available.

Examples are struts, Spring MVC, struts 2, Tapestry etc.

It is necessary that we learn at-least one of these frameworks.

  • Framework streamlines our development efforts and makes development easy and cost effective
  • They help us in following best practices.
  • Enables code reuse.
  • Help entire team in writing code in similar style.

10. Unit Testing – Unit testing code is a must in current agile world. The development, testing and deployment happens at a very fast rate. Unit testing makes our code less viagra pas cher prone to bugs. It gives us confidence that our code is bug free and we can freely commit our code. Examples are Junit, Junit Perf, HttpUnit, MockObject, Cactus.

11. Mimalistic UML – This is completely my view and I know it will draw lots of criticism. In agile methods we follow a minimalist design approach. This means that we design to an extent which allows us to capture the essence of our product architecture.  In this scenario, shall we learn UML which is a complex  framework and can be used to capture the design exhaustively? I have often found that I can get away by knowing Class Diagram and to some extent sequence diagram. So as a developer we should learn some part of UML which can help us to convey our ideas in bare but efficient ways. Knowing Class Diagram is a must and it can topped by knowing the sequence diagram.

Note : Use Cases etc are handled using story boards now a days.

Learn about minimalistic design here

12. Design Pattern – Without Design patterns knowledge we are only half the developer we can be or even less. Learning design patterns can be a daunting task, and applying them can be even more difficult. But this should not deter us from acquiring the knowledge. Learn a couple of patterns and think where you can apply them while coding. Once you find a place to apply, create a write up and a class diagram for the same. You can start with one or two pattern per month. It is no use to mug up patterns as you will be lost if you don’t understand the intent and application of the pattern. I have often found myself using these patterns

  • Factory Pattern.
  • Singleton.
  • Adapter.
  • Bridge.
  • Abstract Factory.
  • Facade

These can be a good starting point for any young developers.

13. SOLID Design Principles – What kind of programmers would be if you don’t understand SOLID design principles.  So go ahead read about them and understand them and use them like a checklist while designing and writing your code.

Learn more here.

  1. http://www.oodesign.com/design-principles.html
  2. http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)

14. Object Caching Frameworks– If you are writing a highly scalable web application then at some point you will require a Object Caching Framework. There are many caching framework available in market. Lots of them are open source and very mature. Examples are memcache, ehcache, OSCache, JCS, and tons more. Choose one of them learn what are they and how to use them. My Favorite is Memcache.

15. Cloud Computing – Age of Cloud Computing is upon us. So any aspiring developers should have their basics right. Learn what is cloud computing, its layers, cloud players. If possible get a hands on work shop on any of cloud platform like AWS or Azure.

16. BigData, NoSQL, Hadoop – I have clubbed these together as all are linked and many times talked about in same frame. The systems today generate more and more data and they need to be persisted, processed, accessed and made sense of. These are some of the concepts and tools you will have to acquire as you grow.

17. Javascript, Ajax, Jquery – Ok you may be cursing me, but these are the skills any web engineers should have even if they are backend engineers. Basics of object oriented javascript and bit of jquery in your resume will take you places and make you more complete developer.

18. Agile methods – Most of the development house of today are increasingly turning agile. The most popular processes they follow are

  • Scrum
  • XP
  • Pair programming
  • TDD
  • Continuous Integration.

As a developer you should study about these concept and try to understand the processes set up by the team management. They are awesome and definitely helps in creation of a better product.

Summary

This is a handful list. It takes a while before you will start to get a hang of things in Java. So now we see that journey to becoming an awesome java developer is not an easy task, you need to keep on learning new and new things. Only after hard work and perseverance can you reach a point when you can say that I am a awesome Java Engineer. Even then you will see new tools coming into light and becoming relevant. The process of learning is everlasting and you should aim of learning one tool/technology per month. 

This is by no means an exhaustive list and hence I apologize in advance if I miss have somethings. Please drop me a line or two to make this article better. 

Warm Regards
Niraj

 

 

 

Print Friendly, PDF & Email
Posted in Blaber, Uncategorized | Comments Off on Becoming a Senior Java Engineer

Introduction to Extreme Programming aka XP

Extreme Programming or XP is an agile methodology applied on the software development process to produce high quality software in simple and efficient way.

Principles of XP

XP is based on 4 basic ideas or principles.

  1. Communication.
  2. Simplicity
  3. Feedback
  4. Courage

To simply explain the 4 values. XP programmer communicates with clients and fellow team programmers to gather requirements and create tasks. Based on solid communication they strive to create a simple and efficient design for developing the software system. After designing, they conduct tests on all the use cases even before starting the development process. This enables them to introduce a very very early feedback system. Now with requirements chalked out correctly(communication), simple design in place(simplicity), and with early feedback system in place (test driven development) XP programmers embark on their software development journey without any fear and full of courage.  

XP Core Practices

As we know that XP is an agile process. Apart from adopting common agile practices XP defines 12 of its own core practices.

  1. Whole team in one place – This means that whole team including developers, designers, project managers and the client work together in a common room. One member from client team who is expert on project subject matter is always present on the team premise. This results in enhanced communication where doubts of developers gets resolved quickly. They can create their test cases quickly and get instantaneous feedback.
  2. Small and frequent release – XP as any other agile process advocates small and frequent release. The release time is usually 1- 3 weeks. Small release have many advantages the main one being –  client gets to see small features after every release and can run acceptance tests on them and thus create a very early feedback loop. As number of features per release is less, it reduces pressure on development team . An easy and steady development pace is established from very beginning which is good in long run.
  3. Testing – XP puts great importance on testing practices. Each task within the XP project must be unit tested.  XP follows practice of Test Driven Development.  After delivery all the features must have an acceptance testing. Each test must have binary result i.e. pass or fail. The tests should be automated and run with little or no human intervention.  The acceptance test cases are written by customer themselves which are later automated by testing team. This ensure the product development as per client wishes.
  4. Release Planning Game – Goal of planning game is to capture the scope of next release. It usually takes half to one day to complete the Release Planning Game. In this process the customer writes Story Cards to describe the feature they wan’t. Based on the story cards developers then create a task list and provide estimates on how soon they can complete the tasks pertaining to Story Card. The pending story card from prior release is also considered in mix.
  5. Iteration Planning Game – With all the story cards and estimates present, the client decide which stories will be delivered during next release.  Client can choose number of cards that can be delivered within a fix time frame. Or they can choose a fix number of cards and come up with release date based on these stories. Once the story cards are decided developers are asked to volunteer for tasks they will be taking up.  
  6. Simple Design – XP advocates to avoid speculative designs based on possible future changes. XP also avoids designing any elements which are not to be delivered in current or near future release. The XP design promotes code re-usability and minimizes number of classes to be written.
  7. Pair Programming – All the code in XP are written by set of two programmers on a single computer. Pairs may change frequently with each task. And since in one single moment only one programmer can write code. The other programmer is constantly code reviewing, thinking about unit tests. XP claims that this practice improves productivity through peer pressure and constant review. This also promotes learning and reduced defects and procrastination.
  8. Frequent Refactoring – Since XP work with simple design and small iterations thus design of system is constantly refined to ensure it meet the specifications.  Thus there are lots of refactoring involved in XP.
  9. Team Code Ownership – As we have seen that XP follows pair programming practice.  The pairs often change and hence each person in the team gets to work on all the part of system.  Hence the code is owned by entire team and not by few.  This makes the entire team more efficient as anyone can step up and work on the any code issue and individual dependence reduces.
  10. Continuous Integration – The committed code is continuously integrated with main code, compiled and unit tested on a separate machine.  Later on application is passed though battery of acceptance test. This loop of compiling, unit testing, acceptance testing goes on all the time and is autonomous.
  11. Sustainable Pace – Over work may create unhappiness within the team. Thus XP promotes no overtime practice.
  12. Coding Standards – Since all the developers work on all the parts of code hence it is easy to follow same coding principles and even style.
  13. System Metaphors – A large system will contain lots of subsystems, code templates etc. To make communication between programmers easy XP encourages team to come up with jargons for various subsystems.

XP Life-cycle

So now we are equipped with core principles and practices about XP.  Now let us find out how all of this fit in a XP product development life-cycle. Describing everything in details will take a book (and frankly I am not that knowledgeable) so I will just list out the steps with small amount of info. 

  1. Exploration – Like any project, XP product development starts with an exploration phase. The customers write down general story cards explaining his requirements. The developers provides with a rough estimate and game starts. 
  2. Release Planning Game – The customer and developer gather in one room where discussion takes place and then customer comes up with the story cards. The story card is handed over to developers. Developers break the stories into small tasks and provides their estimation for each of the story cards.
  3. Iteration Planning Game – The Customer then takes on all the story card and chooses which story cards will be worked upon this release. Based on story cards chosen, a task list is created and tasks are assigned to a pair of programmers. The task list also decide the time frame for the release. The time is chosen such that developers are not taxed overtly. Iterations forcing developers to overtime are never encouraged.
  4. TDD – Developers then create test cases and then write the code.
  5. Continuous Integration – The code is committed, unit tested, deployed and acceptance tested.
  6. Production Release – As the iteration is time boxed the code is released to production on fixed date. The tasks that remains are transferred to next iteration.
  7. Patch – If there are minor bugs in production code then they are fixed as part of patch release using the steps defined above.
  8. Relax – Generally a small time is given to developers to relax between two iteration.
  9. Start with next release

Summary

In this post we explained that XP is an agile methodology with a team related focus. XP team comprises of client, programmers and managers. Then we went on to enlist the 4 principles of XP i.e communication, simplicity, feedback on courage. These principles forms the foundation upon which whole of XP structure stands. Then we went through XP practices like pair progamming, team in common room. release and iteration plannings etc,

But like any other method it has pit falls. XP promotes a myopic view on upfront design, this may while save a lot of time upfront may also result in major design changes in future. Major design changes means lots of re-factoring which in turn increases project cost in terms of time and money. The pair programming  is the most important practice of XP but lot f developers are reluctant to be part of pair team.

All in all XP is a pretty powerful method. It is often found that XP practices are used in conjunction of other agile methods like scrum and evo to create a more versatile methodology.

This is my first post in this year and phew it was hard. I though I will start with an easy non code post, but boy it turned into a marathon. I hope that you like this post and would drop some comments (my wishlist) to encourage me in writing more posts. 🙂 Untill then

Warm Regards

Niraj

References

  1. http://en.wikipedia.org/wiki/Extreme_programming
  2. http://en.wikipedia.org/wiki/Pair_programming
  3. http://www.extremeprogramming.org/
  4. http://www.jera.com/techinfo/xpfaq.html
  5. http://www.agilier.com/book-reviews/agile-development.html
  6. http://www.techrepublic.com/article/eight-reasons-why-extreme-programming-wont-work-in-your-shop/#.
Print Friendly, PDF & Email
Posted in Agile | Tagged , | Comments Off on Introduction to Extreme Programming aka XP

Weblog4j wishes Happy New Year

To Dear Readers,

Weblog4j wishes all its reader Happy New Year.

It has been a humble start for weblog4j.  We managed to

12 great post

3 posts promoted on dzone.

Some of the posts cited as reference on some sites.

Ever increasing traffic.

Finally a facebook page.

We promise to work harder in 2014 and publish more and more quality content.  We also look forward to receive feedback from all of you which will help us improve.

Thanks and Warm Regards

Happy New Year

Weblog4j Team

 

Print Friendly, PDF & Email
Posted in Uncategorized | Comments Off on Weblog4j wishes Happy New Year

Aspect Oriented Programming with Spring

Introduction

In an ideal Object Oriented System, we would want to design each object to perform one specific task. However apart from performing its main task the objects also performs passive task like logging, transactions, security, caching etc. These passive activities which are necessary but not part of business logic are called “Cross Cutting Concerns“.

(Cross Cutting Concerns == Commonly Used Functionality across the system)

Separating  Cross Cutting Concerns from business logic can be a major step towards writing an well designed decoupled code. Let us ponder over ways to deal with separating Cross Cutting Concerns

Inheritance

Inheritance pops up in the mind straight away, we can inherit the common functionality and use it in our objects. But Inheriting the common functionality requires us to design us a base class. If we reuse this class in multiple places then modifying the class could be a tough job later on.

Inheritance == Difficult to modify later(inelastic code)

Delegation

Delegation is a better way of dealing with the cross Cutting Concerns. Remember Composition over Inheritance, (delegation and composition share a common concerns). But Then we would have to make calls to delegate objects at many places thus making it cumbersome.

Delegation == Cumbersome

Aspect Oriented Programming

Does this mean we are in soup. Rather not, this leaves us with a third and the best approach of all, Aspect Oriented Programming. AOP spares us the brittleness of Inheritance and cumbersomeness of delegation.  AOP shines in area of separting cross cutting concerns

What is AOP?

AOP allows us to modularize cross cutting concerns into special objects called Aspects, thereby creating a cleaner and decoupled code. With aspects in place objects no longer have to worry about performing the passive cross cutting concerns as AOP takes care of it all.

Terminologies related to AOP

Like any successful technologies AOP comes with its own sets of jargon and terminologies. Let us take a glance at those before moving to more serious business of understanding AOP.

  1. Concerns – These are the part of system modularized based on their functions. There are two types of concerns. 1. Core concerns 2. Cross Cutting concerns. Core concerns are related to the business logic of the system i.e active tasks that system performs like generating salary slip, getting employee record, doing bank transfer etc. Cross cutting concerns are the passive tasks that are required to perform the active tasks like logging, caching etc. 
  2. Joinpoint – Joinpoint is a point in execution flow where some action takes place and a possibility arises to apply an Aspect(cross cutting concern).  A joinpoint can be method being invoked, exception being thrown or change in state of an object.
  3. Advice – Each Aspect in AOP has a purpose i.e. the job it has to do. This job has to be applied at a Joinpoint.  Job or purpose of an Aspect is called Advice. Apart from defining the job of aspect, Advice also defines the time when the Aspect is to perform the job. Should the job be applied before or after or both before and after a core concern finishes its execution.
  4. Pointcut – There can be many Joinpoints in the system, but not all are chosen to be advised by an Aspect.  Aspect takes help from Pointcut to choose the Joinpoint where advise is to be woven.
  5. Aspect – Advice and Pointcut defines an Aspect. As we saw that Advice defines the job of an Aspect and when to perform it. While Pointcut defines the location where aspect weaves it advice. So what, when and where of a job defines the Aspect.
  6. Target – Target is the object which is being adviced. (Core Concern). With help of AOP this object is free to perform its primary task without worrying about cross cutting concerns.
  7. Proxy – When advice is applied to a target object a Proxy object is created. AOP container creates and manages the lifecycle of object and programmers need not worry about them.
  8. Weaving – Weaving is the process of applying Advice or Aspect to the target object to create the proxy object. Weaving can be done at compile time or classloading time or at runtime. Typically Spring AOP weaves aspect in the target object at runtime.

That’s a long list of terms to digest. Take your time in understanding them before moving on.  

Types of Advice

One Final piece before indulging in an example is to learn about type of advice. Mainly there are 4 types of advice.

  1. Before Advice – Before advice is applied before the Joinpoint starts execution. BeforeAdvice is created by implementing org.springframework.aop.MethodBeforeAdvice interface.  The method to be implemented is public void before(Method m, Object args[], Object target) throws Throwable
  2. After Returning Advice – After advice is applied after the Joinpoint completes executing. AfterReturningAdvice is created by implementing org.springframework.aop.AfterReturningAdvice interface.  The method to be implemented is public void afterReturning(Method m, Object args[], Object target) throws Throwable
  3. Throws Advice – Throws advice is applied when Joinpoint throws an exception during execution.
  4. Around Advice – This advice surrounds the Joinpoint execution and is executed before and after Joinpoint execution. This can even be use to control the invocation of a Joinpoint. 

Example

We will try to develop a simple cache with help of SpringAOP. Caching has three main core concerns.

Core Concerns

  1. Save object in Cache.
  2. Return object from Cache.
  3. Delete object from Cache.

Now apart from these core concerns caching framework has other passive task. These passive tasks forms the cross cutting concern.

Cross Cutting Concerns

  1. Re-sizing the cache when it reaches its size limit. (LRU) implementation.
  2. Locking an object to prevent from deletion when it is being read.
  3. Locking the cache to prevent and read/writes/deletes when it is getting re-sized.

Coding for all these cross cutting concerns can be time taking and tedious so let us simplify the example and we will just implement the re-size logic when the cache is full.  So after example is done we will have a cache where we can put, get and delete objects. There is a max size of cache which has been set to 10 in example. Once the cache stores 10 object then any addition to the cache will result in deletion (re-sizing) of cache by deletion of first object. The re-sizing operation is controlled by an Aspect created using Spring AOP.  Here are the steps to be followed in the example

Example Code Can be downloaded from SVN here 

https://www.assembla.com/code/weblog4j/subversion/nodes/31/SpringDemos/trunk

1. Dependencies – AOP is a core functionality of spring so to get Spring AOP going all we need are core spring jar so in your POM add following dependencies. 

     <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>${spring.version}</version>
      </dependency>

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
          <version>${spring.version}</version>
      </dependency>

      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${spring.version}</version>
      </dependency>

2.  Core Caching object.

package com.aranin.spring.aop;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

public class MyCache {

    private LinkedHashMap&lt;String, Object&gt; cacheMap = new  LinkedHashMap&lt;String, Object&gt;();
    private LinkedHashMap&lt;String, Date&gt; timeStampMap = new  LinkedHashMap&lt;String, Date&gt;();
    /**
     * defines the max size of hashmap
     */
    private long maxsize = 10;  //should come from properties file or some configuration
    /**
     * how long the object should be stored before it is evicted from cache
     */
    private long objectLifeTime = 10000;

    private boolean lock = false;

    public LinkedHashMap&lt;String, Object&gt; getCacheMap() {
        return cacheMap;
    }

    public void setCacheMap(LinkedHashMap&lt;String, Object&gt; cacheMap) {
        this.cacheMap = cacheMap;
    }

    public LinkedHashMap&lt;String, Date&gt; getTimeStampMap() {
        return timeStampMap;
    }

    public void setTimeStampMap(LinkedHashMap&lt;String, Date&gt; timeStampMap) {
        this.timeStampMap = timeStampMap;
    }

    public long getMaxsize() {
        return maxsize;
    }

    public void setMaxsize(long maxsize) {
        this.maxsize = maxsize;
    }

    public long getObjectLifeTime() {
        return objectLifeTime;
    }

    public void setObjectLifeTime(long objectLifeTime) {
        this.objectLifeTime = objectLifeTime;
    }

    public boolean isLock() {
        return lock;
    }

    public void setLock(boolean lock) {
        this.lock = lock;
    }

    /**
     * This method is used to retrive the object from cache
     * @param key
     * @return
     */
    public Object get(String key){
        return this.getCacheMap().get(key);
    }

    /**
     * this method is used for putting an object in cache
     * @param key
     * @param object
     */
    public void put(String key, Object object){
        //get the curr date
        Date date = new Date(System.currentTimeMillis());
        //set object in cacheMap
        this.getCacheMap().put(key,object);
        //put timestamp in cache
        this.getTimeStampMap().put(key, date);
    }

    public void delete(String key){
        this.getCacheMap().remove(key);
        this.getTimeStampMap().remove(key);
    }

    public void clearAll(){
        this.setCacheMap(new  LinkedHashMap&lt;String, Object&gt;());
        this.setTimeStampMap(new  LinkedHashMap&lt;String, Date&gt;());
    }

    /**
     * remove last 2 entries
     * not worried about object life time
     * this is just an example
     */
    public void resize(){
        System.out.println("inside resize");
        long size = this.getCacheMap().size();
        System.out.println("size + " + size);
        if(size == this.getMaxsize()){
            System.out.println("max size has reached");
            Map.Entry&lt;String, Date&gt; firstEntry = this.getTimeStampMap().entrySet().iterator().next();
            System.out.println("removing : " + firstEntry.getKey() + " value : " + firstEntry.getValue());

            this.timeStampMap.remove(firstEntry.getKey());

            Map.Entry&lt;String, Object&gt; firstCEntry = this.getCacheMap().entrySet().iterator().next();
            System.out.println("removing : " + firstCEntry.getKey() + " value : " + firstCEntry.getValue());
            this.cacheMap.remove(firstCEntry.getKey());
        }
        System.out.println("leaving resize with size : " + this.getCacheMap().size());
    }
}

There is nothing much to say about this class. There are two LinkedHashMaps one which stores the object and the other stores the timestamp when object was pushed in the cache. The max size is set to 10 and it has get, put and delete methods. Also there is a re-size method which will be called by Aspect as we will check later.

3. Resize Advice

package com.aranin.spring.aop;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class ResizeAdvice implements MethodBeforeAdvice {
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
          System.out.println("invoking " + method.getName() + " on " + target.getClass() + " Object");
          if(method.getName().equals("put")){
              System.out.println("before invoking " + method.getName());

              ((MyCache)target).resize();
          }
    }
}

As you can see this is a method before advice. Class implements MethodBeforeAdvice interface which contains a single mthod before(). If you examine the method you will check that rezise method is called when ever we call a put method.

3. Spring context springaopdemo.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <bean id="resizeAdvice" class="com.aranin.spring.aop.ResizeAdvice" />

    <bean id="myCache" class="com.aranin.spring.aop.MyCache" />

    <bean id="myAOPCache"
                 class="org.springframework.aop.framework.ProxyFactoryBean">

		<property name="target" ref="myCache" />

		<property name="interceptorNames">
			<list>
				<value>resizeAdvice</value>
			</list>
		</property>
	</bean>
</beans>

If you notice the above xml file, both MyCache and ResizeAdvice have been registered as spring bean. The main bean in the file is myAOPCache. This is the proxy object that spring aop creates after applying the advice on the core class. The proxy object is created by ProxyFactoryBean class. We pass a reference of myCache object to the proxy object and also register all the advice which are to be applied to the proxy classes.

4. Finally let check the Client which will help us running this demo.

package com.aranin.spring.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class MyCacheClient {
    public static void main(String[] args){
        ApplicationContext springcontext = new FileSystemXmlApplicationContext("D:/samayik/SpringDemos/src/main/resources/springaopdemo.xml");

        MyCache myCache = (MyCache)springcontext.getBean("myAOPCache");

        myCache.put("1", "1");
        myCache.put("2", "2");
        myCache.put("3", "3");
        myCache.put("4", "4");
        myCache.put("5", "5");
        myCache.put("6", "6");
        myCache.put("7", "7");
        myCache.put("8", "8");
        myCache.put("9", "9");
        myCache.put("10", "10");
        System.out.println((String)myCache.get("1"));
        System.out.println((String)myCache.get("2"));
        System.out.println((String)myCache.get("10"));
        myCache.put("11", "11");
        System.out.println((String)myCache.get("1"));
        System.out.println((String)myCache.get("2"));
        System.out.println((String)myCache.get("10"));
        System.out.println((String)myCache.get("11"));

    }

}

In this class we start the spring container and load the beans present in spingaopdemo.xml.  We push 10 objects in the cache and when we try to push the 11th object then the first one is deleted and 11th inserted. Output is big so I am not posting the output. Run the class and check the output to your satisfaction.

Summary – In this post we learnt how to better deal with cross cutting concerns using Aspect Oriented Programming. AOP is a powerful concept that allows us write cleaner and decoupled code. AOP does not provide any thing new. All it does is to segregate the business logic from other mundane tasks that system has to perform. It enables reuse of code implementing system wide cross cutting concerns. We also learnt the various terminologies associated with AOP. Last but not the least we saw a simple example where we created a simple before method advice using Spring AOP and applied it to manage our caching system.

Note: You can freely use and distribute the caching system developed in this code. Though using it in production system is not advisable. :-).

As and always I intend this post as a launching platform for collective learning, feel free to drop in a comment or two about what you feel about AOP and how you to plan to use it in your code. Happy reading.

Regards

Niraj

References

  1. http://docs.spring.io/spring/docs/3.0.x/reference/aop.html
  2. http://docs.jboss.org/aop/1.1/aspect-framework/userguide/en/html/what.html
  3. http://stackoverflow.com/questions/9059708/what-are-the-major-frameworks-libraries-for-java-aop
  4. http://www.ibm.com/developerworks/library/j-aopwork15/
  5. http://stackoverflow.com/questions/2197051/aop-use-cases
  6. http://forum.spring.io/forum/spring-projects/aop/74811-listing-a-number-of-good-uses-of-spring-aop

 

Print Friendly, PDF & Email
Posted in Enterprise Java, Spring AOP | Tagged , , | 1 Comment