September 29, 2009

FrameWork: Spring-JPA-Hibernate (Annoation Based)

Filed under: Architecture,Java,JEE — khangharoth @ 4:56 pm

This skeleton web framework I wrote for Quarks , as they wanted a core framework on top of which they can build the applications.

As I had a luxury to design a Framework from scratch and so decided with these technologies.This dev stack is now becoming a vary dominant framework or to say in developers words “The next Popular Stack”.

Testing env I have used in this framework is TestNg , which I feel is much more suited to present day testing needs than our old JUnit(even after realese of Junit 4).

And with JDK 5+ , Spring 2.5+ which give support for Annoatations , you can have a very Simple yet very powerful framework to work with.So with this what we have is

  • Spring as a Application Framework
  • JPA as Persistence Framework (Hibernate as JPA impl)
  • Annotation based Transactional Control.
  • Spring Dependency injection with Annotation.
  • Spring MVC : This can be changed if you want to use something else.
  • Annotation based Validation framework.

These all elements give us enough power to create a generic and robust framework ,which can be customized for various needs.

Now let’s get to the actual work ……

Core Design Principle : The whole framework is desigend in Layers.Each Layer can only be called by layer above it and no skip hierarcy call’s are allowed.

Various Layers are

  • Web : Comprises of Spring MVC & JSP , this is due to the fact that most developer in quarks are quite familiar with JSp and so we wanted to start with this.Although I am not really happy with technology choice and wanted to have GWT or Flex based GUI.
  • Delegate : This is logical seperation between Web(Front End) and Service (back End).If you think that GWT or you something else suits you then this is the place where you should take a detour.
  • Service : Spring based beans, annotation based Dependency & Transaction management.
  • DAO : Db access layer , based on JPA and using hibernate as Persistence provider.
  • Persistence Domain model : Java Beans on lines of JPA Entities.

So the principle is that a layer can only call layer below it so in this Web —-> Delegate and any call direct to say services or DAO’s should be discourged.

Another way to see this is that if we just delete a particular Layer then code below it should compile just as fine without any problem.

I wanted the package structure to reinforce this idea  .Also its easier for a new person to see as how the packages are organized . The package structure is

  • com.quarks.a.web.controller
  • com.quarks.b.delegate
  • com.quarks.c.service
  • com.quarks.d.dao
  • com.quarks.e.persistence

Used a,b,c,d,e so that packages are shown in order in project view and aslo it gives clear idea of dependency in project.

Now looking at this I can easily say that DAO is only dependent on persistence pacakge.

Note : Still in edit , I’ll upload code as well . Please do give your valuable opinion about how can we have a Generic framework on this Dev Stack .

August 23, 2009

Generating Java Code on the fly!

Filed under: Java,JEE — khangharoth @ 3:31 pm

Currently I am working on a Grid based Cache (Coherence) in my regular job.

The concept is that differenct System can just use the Cache and do the stuff and its very easy and fast to share information.No XMl’s being excahnged and no bickering on XSD’s etc.

The thing  is in this process we were end up writing so much similar code for Serialisation purpose (PofSerialisers) and thought the this code can be auto generated.

And with this thought in mind when we looked at the problem that our Cluster needs to support various version of our core Domain model ,let me explain this problem better :

Let’s assume we have a class with 2 attribute and we call this versionV1 so we have T-V1.Now some new attributes are added and we have T-V2 and henceforth.But its very likely that some clients of this Cluster would not like to upgrade and would still be using T-V1 .


To code and maintain multiple versions of Data model is big task and so we decided to go ahead with concept of auto-generating the java code giving a schema file.

This is the first time i am doing something like this.Its ok to generate Stubs/Skeletons which we use in Web-Services to get auto generated but to use auto generated domain objects and this is used everywhere in project is something first time for me.

So initally our project just have Classes having business logic and these are not compilable becuase all domain classes which they use are just not their ! and when we invoke compile goal of Maven pom file ,these domain classes get generated with their Serialsers and now we have fully fuctional code 🙂 which can be deployed.

October 13, 2007

AspectJ aspect configured by Spring

Filed under: Java,JEE — khangharoth @ 9:34 am

Today i came across a peculiar problem and more importantly it hit me in my face ,the integration tests were breaking and result of this were mail’s flying all across.

We are having a Web-Service which web-client calls and in the server side we are using spring as application framework.We were using aspect of AspectJ for some purpose and it needed certain properties which were available in spring.xml,so we thought to configure the aspect from spring.

Now just to quote a citation

Now I’d like to configure my aspect with a particular exception handling strategy using dependency injection. For this, I can use the standard Spring approach, but with one caveat. Normally Spring is responsible for both creating and configuring beans. AspectJ aspects, however, are created by the AspectJ runtime. I need Spring to configure the aspect that AspectJ has created. For the most common case of singleton aspects such as the RemoteExceptionHandling aspect above, AspectJ defines an aspectOf() method that returns the aspect instance. I can tell Spring to use the aspectOf() method as a factory method for obtaining the aspect instance. Listing 2 shows the Spring configuration for the aspect:

Now what i mistakenly did was put this line of code in my spring.xml.

And everything was fine in Unit-testing and functional level testing.But as soon as client tried to generate the proxies from WSDL,their were number of proxies getting generated which were not even part of our WS interface.

After debugging , i got the cause of  those extra classes in WS interface.As sprin AOP is proxy based framework and it was this that was creating those extra proxy classes.

Need to get more into Spring AOP and how it is different from AspectJ.

October 9, 2007

Overview Of ORM : Hibernate

Filed under: Java — khangharoth @ 8:38 am

I have to give a presentation on ORM and then coming down the days more light on Hibernate.

So the theme across my series of presentation would be first addressing some basic questions about ORM .

q1) What is the problem that ORM solves?

q2) Magnitude of Object-Relational paradigm mismatch.

q3) How people survived before ORM concepts.

q4) How those efforts of traslated to many home-grown ORM frameworks.

q5) Industry wide available ORM solutions.

q6) Why to choose hibernate among all these.

And subsequently moving into internals of Hibernate .

Note:Presentation don’t have much text,if you need full transcript then do contact me.

ORM OverView :Hibernate

September 26, 2007

Tutorial: Profiling With AspectJ

Filed under: Java,JEE — khangharoth @ 8:00 am

Just to have background about what is Aspect Oriented Programming :Well we are in Object Oriented programming world.

Everything is object and concepts of OOP’s can applied very easily.Things are easy to maintain as things are very well encapsulated under objects and hence code changes are easy to implement and maintain.

This happens because each Object has a specific task ,and in well written OOP’s code change in some functionality involves changes at few places or to say only concerned objects change.

This is generally applicable for Business requirements which can be easily modularized,but what about the cross-cutting concerns.

Cross-Cutting Concerns: The concerns which are to be taken care of ,in almost every part of code or in other words,code for these concerns is scattered all around the code base.In short these requirement cross-cut at many places and hence regular concepts of OOP’s are not very useful in handling them.

These are generally requirements not specified by the user , but are needed for over-all well being of the projects.

So what are these kinds of requirements:

  • Security: Security checks may be need at each and every class.
  • Logging: Logging is a typical example of cross-cutting concerns.
  • Profiling:Need to know bottleneck in the system,so typically present at everywhere.

Now as this type of code will scattered everywhere in the main code.Other then reason’s like maintenance etc ,it also reduces the code readability and make code ugly.

We imagine if you have to change something ,then we need to go and change thousand’s of classes,ex:If we decide to change the way logging has been implemented,then probably we will need to open each and every file in the project and do the change.And we all know changes are the main cause of getting infected with new bugs.So again the goal is to minimize the effect or localize the effect of change.

Q)So how these cross-cutting features come’s into play?

A) We define pointCuts:These are basically some conditions which when fulfilled starts the magic.

so a pointcut in annotation will be defined as @Pointcut(“execution(* com.model.service.EmployeeService.*(..))”)
public void employeeService()

This means employeeService pointcut is applicable to all methods of com.model.service.EmployeeService implementations.

for specific methods we write like

@Pointcut(“execution(* com.model.service.EmployeeService.doSomeStuff(..))”)
public void doSomeStuff()

This pointcut will pick only this specific method.

And then you define advice where you define actual code about what you want to do,advice is then linked to a pointcut.

public void methodEnter(JoinPoint pjp )
Object obj = pjp.getTarget();
LOG.debug( “[” + obj .toString + “] ” );


So suppose we need to introduce logging into our existing code-base.What are the steps needed?

  • Define  pointcut’s  specifying where these should be invoked. You can use wild-cards and this make pointcut definition very powerful.
  • Define an advice as what needs to be done when program flow reaches these pointcuts,i.e our logging code. Now it should be very clear as how we have modularize the cross-cutting concerns.No more we have code like Log.Debug all across out code-base.
  • We also has to define as which kind of advice it is.It means when this advice code will get executed.                                                 1) @Before :Runs before the actual method starts running,just after the arguments to the method call are evaluated.                                                                                                                                                                                                             2) After: similarly we have @AfterRetruning,@AfterThrowing and simply @After which is like finally i.e no matter how the method returns ,it will run.

In the example ,the goal is to try and have profiling enabled in the project.Its a very crude profiling which just logs how much time a method takes.

To run this example just create a new AspectJ project in Eclipse,and paste the code in corresponding java files. is the one which have main method,also if eclipse you can see a nice Cross-Refrence view as which aspect is advising whom or other way round.

Note:Looking out for your comment’s!

August 16, 2007

DbUnit : Testing with Database

Filed under: Java,JEE — khangharoth @ 7:49 pm

I moved to a big investment bank and now in a transition state from Java Graphics , Java3D , Xith3D …etc etc to JEE stuff ,and boy things have changed and that too drastically its surely more than 2 going away from J2EE.

One of good things working in a financial firm is emphasis on Testing:All sort of testing ,unit-Test,integration -test ……after all all those number are money and you won’t be very pleased if some java operation just truncate the decimal part of a number which happens to be your money value or worse some multiplier which magnifies the effect.

In middle of all this wonderful journey i came across a very good tool: Don’t get me wrong ,i know we already have more tools than work in hand.But this one is easy to use and come’s very handy if you are already accustomed to Junit.

Basically its a utility framework which helps you in testing of Database-Driven Projetcs :

  • Extension of Junit.
  • Helps you to put the database into a known state between test runs.
  • A database can be seeded with a desired data set before a test ,moreover ,at the end you can put it into pre-test state.

Rest you can see in this ppt: Its a good one and i have got this one from internet. DbUnit : Testing with Database


June 7, 2007

Java Gyan : Making Java Simple

Filed under: Java — khangharoth @ 1:14 pm

I am trying to come up with a web-site about Java .Why a new one when their are already so many of them available?Well the answer lies in the fact that i have done teaching (Physics teaching for IIT entrance) and found that experience very different.

What i learn in those 4 years as a Physics teacher is

  • Its a learning process for both student as well as Teacher.
  • As a individual you get to live so many lives.You share your students aspirations,fears.It just make you feel younger.
  • Its not a easy task if you are doing your part sincerely as you keep on coming up unexpected question which you have never thought of.
  • Students do respect teachers if he knows his subject.
  • Having knowledge and imparting it to others are two different things.Great players do not always make great coaches.

Coming back to the question of why a new web-site : Its just my efforts to explain things in simple words so people coming from different backgrounds in software industry finds the transition more smoother.

I’ll be very delighted if you can  give suggestion about it should be like!

May 16, 2007

Java Collection :When to Use Which

Filed under: Java — khangharoth @ 3:26 am

This is a presentation made by Divya and Devendra in fresher training at Eigen under me ,Our main aim in this presentation was to dig on Java Collection framework.

One of the thing that i found missing on almost all tutorials on net and in available book’s is some simple strategy to make a choice about which Data-Type to use.What i have seen is most of us only read about all these but in projects we just use one or two data structure say ArrayList ,even if we are adding and deleting the list often than search functionality.

I was just going through this and thought that it will be good idea if other can also view and give their inputs.The idea is to make this template some sort of guideline for choosing a particular data structure in Java.


This is basic flow diagram,go through the ppt and do comment on how to make it more Useful.

Note:Vector are missing in this ppt , should have been part of it.


May 15, 2007

Encryption of Password in Java

Filed under: Java — khangharoth @ 4:31 am

If you are developing a web application and managing User session on the basis of User password.With the traditional way of storing of storing user password as it is in a Db table is not very elegant.Anybody who has the access to Db can get those passwords .This problem is more acute than it seems as most of the Users keep same Login-Id and Password.

So in era of Outsourcing and remotely managed servers and with traditional method of storing password you can never be sure who all are peeking into the User information.

One very simple solution can be to encrypt or in technical terms  to generate a Hash-Key corresponding to the User entered Password and store this i database.When User login again,than take the entered value ,convert into Hash-Key and compare it with value in Db for authentication.

This is very simple yet powerful way,if your application demands more security than you must probably look Jasypt  .


May 12, 2007

MultiThreading Programming In Java.

Filed under: Java — khangharoth @ 9:57 am

Let’s first understand Concurrency :Concurrency is a property of Systems in which several computational process are executing at the same time and potentially interacting with each other.

Concurrency may be physical ,if each unit is executed on a dedicated processor.Its also called true concurrency. If your system has only one CPU ,than it can’t perform true concurrency.Now we have multiple CPU’s in mainstream systems,and these systems are capable of Parallelism or true concurrency.

Concurrency can be logical,If you have single processor system than this is what your system does.Concurrency is just a illusion created by CPU.CPU can execute only one of the programs at a time. The OS maintains the illusion of concurrency by rapidly switching between running programs at a fixed interval, called a time slice. The time slice has to be small enough that the user doesn’t notice any degradation in the usability and performance of the running programs, and it has to be large enough that each program has a sufficient amount of CPU time in which to get useful work done.

So with these basics now let’s move towards more concrete.

Processes (Program) & Threads

  • Process: Is a self contained running program with its own address space.Typically two process share very minimal data,not more than filename etc.Or we can say sharing of data variable is not their.Typical processes on your system are Window Media Player,Outlook,Eclipse etc.These are processes which have their separate memory area and sharing is minimal between them.
  • Operating System is capable of switching the CPU from one process to another ,giving a feel that Media Player and eclipse are running simultaneously.If you are still not clear that perhaps TV analogy will help.In TV ,static images are refreshed on screen so fast that to human mind it appears continuous.
  • Thread or we can say Light-Weight process are concurrent Units which share a single address space.So sharing of data is very common and high.

I think now the difference between a Thread and a Process is clear.Just to make it more clearer:

  • Threads are lightweight compared to processes.
  • Code and Data sharing is easily done in threads as they share same address space.
  • To put in proper perspective , A process can be single threaded or multi threaded.

Its the O.S which switches between various processes and various threads in a single process.Their are different models to achieve this

  • Preemptive multitasking. In preemptive multitasking, the operating system decides how to allocate CPU time slices to each program. At the end of a time slice, the currently active program is forced to yield control to the operating system, whether it wants to or not. Examples of operating systems that support preemptive multitasking are Unix, Windows 95/98, Windows NT and Mac OS X.
  • Cooperative multitasking. In cooperative multitasking, each program controls how much CPU time it needs. This means that a program must cooperate in yielding control to other programs, or else it will hog the CPU. Examples of operating systems that support cooperative multitasking are Windows 3.1 and Mac OS 8.5

Modern O.S generally use preemptive model so your running thread can loose control at any point of time even in some simple assignment statements which seems atomic.Its a very important concept to be learned that a thread can loose control at any stage and will start from that point when again its turn will come.Their are some guaranteed atomic operations in java .

We want to start a new thread when we have a piece of code which can run independently .If done correctly it results in better user experience and also increased performance. To better understand need of multi threading in normal programming lets take an very common example.

Example:Suppose we have a Swing Gui and its displaying a list of Employee’s name and in front of each name their is a button “Get Details”.On click of a specific button ,application picks the corresponding name and retrieves all data related to that employee for display. On Click of button ,action perform method will be called and from this we can make a database call ,gets all the data and than populate the Gui.The catch here is ,action perform method is called by Swing Event Thread.And if we make database call from this thread itself ,till the time our work is complete ,it won’t be able to perform its other responsibility like painting/repainting and firing events.Now if the application task takes too much time (500ms) ,the Gui would appear hang and unresponsive.

This is the perfect place to do Application work in separate thread and free the Event thread as early as possible.So the flow should be: Event Thread(Gives the trigger :Name) —-initiates and returns–>Worker Thread (gets the data related to name ) —hand over data to Event thread–>Swing Thread(updates the Gui).

So Swing thread is free to perform its own responsibilities in the mean time a Time-Consuming task is been performed.I suppose now its clear why multi threading capabilities are needed in modern applications.Sometimes designing a complex problem is easier in concurrent threads rather than in a single flow,like user events with some other task also running.

Now its time to take some real Java examples.In java their are two ways to start a thread.

  • Create a Class which extends Thread Class :Than you put you application code in overridden run method.Basically anything we want to do from this thread is put in run method.Try out example in SimpleThread.txt.Here its important to note that order of execution does not depend on which thread was started first,try for 10-15 times you will notice that sometimes its the second thread which started first although we have done in other way round.So its important to note that we cannot guarantee about the order of execution and also the behavior can be different on different O.S.
  • Create a Class which implements Runnable Interface : In this case also we would put our code in run method.And to start anew thread,we will create a new thread and pass runnable instance to it.Try out example in RunnableExample.txt.Here also order is not guaranteed.

So which is the more preferred way.Well most of the time its the second which is used,because generally our classes are already of some type say Swing Component has so have to extend some other class.In java as multiple inheritance is not allowed so we give thread properties to a class by implementing runnable.

Their is one more handy way to use in application.In our example we just wanted to do some work in a separate thread.To achieve that we can directly use

Thread thread=new Thread(new Runnable(){

public void run() {
* Put your work related code here


Now let’s go through the Life Cycle of a thread for better understanding : A thread can be in one of four states during its lifetime.

  • new – A new thread is one that has been created (using the new operator), but has not yet been started.
  • runnable – A thread becomes runnable once its start() method has been invoked. This means that the code in the run() method can execute whenever the thread receives CPU time from the operating system.
  • blocked – A thread can become blocked if one of the following events occurs:
    • The thread’s sleep() method is invoked. In this case, the thread remains blocked until the specified number of milliseconds elapses.
    • The thread calls the wait() method of an object. In this case, the thread remains blocked until either the object’s notify() method or its notifyAll() method is called from another thread. The calls to wait(), notify() and notifyAll() are typically found within synchronized methods of the object.
    • The thread has blocked on an input/output operation. In this case, the thread remains blocked until the i/o operation has completed.
  • dead – A thread typically dies when the run() method has finished executing.

Also stay away from these methods of Thread Class :stop(), suspend() and resume() .Usesage of these can result of unpredictable results in your program.These methods have been deprecated by Java team.


Next Page »

Blog at