Pages

Friday, August 31, 2012

Spring 3 security login example with database help

dependencies
spring 3.x  standard library
spring security web
spring security core
spring security config

First create a mysql database called loginexample. The sql code is as following.

CREATE TABLE `users` (`USER_ID` INT(10) UNSIGNED NOT NULL,`USERNAME` VARCHAR(45) NOT NULL,`PASSWORD` VARCHAR(45) NOT NULL,`ENABLED` tinyint(1) NOT NULL,PRIMARY KEY (`USER_ID`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `user_roles` (`USER_ROLE_ID` INT(10) UNSIGNED NOT NULL,`USER_ID` INT(10) UNSIGNED NOT NULL,`AUTHORITY` VARCHAR(45) NOT NULL,PRIMARY KEY (`USER_ROLE_ID`),KEY `FK_user_roles` (`USER_ID`),CONSTRAINT `FK_user_roles` FOREIGN KEY (`USER_ID`) REFERENCES `users` (`USER_ID`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO users (USER_ID, USERNAME,PASSWORD, ENABLED)VALUES (100, 'madhumal', '123456', TRUE);

INSERT INTO.user_roles (USER_ROLE_ID, USER_ID,AUTHORITY)VALUES (1, 100, 'ROLE_ADMIN')

INSERT INTO users (USER_ID, USERNAME,PASSWORD, ENABLED)VALUES (101, 'user', '123456', TRUE);

INSERT INTO user_roles (USER_ROLE_ID, USER_ID,AUTHORITY)VALUES (2, 101, 'ROLE_USER')

Note that we have two user roles, admin and user.

Create a Dynamic web project with the name SpringLogin

create your mvc-dispatcher-servlet.xml in WEB-INF folder

put the following code in there

Wednesday, August 29, 2012

What is failover?

what is failover?

In computing, failover is automatic switching to a redundant or standby computer server, system, hardware component or network upon the failure or abnormal termination of the previously active application,server, system, hardware component, or network. Failover and switchover are essentially the same operation, except that failover is automatic and usually operates without warning, while switchover requires human intervention.


How ever when the main server recovers, requests are then again sent to the main server.

There are 3 main type of fail overs
  1. clod failover : Should do manually
  2. warm failover : failover happens automatically. But the transaction may abort due to the failure of data synchronization.
  3. hot failover : happens automatically. Data synchronization also happens. Therefore can continue operation without a problem. 

spring jdbc template with mysql

Required Libraries are,

commons-logging
spring-jdbc
spring-beans
spring-core
spring-tx
spring-asm
mysql-connector-java
spring-context
spring-context-support
spring-expression

You can do this simply by using maven. Just google maven dependencies for spring jdbc template and put the dependencies in your pom.xml file and you are good to go.

Let's see how to use jdbc template in spring to communicate with mysql database.

Create a model class named Book.


package mad.library.form;

public class Book {

private String name;
private String author;
private String category;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}

}

Now create the BookDataManager class as following.

Sunday, August 26, 2012

Java Persistence API

What is persistence?

The general objective of persistence is to increase the life span of an object. This could be done by storing it in a disk, file etc... One simple method is to store the object in xml format. Another way of implementing the persistence is to use the databases.

Why do we need JPA?

If you consider about databases, usually it is used in the form of tables that are related in the traditional relational methods. How ever on the other hand objects are entities that has states and can invoke methods that makes it unique. So there is some conflict in objects way of keeping data and keeping data in databases.  JPA is introduced to fulfill this inadequacy.

Java Persistence

The Java Persistence Architecture API is a java specification for accessing, persisting, managing data between java objects, classes and databases. It is considered as the industry approach for object relational mapping (an ORM). That is it helps to retrieve data from the data in the form of java objects. This simplifies the life of a java developer significantly. 

However JPA  is a standard for the java persistence. Probably most of you must have heard about hibernate. Hibernate is a vendor implementation of the JPA and addition to that it provides some additional non JPA facilities as well.

Friday, August 24, 2012

proxy design pattern using java

what is proxy design pattern?
It is a design pattern that uses a proxy to control access to another object. What is the meaning of proxy? It means acting something on behalf of something. In this case, the client access an object through proxy.
So to what kind of objects do we need to provide a proxy?
Usually for objects that takes a lot of memory, files, resources that are expensive or hard to duplicate.

Below a simple implementation of the proxy design pattern.

Interface Game{
   void playGame();
}

public RealGame implements Game{

    private String game;

    public RealGame(String game){
         this.game = game;
         loadGame(game);
    }

    private loadGame(String game){
           System.out.println("loading game : "+game);
    }

    public void playGame(){
         System.out.println("playing game: "+ game);
    }
}

public ProxyGame implements Game{

     private RealGame game;
     private String gameName;
     public ProxyGame(String game){
         this.game = game;
   }
 
   public void playGame(){
      if(game==null)
           game=new RealGame(gameName);
      }
      game.playGame();
}



public DemoProxy{

   public static void main(String[] args){
       Game proxyGame = new ProxyGame("modern warfare");
        proxyGame.playGame();
   }
}

Thursday, August 23, 2012

Facade Design pattern in java

Facade design pattern is a pattern that is used to provide a simple interface to a large amount of code. This makes it very easy to use libraries in programming language. The following example is taken from http://en.wikipedia.org/wiki/Facade_pattern.


/* Complex parts */
class CPU {
public void freeze() { ... }
public void jump(long position) { ... }
public void execute() { ... }
}

class Memory {
public void load(long position, byte[] data) { ... }
}

class HardDrive {
public byte[] read(long lba, int size) { ... }
}

/* Facade */

class Computer {
private CPU cpu;
private Memory memory;
private HardDrive hardDrive;
public Computer() {
this.cpu = new CPU();
this.memory = new Memory();
this.hardDrive = new HardDrive();
}

public void startComputer() {
cpu.freeze();
memory.load(BOOT_ADDRESS, hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
cpu.jump(BOOT_ADDRESS);
cpu.execute();
}
}

/* Client */

class You {
public static void main(String[] args) {
Computer facade = new Computer();
facade.startComputer();
}
}

Tuesday, August 21, 2012

Flyweight design pattern in java

fly weight design pattern is a structural patterns used to improve memory usage and performance. Here, instead of creating a large number of objects, we reuse the objects that are already created.

Lets say we have a MathHelper interface and has doMath method.

public interface MathHelper{
   void doMath(int a , int b);
}

Let's implement two classes that implement MathHelper.

public class Multiplier implements MathHelper{
  @override
  public void doMath(int a , int b){
      System.out.println(a*b);
  }
}


public class Adder implements MathHelper{
  @override
   public void doMath(int a , int b){
      System.out.println(a+b);
  }
}


Now we have the factory class that limits creating the objects.

public class FlyweightFactory{
 
    public FlyweightFactory(){
       Map<String,MathHelper> map = new HashMap<String,MathHelper>();
   }
    public static MathHelper getHelper(String val){
      if(map.containsKey(val))
          return map.get(val);
      if(val.equals("add"))
          map.put(val,new Adder());
     if(val.equals("multiply"))
          map.put(val,new Multiplier());
  }
}


Now the main method in the demo class is like this.
public static void main(String[] args){
   MathHelper helper = FlyweightFactory.getHelper("add")
   helper.doMath(2,3);
}

serialize and deserialize an object with java

We usually use serialization, when we need to store an object with the state to a storage medium so that we can use it later or when we need to transfer an object through the network.
Now lets see how to serialize an object to a file.


ObjectOutputStream o = new ObjectOutputStream(new             FileOutputStream("file.ser"));//saving to a file named file.ser
o.writeObject(ObjectToSerialize);//writing the object
o.close();

Now lets see how to deserialize the saved object.


        FileInputStream fileIn =
                          new FileInputStream("file.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
        try {
            dictionaryMap = (ObjectType) in.readObject();//add cast
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Dictionary.class.getName()).log(Level.SEVERE, null, ex);
        }
            in.close();
            fileIn.close();

Saturday, August 18, 2012

Port 8005 required by Tomcat v7.0 Server at localhost is already in use

Well this error message is thrown when another instance of tomcat is running. Basically the Tom cat server requires the ports 8005,8009,8080 by default. Therefore you need to stop the instance in order to run the server. Also it may happen due to, if some other program is using the particular ports. Therefore you need to resolve the port issue to proceed.

How to install tom cat on ubuntu

You can do this in two ways.

  1. Install using : sudo apt-get install tomcat7
  2. You can Install manually which is straight forward. download tomcat 7 binaries from http://tomcat.apache.org/ and extract it to a location you want and go to the bin folder in your extraction using the terminal.  Then type
                                                                             sh startup.sh : to start the server 
                                                                             sh shutdown.sh : to down the server

after you start up the server, you can access the server at the port 8080 (which is the default port for tomcat).

How ever the tomcat server is some what considered light weight compared to servers like glassfish, jboss etc... Therefore if you consider having a server with all the capabilities and features of java, it is better to use a server like glassfish.

Unit testing with java.

First question is what is unit testing?
Well unit testing is a code written by a programmer to test a specific functionality of a program.

Now the question is how can we do this in java? 
There are some libraries in java that helps unit testing. How ever the most popular and the common library used is the JUnit. Actually it is a framework that uses annotations to identify the test methods. Also one thing to remember is JUnit assumes that the tests can be conducted in an arbitrary order. That is the tests we write should not depend on each other.

Setting up JUnit.
You can download JUnit from http://www.junit.org/ and add the junit.jar to your project and classpath.

Using Junit
Create a java project using eclipse. Then right click on the project and create new->source folder and name it as test.
Now create a package inside the src folder and create a class named MyClass inside the package.

Enter the following code inside the MyClass.

public int divide(int x, int y) {
   return x * y;
 }

Now right on the MyClass file and create new->JUnit Test. change the path from src to test in the screen you get after choosing JUnit Test in the menu. Name the file to MyClassTest. Now click next and choose the methods to be tested. click finish.

Now you will see a class called MyClassTest inside test folder. You will see something like below in the class.


@Test
public void testDivide() {

}

Now put the following code inside your testDivide method.


 MyClass tester = new MyClass();
assertEquals("Result", 2, tester.divide(10, 5));

Now right click on the MyClassTest file and run as junit test. You will see a red bar as the result. This is because the result should be 2 but it returns 50. Now correct the code in divide method inside MyClass and rerun the unit test. You will see a green bar. That means the test is ok.

You can create a test suit also. That is you can select several tests and run all the selected methods.


 Now select the Test classes and right click on it. Then new->other and then use Junit ->test suit. Fill the parameters according. After finishing, you will see the Test suit class is created. If you run the file, all the mentioned tests will be run.

Now lets see how you can run tests using your code.
create a class called MyTestRunner inside the test source folder. Then put the following code inside it.

public static void main(String[] args) {
   Result result = JUnitCore.runClasses(MyClassTest.class);
   for (Failure failure : result.getFailures()) {
     System.out.println(failure.toString());
   }
}

Now you will see if there are any errors in the test.

There are some annotations like @Test , @Before, @After, @AfterClass , @BeforeClass, @Ignore, @Test(timeout=100) , @Test(expected=Exception.class). Google and find what these annotations are used for.



Sunday, August 12, 2012

What is a java factory method ?


Java Factory Method is a creational design pattern used by java developers. what it basically does is it instantiates objects from a set of classes by considering a certain logic. That is creating an object without specifying the exact class of object that will be created. This is quite simple. Let's see how we can do this.

Say for an example we have a shape interface

public interface Shape{
      void drawShape();
}

Now lets say we have two classes that implement the interface called Triangle and Square.


public class Triangle implements Shape{

      public void drawShape(){
         System.out.println("drawing three points and joining them");
     }
}



public class Square implements Shape{

      public void drawShape(){
         System.out.println("drawing four points and joining them");
     }
}

Now lets create the ShapeFactory class that is used to instantiate a shape.

public class ShapeFactory{

    public Shape getShape(int numberOfEdges){

               if(numberOfEdges==3)
                     return new Triangle();
               if(numberOfEdges==4)
                     return new Square();
          return null;//just to make the compiler happy ;)
    }
}


Now let's see how to create a new square or a triangle. create a new class ShapeManager.

public class ShapeManager{

    public static void main(String[] args){
           ShapeFactory factory = new ShapeFactory();
           Shape triangle = factory.getShape(3);//note that the object will be a triangle since the //parameter is 3
    }
}


This is simply what happens in a factory method. You do not directly call "new"
 key word to create an instance of shape. Instead you use a factory method to get an instance.

Java UnsupportedClassVersionError

This exception is most likely to be thrown when you compile the program from one version of java and running it on another version of java.
Eg : You compile the code using jdk 7, 6 etc... and run on version 4.

Thursday, August 9, 2012

Maven building and compiling the first App

In the last post I described how to set up maven in linux environment. Now let's see how to create a project structure, compile, package and install.

First open a terminal, then make a directory called TestAppDir and go to the folder. 
  • Now type in the terminal:  mvn archetype:generate Note that when you run this command for the first time it will download the dependency jars and pom files. Now this command will show you a list. The list contains various architectures (spring apps, hibernate etc...).  Lets not input anything and press enter (This will generate a folder structure with default archetype).
  • Now you will be asked the following
Choose org.apache.maven.archetypes:maven-archetype-quickstart version: 
1: 1.0-alpha-1
2: 1.0-alpha-2
3: 1.0-alpha-3
4: 1.0-alpha-4
5: 1.0
6: 1.1

Enter 6 (Latest version). If you run this for the first time this will download the dependencies as well.

Then you will be asked to fill the following


Define value for property 'groupId': : mad.maven.test
Define value for property 'artifactId': : MadTest
Define value for property 'version':  1.0-SNAPSHOT: :
Define value for property 'package':  mad.maven.test: :
Confirm properties configuration:

the values mad.maven.test is given by me and it is like the package name in a normal program. The name I have given for the artifactId is MadTest. So when you package the app, it will  be like MadTest.jar. version refers to the version of the app you are creating. in the test package, you can write all the test cases. 

Now you will see a directory called MadTest in side TestAppDir. Now go to the MadTest directory. There you will see a pom.xml open it using a text editor. You will see something like below.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>mad.maven.test</groupId>
  <artifactId>MadTest</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>MadTest</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

The group id, artifact id, version, name are given by you. Packaging tag indicates the type of file you will get after packaging the app. If you have war, it will package app in to a .war file. All the dependencies are mentioned inside dependency tags. By default maven will include junit as a dependency to run unit tests in the test directory within your app.

Now go back to the MadTest directory.  You can enter below commands


  • mvn compile : This will compile your code.
  • mvn test : This will run the unit tests in the app
  • mvn package : This will package your app in to a file you specified in the pom.xml file. In this case it is a .jar file.
Now let's say you need you put a logging code inside your source code, like

Logger logger = LoggerFactory.getLogger(App.class);
        logger.info("Hello World !!!");

Now to work this code you need slf4j jar as a library and import it in the code. 
put,
import org.slf4j.*;

Now with maven, you do not need to download manually and put it in the libraries. Instead go to 


and put slf4j in the search box. Then go to the SLF4J Api module link and choose the version you want and click on the version number. If you choose 1.6.6, you will see something like below in that page.

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.6</version>
</dependency>

put this code inside dependencies tags in your pom.xml.
Then in the terminal go to the MadTest directory and type mvn compile. Now the dependent slf4j will be automatically be downloaded at the compile time. Then type mvn package. Now you will see the jar file in the target folder.

Now if you type mvn install in the terminal from the same directory, the app will be available in your local maven repository.

Wednesday, August 8, 2012

How to operate with big integer, big decimal

Sometimes the range of long, double  etc... becomes inadequate for certain mathematical operations. So  java provides a way to handle this problem by introducing BigInteger and Bigdecimal. These are very useful when the programmer needs to calculate big values.  Below examples shows how to work with big integer and big decimal.

First lets see an example of big integer.

BigInteger b1  = new BigInteger("293847293847938798");

BigInteger b2  = BigInteger.valueOf(1298L);
b1 = b1.add(b2);
b1 = b1.subtract(b2);
b1 = b1.multiply(b2);
b1 = b1.divide(b2);
b1 = b1.negete();

int exponent = 3;
b1=b1.pow(exponent);

Now lets see an example of big decimal.

Bigdecimal b1  = new Bigdecimal("348950394.943859438");

Bigdecimal b2  = Bigdecimal.valueOf(1298L);

b1 = b1.add(b2);
b1 = b1.subtract(b2);
b1 = b1.multiply(b2);
b1 = b1.divide(b2);
b1 = b1.negete();

An introduction to maven : How to setup maven manually

Maven is a built tool like ant. It is mainly used in building a program and project management. First the question is why do we need maven? below are some of the reasons to why we need maven.

  • It is very much likely that a program use jar libraries. We need to make sure these jars are available at the compile time, when bundling the program. Maven helps us in this regard.
  • Another problem is dependencies. A jar in the program may require another jar. May be the jars needed may need to have specific versions. This can be handled using maven.
  • To set a project structure, we can use maven.
  • To build, publish and to deploy.
Second question is how to set up maven? This is described below. This is very easy.
  • download maven from http://maven.apache.org/download.html
  • Then extract it to some location
  • open a terminal and type:           export MQ_HOME=/home/madhumal/apache-maven-3.0.4
  • Then type:                    export PATH="$PATH":/home/madhumal/apache-maven-3.0.4/bin
  • Now type :                    mvn --version
  • You will get the maven version and that is it. Not that the MQ_HOME is the path where you extracted maven binaries.
Alternatively the NetBeans IDE has inbuilt support for maven as well.

I will post more about maven in later posts.

Saturday, August 4, 2012

Aspect Oriented Programming with spring

In software programming, we meet cross cutting concerns in out app. Security, transaction handling, logging are examples to some of those. So Aspect oriented programming focuses on handling these concerns.
First of all why is it not okay to use a separate class or something to handle these concerns? For example why not logging with a class?

Well there are mainly 3 disadvantages 

1) We have to call methods using references to the class we created. - In logging we will be creating a logging object and calling a method within it when we need to use logging. Now say you modify or remove the logger class, then you will have change a lot of code in your program where you called the methods in the logger class. So it's a lot of mess for one little thing.

2) Too many relationships to the cross cutting concerns - You will have too many relationships to the logger class by referencing it from other classes. In the case of logger, it will be having too many relations from other classes. We do not want that. Simply because logger does not add a lot of business value to the program but only a helper.

3) cannot change all at once. - you will have to change codes in each and every class.

So how are these concerned solved?

Well we handle these by creating aspects (For the moment let's say aspect is a class with special privileges) like and aspect for logging, another for security, and another for Transactions etc...
Now how do we apply these aspects to the code? We do not create objects and call methods from other classes where the aspect is needed. Instead, an aspect configuration is created.
Now the question is how does the configuration handle it? well the configuration contains where to which classes and methods in the program the aspect should be acted upon. Therefore in a way, the aspect configuration is something that glues the aspects and the business logic objects together.


Eg: Say you need to call a security method in classA and classB. What you do is first create the security aspect and implement the methods. Then create classA and classB. Then create the aspect configuration. The configuration says to which methods in classA and classB, the methods in security aspects needs to be called for. It can specifically say which methods in security to call for a certain method in classA , which methods to call for a certain method in classB. aspects can be applied before or/and after the methods.

So if you want to do a bulk change, you can just chang the aspect configuration instead of changing everywhere.

Friday, August 3, 2012

Spring JSR 250 annotations

Below are some commonly used annotations in spring

1) resource annotation

@Resource(name="someBean")
public void setProperty(somebeantype property){
   this.property = property;
}
Here the @Resource annotation is used to locate the resource. The property is set using the .xml file and it should have a bean named "someBean". If the parenthesis and the arguments within it is not given with the annotation, then spring looks for a bean named in the xml file as the same name as the property. If not found you will get an exception.

2) required annotation.

Say you need to set a certain property when you initialized a bean and it is a must. Then you can add the @required annotation for the set method. In this way if the property is not set or the setter is not called for, Spring gives the exception even before running the business logic (That is in the initialization phase).

@required
public void someSetterMethod(Obj obj){
   this.obj  = obj;
}

3) post processor annotations.

@PostConstruct
   You can use this annotation to call a method just after the construction of a bean.

@PreDestroy
   You can use this annotation to call a method just before the bean is destroyed. This will be useful to do some clean up work.

Spring writing a bean post processor

BeanPostProcessor is an interface in Spring which helps the java developer to do some work when each an every bean is initialized. It does not matter weather you have one bean or many. The post processor acts on all of the beans.

First a class that implements the BeanPostProcessor should be created. The BeanPostProcessor implements two methods. One which does work before initializing a bean and another which does work after initializing a bean.

public class MyBeanPostProcessor implements BeanPostProcessor{
        //two methods that the BeanPostProcessor goes here(Use the ide to get the methods)
        // arguments in the methods are the bean itself and the name of the bean
}

Then you need to declare the implemented class in the xml file as a bean

<bean class="package.MyBeanPostProcessor"  />

Note that we have not used an id or a name for the bean. This is because the bean only needs to be declared in the xml file and is not used in any other bean.


Another post processor that is used in spring is the BeanFactoryPostProcessor which does work when the bean factory is initialized. The procedure is same as above except that this time the class extends the BeanFactoryPostProcessor.

One example for a BeanFactoryPostProcessor is the PropertyPlaceholderConfigurer in spring framework.
 You can store values in a filename.properties file and these values can be used in properties of a bean by using the PropertyPlaceholder.






Thursday, August 2, 2012

life cycle call backs of Spring framework

Lets say you need to keep track of life cycle call backs of spring beans.

The first point is if you want to destroy all the beans you created using a certain context, then you need to get the AbstractApplicationContext type of context Object. Then by calling registerShutdownHook method on the instance, all the beans that are created using that context instance is destroyed when the method is finished executing.

AbstractApplicationContext context = new ClassPathApplicationContext("spring.xml");
context.registerShutdownHook();

If you want to do something after the properties are set in a certain bean, you need to implement the InitializingBean interface in the class. The interface implements afterPropertiesSet method.

if you want to do something just before the bean is destroyed, you need to implement DisposableBean interface. The interface implements destroy method and there you can include any cleanup codes.

public class Vehicle implements InitializingBean, DisposableBean{

     public void afterPropertiesSet() throws Exception{

    }
    public void destroy() throws Exception{

   }
}

Another way of handling the life cycle of a bean is to mention the methods in the bean tag

<bean id="car" class="org.Car" init-method="myInit" destroy-method="destroy" ></bean>
Now spring looks for the myInit when initializing and destroy method after finishing in the bean class.

Instead of doing the above we can do the following

<beans default-init-method="myInit" default-destroy-method="destroy" >

As above the default methods can be metioned in the beans tag which covers all the beans. However if the method is not found in the corresponding bean class, then spring will just ignore it.

If we use both the methods together, then the priority goes to the interface implementation. That is interface methods are called first and then the spring configuration methods gets called.