Are you the publisher? Claim or contact us about this channel

Embed this content in your HTML


Report adult content:

click to rate:

Account: (login)

More Channels

Channel Catalog

(Page 1) | 2 | newer

    0 0
  • 03/05/11--04:58: Universal Date Parser.
  • It is easy to read the Date object from a string in Java. The task can be quite tricky when you are dealing with a third party data feed and you are not really sure about the format in which the date is going to come.

    The below example handles most of the date formats and returns the date object. The format supported are [dd MMM,yy], [MM/dd/yy], [MMddyy], [yyyy-MM-dd], [dd-MMM-yy], [dd MMM yy], [MMM dd, yy], [yyyyMMdd].

    You can easily add more formats but needs to make sure they and not conflicted with the existing things. For example you should not add [dd/MM/yy] as it will conflict with [MM/dd/yy] but it can be replaced. 

    0 0
  • 03/05/11--06:32: Hibernate Mapping Example

  • In this post I am trying to add a reference mapping project which includes most of the real world scenarios you will encounter when using hibernate.This example is primarily meant for differentiating the various types of relationships in hibernate and it is tested for the SAVE, UPDATE and SELECT features. I leave it to you to find out how to DELETE a row in the table or a member in the child list.

    If you are not familiar with the hibernate get an heads up on the various object relations in from this article.
    Now lets take an example and try to put a Object map and table design for the same. I am trying to provide all the relations in the same example.
    As  first step create the java and hibernate files as below.


     package com.manu.hibernate.mappings.domain;

    import java.util.List;

    import java.util.Set;


    * The Main class A.


    public class AMain {

    //Properties of A.

    Integer aId;

    String name;

    String prop1;

    String prop2;

    ASub1 one2oneSubA1;

    Set<ASub2> subSets;

    List<ASub3> subList;

    RefOnlyAMain one2oneSubRef;

    public AMain(String name) { = name;


    public AMain() {


    /* Add the Getters and Setters */


    public String toString() {

    // TODO Auto-generated method stub

    return " AMain with Id:"+aId+" Name:"+name;




     package com.manu.hibernate.mappings.domain;

    public class ASub1 {

    Integer as1Id;

    Integer aId;

    String subName;

    AMain parent;

    public ASub1(String subName) {

    this.subName = subName;


    public ASub1() {


    /* Add the Getters and Setters */


    public String toString() {

    return " ASub1 with Id:"+as1Id+" Name:"+subName+" Parent:"+parent;



    3. Similarly create the classes,,

    4. The Mapping file ABeanTypes.hbm.xml
    Note:- It is better to move the xml declaration to separate files I have put them together for easy understanding.

    <?xml version="1.0"?>

    <!DOCTYPE hibernate-mapping PUBLIC

    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"


    <hibernate-mapping package="com.manu.hibernate.mappings.domain">

    <class name="AMain" table="A_Main">

    <id name="aId" column="a_id" unsaved-value="null">

    <generator class="hilo" />


    <property name="name" />

    <property name="prop1" />

    <property name="prop2" />

    <one-to-one name="one2oneSubA1" class="com.manu.hibernate.mappings.domain.ASub1" cascade="all"


    <set name="subSets" inverse="true" cascade="all">

    <key column="a_id" />

    <one-to-many class="com.manu.hibernate.mappings.domain.ASub2" />


    <list name="subList" inverse="true" cascade="all" lazy="false">

    <key column="a_id" />

    <list-index column="as3_id" />

    <one-to-many class="com.manu.hibernate.mappings.domain.ASub3" />


    <one-to-one name="one2oneSubRef"

    class="com.manu.hibernate.mappings.domain.RefOnlyAMain" property-ref="parentARef"

    cascade="all" >





    <class name="ASub1" table="A_Sub1">

    <id name="as1Id" column="as1_id" unsaved-value="null">

    <generator class="hilo" />


    <property name="subName" column="sub_name" />

    <property name="aId" column="a_id" insert="false" update="false" />

    <many-to-one name="parent"

    class="com.manu.hibernate.mappings.domain.AMain" column="a_id"

    unique="true" cascade="save-update" />


    <class name="ASub2" table="A_Sub2">

    <id name="as2Id" column="as2_id" unsaved-value="null">

    <generator class="hilo" />


    <property name="subName" column="sub_name" />

    <property name="aId" column="a_id" insert="false" update="false" />

    <many-to-one class="com.manu.hibernate.mappings.domain.AMain"

    name="parent" column="a_id" />


    <class name="ASub3" table="A_Sub3">

    <id name="as3Id" column="as3_id" unsaved-value="null">

    <generator class="hilo" />


    <property name="subName" column="sub_name" />

    <property name="aId" column="a_id" insert="false" update="false" />

    <many-to-one class="com.manu.hibernate.mappings.domain.AMain"

    name="parent" column="a_id" />


    <class name="RefOnlyAMain" table="Ref_A_Main">

    <id name="refId" column="ref_id" unsaved-value="null">

    <generator class="hilo" />


    <property name="name" />

    <property name="aOrbId" column="aOrb_id" insert="false" update="false" />

    <property name="aOrbInd" column="aOrb_ind" />

    <properties name="parentARef">

    <property name="aOrbInd" column="aOrb_ind" insert="false" update="false"/>

    <many-to-one name="parentA"

    class="com.manu.hibernate.mappings.domain.AMain" column="aOrb_id"

    unique="true" cascade="save-update" />




    5.The hibernate configuration file.

    <?xml version='1.0' encoding='utf-8'?>

    <!DOCTYPE hibernate-configuration PUBLIC

    "-//Hibernate/Hibernate Configuration DTD//EN"




    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/appDB1</property>

    <property name="hibernate.connection.username">root</property>

    <property name="hibernate.connection.password">manupk</property>

    <property name="hibernate.connection.pool_size">10</property>

    <property name="show_sql">true</property>

    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <property name="">create</property>

    <mapping resource="com\manu\hibernate\mappings\domain\ABeanTypes.hbm.xml" />



    6. Test client.

     package com.manu.hibernate.mappings.client;

    import java.util.ArrayList;

    import java.util.HashSet;

    import java.util.List;

    import java.util.Set;

    import org.hibernate.Session;

    import org.hibernate.SessionFactory;

    import org.hibernate.Transaction;

    import org.hibernate.cfg.Configuration;

    import com.manu.hibernate.mappings.domain.AMain;

    import com.manu.hibernate.mappings.domain.ASub1;

    import com.manu.hibernate.mappings.domain.ASub2;

    import com.manu.hibernate.mappings.domain.ASub3;

    import com.manu.hibernate.mappings.domain.RefOnlyAMain;


    * @author Manupk



    public class RelationsSaveTest {


    * @param args


    public static void main(String[] args) {

    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

    Session session = sessionFactory.openSession();

    Transaction tx = session.beginTransaction();

    //Create the Parent Object.

    AMain a = new AMain("A");

    //One2One Child of AMain, with shared column in both table.

    ASub1 as1 = new ASub1("ASub - 1");



    //One2Many Using set, with shared column in both table.

    ASub2 as2a = new ASub2("Set - 1");

    ASub2 as2b = new ASub2("Set - 2");



    Set<ASub2> subSet = new HashSet<ASub2>();




    //One2Many using List, with shared column in both table.

    ASub3 as3a = new ASub3("List - 1");

    ASub3 as3b = new ASub3("List - 2");

    ASub3 as3c = new ASub3("List - 3");




    List<ASub3> subList = new ArrayList<ASub3>();





    //One2One Child of AMain, but without a shared column.

    RefOnlyAMain rfa = new RefOnlyAMain();

    rfa.setaOrbInd("A"); //Add the indicator to point the correct parent class.

    rfa.setName("Child 1 A");






    //Close the session and open a new one for proper testing.

    session =sessionFactory.openSession();

    List<AMain> result1 = session.createQuery(" from AMain").list();


    List<ASub1> result2 = session.createQuery(" from ASub1 ").list();


    List<ASub2> result3 = session.createQuery(" from ASub2").list();


    List<ASub3> result4 = session.createQuery(" from ASub3").list();


    List<RefOnlyAMain> result6 = session.createQuery(" from RefOnlyAMain").list();




    In the class; note the properties,

      ASub1 one2oneSubA1;
     Set<ASub2> subSets;
     List<ASub3> subList;
     RefOnlyAMain one2oneSubRef;

    As the name implies,
            ASub1 has a One-to-One relationship with AMain. 
            ASub2 has a Many-to-One relationship with AMain and it is implemented using Set.
            ASub3 has a Many-to-One relationship with AMain and it is implemented using List.
            RefOnlyAMain a One-to-One relationship with AMain, but it does not share a column with AMain as in the above case.So we need to use the 'formula' to map this bean.

    All the tables that contains the child data of AMain has the a_id column as the foreign key and all the mappings are done based on that.

    Now have look at the test client.

    In the test client all the properties are set and are being saved to the table.

    All the table mappings are given in the ABeanType.hbm.xml file and are self explanatory.
    When the Test client is executed the hibernate generates the insert scripts as below.
    Note:- In the hibernate.cfg.xml file the property is set as create so that hibernate automatically create the required table. Change it to update in the consecutive runs.

    Hibernate automatically takes care about the referential integrity of data by inserting them in the order. All you need to do is to save the Main bean and all the child beans are automatically saved to the DB.If there is any error in the operation all the data inserts are rolled back and hibernate maintains the integrity of the data.

    Hibernate: insert into A_Main (name, prop1, prop2, a_id) values (?, ?, ?, ?)
    Hibernate: insert into A_Sub1 (sub_name, a_id, as1_id) values (?, ?, ?)
    Hibernate: insert into A_Sub2 (sub_name, a_id, as2_id) values (?, ?, ?)
    Hibernate: insert into A_Sub2 (sub_name, a_id, as2_id) values (?, ?, ?)
    Hibernate: insert into A_Sub3 (sub_name, a_id, as3_id) values (?, ?, ?)
    Hibernate: insert into A_Sub3 (sub_name, a_id, as3_id) values (?, ?, ?)
    Hibernate: insert into A_Sub3 (sub_name, a_id, as3_id) values (?, ?, ?)
    Hibernate: insert into Ref_A_Main (name, aOrb_ind, aOrb_id, ref_id) values (?, ?, ?, ?)

    Hibernate: select amain0_.a_id as a1_1_, as name1_, amain0_.prop1 as prop3_1_, amain0_.prop2 as prop4_1_, 'A' as formula0_, amain0_.a_id as formula1_ from A_Main amain0_
    Hibernate: select asub1x0_.as1_id as as1_2_0_, asub1x0_.sub_name as sub2_2_0_, asub1x0_.a_id as a3_2_0_ from A_Sub1 asub1x0_ where asub1x0_.a_id=?
    Hibernate: select refonlyama0_.ref_id as ref1_5_0_, as name5_0_, refonlyama0_.aOrb_id as aOrb3_5_0_, refonlyama0_.aOrb_ind as aOrb4_5_0_ from Ref_A_Main refonlyama0_ where refonlyama0_.aOrb_ind=? and refonlyama0_.aOrb_id=?
    [ AMain with Id:1 Name:A]

    Hibernate: select asub1x0_.as1_id as as1_2_, asub1x0_.sub_name as sub2_2_, asub1x0_.a_id as a3_2_ from A_Sub1 asub1x0_
    [ ASub1 with Id:32768 Name:ASub - 1 Parent: AMain with Id:1 Name:A]

    Hibernate: select asub2x0_.as2_id as as1_3_, asub2x0_.sub_name as sub2_3_, asub2x0_.a_id as a3_3_ from A_Sub2 asub2x0_
    [ ASub2 with Id:65536 Name:Set - 2 Parent: AMain with Id:1 Name:A,  ASub2 with Id:65537 Name:Set - 1 Parent: AMain with Id:1 Name:A]

    Hibernate: select asub3x0_.as3_id as as1_4_, asub3x0_.sub_name as sub2_4_, asub3x0_.a_id as a3_4_ from A_Sub3 asub3x0_
    [ ASub3 with Id:98304 Name:List - 1 Parent: AMain with Id:1 Name:A,  ASub3 with Id:98305 Name:List - 2 Parent: AMain with Id:1 Name:A,  ASub3 with Id:98306 Name:List - 3 Parent: AMain with Id:1 Name:A]

    Hibernate: select refonlyama0_.ref_id as ref1_5_, as name5_, refonlyama0_.aOrb_id as aOrb3_5_, refonlyama0_.aOrb_ind as aOrb4_5_ from Ref_A_Main refonlyama0_
    [ RefOnlyAMain with Id:131072 Name:Child 1 A Parent: AMain with Id:1 Name:A]

    Now go ahead and play around changing the values and table structure for better understanding.

    Given below the code snippet used to update the set of child beans.

             SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

    Session session =sessionFactory.openSession();

    Transaction tx = session.beginTransaction();

    List<AMain> result1 = session.createQuery(" from AMain").list();


    //Create the Parent Object.

    AMain a = result1.get(0);

    //One2One Child of AMain, with shared column in both table.

    ASub1 as1 = a.getOne2oneSubA1();


    //One2Many using List, with shared column in both table.

    ASub3 as3a = new ASub3("NEW List - 1");

    ASub3 as3b = new ASub3("NEW List - 2");

    ASub3 as3c = new ASub3("NEW List - 3");




    List<ASub3> subList = new ArrayList<ASub3>();






    //session.createQuery("delete from ASub3").executeUpdate();



    //Close the session and open a new one for proper testing.

    session =sessionFactory.openSession();

    Transaction tx2 = session.beginTransaction();;





    0 0

    In this post I will try to point out various ways you can fetch data in hibernate and in what scenarios each of then are is useful.

    HQL in hibernate
    It is the most preferred way to use that combines you the ease of SQL and flexibility of Hibernate. I don't want to add anything more but will direct you to an excellent article on HQL.

    Criteria Queries
    Criteria queries are less verbose and preferred by people who don't have much exposure to SQL. It is less performative compared to HQL. Read more about Criteria here.

    Native SQL and Stored Procedures.
    This should considered as a last option as you will loose the features of hibernate if you start using Native SQL.Also you should take care the responsibility of transforming the result set to object by yourself.
    But there are situations you want to go with this approach. Read more about them here.

    These typical ways can be tweaked in various ways to customize them to your requirement. Let me discus few of them that you may not find very often documented.

    I have used the classes from examples from my previous post for simplicity.Read it here in case you need any explanation on the examples.

    1. Partial Initialization of a bean.

    Suppose you have a bean AMain, as in my previous post.

     public class AMain {  
    Integer aId;
    String name;
    ASub1 one2oneSubA1;
    List<ASub3> subList;
    //More code below...

    If you write an HQL to fetch this bean as 

     List<AMain> beanList2 = session.createQuery("from AMain am ").list();  

    it will fire the below queries.

    Hibernate: select amain0_.a_id as a1_1_, as name1_, amain0_.prop1 as prop3_1_, amain0_.prop2 as prop4_1_, 'A' as formula0_, amain0_.a_id as formula1_ from A_Main amain0_
    Hibernate: select asub1x0_.as1_id as as1_2_0_, asub1x0_.sub_name as sub2_2_0_, asub1x0_.a_id as a3_2_0_ from A_Sub1 asub1x0_ where asub1x0_.a_id=?
    Hibernate: select sublist0_.a_id as a3_1_, sublist0_.as3_id as as1_1_, sublist0_.as3_id as as1_4_0_, sublist0_.sub_name as sub2_4_0_, sublist0_.a_id as a3_4_0_ from A_Sub3 sublist0_ where sublist0_.a_id=?

     Also the last query can repeat number of times if the lazy loading in enabled.

    Now If I have a requirement to get the partially initialized AMain bean, I mean with only the properties aId and name initialized that definitely should not take mare than 1 query as all the information is available on the AMain table. Most of the people will tend to go to Native SQL at this point.But you can achieve this using HQL.

    write the HQL as   

     List<AMain> beanList2 = session.createQuery("select new AMain (aId,name) from AMain am ").list();  

    Also add the corresponding constructor in class AMain as

     public AMain(Integer aId,String name) {  
    this.aId = aId; = name;

    Now verify the SQL output

    Hibernate: select amain0_.a_id as col_0_0_, as col_1_0_ from A_Main amain0_

    Yes..only 1 query is fired.This is very useful in when we have to fetch a snapshot of a Large object in a performative way.

    2. HQL Joins on multiple columns.

    If there are two related table and we have mapped them in the hbm files then the below hql is possible.

    "from AMain a left outer join a.refMain ref...more joins here"

    It will do a left outer join on the tables RefMain and AMain provided you have a corresponding mapping. Now if you need to add another condition in the join(to satisfy the join but which we could not add as a relationship). It can be achieved using a 'with' operator.

    so, the new HQL is,

    "from AMain a left outer join a.refMain ref with ref.aOrbId = 'a'...more joins here"

    This way the query results can be achieved with out disturbing the original mapping.

    3. Using a DTO instead on a Domain Object.

    Meany times we might need a set of data that might be needed which is spread across multiple tables. Which means I don not have a Domain Object to hold the data. Using hibernate we can populate a DTO object from any SQL of HQL query using Transformers. The Transformers can convert the List of Object arrays to List of DTO that will improve the readability and are much easier to use with.

     public class AFamilyDTO {  
    Integer aId;
    String name;
    Integer as1Id;
    String aSub1Name;
    /* getter/ setters here..*/

    As you can see the bean represent a snapshot of AMain and ASub1 beans Or it can be any DTO which we have created for the easy representation of the data model. Now Lets see how we can use Transformers to populate this bean.

     SQLQuery query = session.createSQLQuery("select amain.a_id as aId , as name, " +  
    "sub1.as1_id as as1Id, sub1.sub_name as as1Name " +
    " from A_Main amain join A_Sub1 sub1 on amain.a_id = sub1.a_id");
    query.addScalar("aId", Hibernate.INTEGER);
    query.addScalar("name", Hibernate.STRING);
    query.addScalar("as1Id", Hibernate.INTEGER);
    query.addScalar("as1Name", Hibernate.STRING);
    List<AFamilyDTO> list = query.list();

    As I have told in the beginning of the post, there are multiple ways to fetch data in hibernate. So, before you blame hibernate for the performance issues in your application have a look all the options it provides you to fetch the data. Turn on the show sql flag on and see how many queries are getting fired. Then see if you can use any alternative ways of fetching data.

    0 0

    We learn by reading books and experimenting on it.  So, it is imperative that you choose the best available options. In this post I would like to share my experience with some of the books and how they can help you evolve as a Java Developer.

    Lets start from the floor, the first 3 books are a good starting point for any Java student. Java Programming Language helps you to get yourself familiar with Java, where Head First will help you stick the Java concepts into your brain, so that you will never forget them. I have chosen Thinking In Java 3rd book in this category but Java the Complete Reference By Herbert Schildt and Java in a nutshell By David Flanagan are good substitutes. These books are more of a reference than a must read.

    1. Java Programming Language By Ken Arnold, James Gosling, David Holmes
                    Direct from the creators of the Java, The Java Programming Language is an indispensible resource for novice and advanced programmers alike. Developers around the world have used previous editions to quickly gain deep understanding of the Java programming language, its design goals, and how to use it most effectively in real-world development. The authors systematically conver most classes in Java's main packages, java.lang.*, java.util, and, presenting in-depth explanations of why these classes work as they do, with informative examples. Several new chapters and major sections have been added, and every chapter has been updated to reflect today's best practices for building robust, efficient, and maintainable Java software.

    Above are extracts from the book index page.

    2. Head First Java By Kathy Sierra, Bert Bates
                    Its unique approach not only shows you what you need to know about Java syntax, it enables and encourages you to think like a Java programmer. Mastering object oriented programming requires a certain way of thinking, not just a certain way of writing code. The latest research in cognitive science, neurobiology, and educational psychology shows that learning at the deeper levels takes a lot more than text on a page. Actively combining words and pictures not only helps in understanding the subject, but in remembering it. According to some studies, an engaging, entertaining, image-rich, conversational approach actually teaches the subject better. Head First Java puts these theories into practice with a vengeance.

    Above lines are copied from Google books read more here.
    3. Thinking In Java By Bruce Eckel
                    Eckel introduces all the basics of objects as Java uses them, then walks carefully through the fundamental concepts underlying all Java programming -- including program flow, initialization and cleanup, implementation hiding, reusing classes, and polymorphism. Using extensive, to-the-point examples, he introduces exception handling, Java I/O, run-time type identification, and passing and returning objects. Eckel also provides an overview of the Key Technology of the Java2 Enterprise Edition platform (J2EE).

    Above lines are copied from Google books read more here.               

    I am not a big fan of SCJP Exam, but A Programmer's Guide to Java SCJP Certification is much more than a certification guide. It gives you an insight in to Java, the tips and tricks. SCJP Sun Certified Programmer for Java 5 Study Guide By Kathy Sierra, Bert Bates is a go to book if you are mad about SCJP. Better to read these books than spending time in reading question dumps, these books will help you much more than clearing the exam in your career.
    4. A Programmer's Guide to Java SCJP Certification: A Comprehensive Primer By Khalid Azim Mughal, Rolf Rasmussen
                     This book will help you prepare for and pass the Sun Certified Programmer for the Java Platform SE 6 (CX-310-065) Exam. It is written for any experienced programmer (with or without previous knowledge of Java) interested in mastering the Java programming language. It contains in-depth explanations of the language features. Their usage is illustrated by way of code scenarios, as required by the exam. Numerous exam-relevant review questions to test your understanding of each major topic, with annotated answers Programming exercises and solutions at the end of each chapter Copious code examples illustrating concepts, where the code has been compiled and thoroughly tested on multiple platforms Program output demonstrating expected results from running the examples Extensive use of UML (Unified Modelling Language) for illustration purposes

    Above lines are copied from Google books read more here.               

    OK, so you got to know Java and been working in it for couple of years its time to take the next step. Everything in this world has good and bad. Java language if not used the way is supposed to be, can make your life miserable. When you write code, its written for future. Writing good Java code is an art that needs lot more skill than knowledge of basic Java. Here I would like to introduce the next set of 4 books that can make you a master in the trade.


    The Pragmatic Programmer is not really a Java book but is a self help book for any programmer. It is a great book covering various aspects of software development and is capable in transforming you to a Pragmatic Programmer.
    5. The Pragmatic Programmer, From Journeyman To Master By Andrew Hunt, David Thomas

                    Written as a series of self-contained sections and filled with entertaining anecdotes, thoughtful examples, and interesting analogies, The Pragmatic Programmer illustrates the best practices and major pitfalls of many different aspects of software development. Whether you're a new coder, an experienced programmer, or a manager responsible for software projects, use these lessons daily, and you'll quickly see improvements in personal productivity, accuracy, and job satisfaction. You'll learn skills and develop habits and attitudes that form the foundation for long-term success in your career. You'll become a Pragmatic Programmer.
    Above lines are copied from Google books read more here.               

    So, we wrote code. It is time to add some style. The elements of Java style is one of the earliest documentation on the style part of Java including its various aspects.
    6. The elements of Java style By Scott Ambler, Alan Vermeulen

                     Many books explain the syntax and basic use of Java; however, this essential guide explains not only what you can do with the syntax, but what you ought to do. While illustrating these rules with parallel examples of correct and incorrect usage, the authors offer a collection of standards, conventions, and guidelines for writing solid Java code that will be easy to understand, maintain, and enhance. Java developers and programmers who read this book will write better Java code, and become more productive as well.

    Above lines are copied from Google books read more here.

    Now, we know how to write code in style. But is it best is class? Does it uses the best practices? Effective Java is one of the best book on best practices is a favourite book for many Java developers.
    7. Effective Java By Joshua Bloch

                    Joshua  brings together seventy-eight indispensable programmer's rules of thumb: working, best-practice solutions for the programming challenges you encounter every day. Bloch explores new design patterns and language idioms, showing you how to make the most of features ranging from generics to enums,  annotations to autoboxing. Each chapter in the book consists of several “items” presented in the form of a short, standalone essay that provides specific advice, insight into Java platform subtleties, and outstanding code examples. The comprehensive descriptions and explanations for each item illuminate what to do, what not to do, and why.

    Above lines are copied from Google books read more here

    Then, you know the good, it is time for the bad stuff. Bitter Java is one of the first book to bring up the Anti-patters in Java. There are various articles and books on Anti-patterns and code smells and is an area where there is lots of space to learn. There are many other books on this topic I am adding this book as a starting point.
    8. Bitter Java By Bruce Tate

                    Intended for intermediate Java programmers, analysts, and architects, this guide is a comprehensive analysis of common server-side Java programming traps (called anti-patterns) and their causes and resolutions. Based on a highly successful software conference presentation, this book is grounded on the premise that software programmers enjoy learning not from successful techniques and design patterns, but from bad programs, designs, and war stories -- bitter examples. These educational techniques of graphically illustrating good programming practices through negative designs and anti-patterns also have one added benefit: they are fun.
    Above lines are copied from Google books read more here

    Many say you need to know Design Patterns, if you want grow as a developer. So I thought of mentioning the best Design pattern book that I have read. It is not a reference book nor it contains the patters catalogue but the book explains the Object Oriented Design Principles that are as important as the patters. Use the book Design patterns: elements of reusableobject-oriented software if you are looking for a reference book.
    9. Head First design patterns By Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates

                    You know you don't want to reinvent the wheel (or worse, a flat tire), so you look to Design Patterns--the lessons learned by those who've faced the same problems. With Design Patterns, you get to take advantage of the best practices and experience of others. Using the latest research in neurobiology, cognitive science, and learning theory, Head First Design Patterns will load patterns into your brain in a way that sticks. In a way that lets you put them to work immediately. In a way that makes you better at solving software design problems, and better at speaking the language of patterns with others on your team.
    Above lines are copied from Google books read more here

    If your are a master at coding and designing application using Java its time to crack the JVM. I have read that 'The Java language specification' is the best book to do that. I have not got the patience or skill to read the book but is an interesting pick if you want to cross the line.
    10. The Java language specification

                    The book provides complete, accurate, and detailed coverage of the Java programming language. It provides full coverage of all new features added in since the previous edition including generics, annotations, asserts, autoboxing, enums, for each loops, variables,  methods and static import clauses.

    Above are extracts from the book index page.

    In these web-years online resources may be more reachable than books, but I fell these books will help in tuning you to a better Java programmer.

    0 0

    In this post I would like to share my experience with  developing Java Web Applications with Tapestry 5.

    Tapestry is a component oriented framework for creating dynamic, robust, highly scalable web applications in Java. Tapestry is been is here for a while now, not really taken off as a web framework for Java. In the past, it is been critisized for non compatability of its versions. After the release of version 5 in 2008 it has been more consistant and popular with developers.

    I have been using Tapestry for the last 15 months and used both version 5.0.18 and 5.2.6. One of the main issues with tapestry was the learning curve and that is been some what improved now, with the exelent documentation available at the project home page here. You don't see  a lot of tapestry resources online. If you search for the tapestry resources in internet you might end up getting t3 or t4 versions which will not be usefull with the new t5 version.

    Having worked in tapestry for more than one year, I must say that I have mixed opinion about tapestry. Its POJO based approach is really nice and it also scores as a component based framework. The components are easily plug-gable in all the pages. There has been a lot of improvements in the ability of unit testing the pages. Even if you don't want to depend on tapestry's test classes you can create your own integration test cases as the pages are simple java classes. It has really good integration with spring that opens your window to all other frameworks and technologies.

    The biggest pain is been when you are stuck with problems, the alternatives were really difficult. For example there is a grid component in tapestry which by default provides sorting for all the columns in the grid. If you need to disable sorting, there should be hell lot of things you have to do as told here. In another example, you might need to have 3 classes construct a simple drop down in tapestry as told here. In today world of IDE tapestry don't have much of IDE support and that can be a pain while you develop a page in tapestry.

    Its been really difficult to find good resouces about tapestry and I thought of sharing some links that I found useful during my learning of tapestry. As I told already the getting started page is reaaly improved and now you can really get started with tapestry in that page. The wiki page contains lots of tips and tricks on how to use tapestry features.

    The Tapestry Jump Start page is great place with lots of examples that will help you get into tapestry. Howard M. Lewis Ship the creator of Tapestry writes about tapestry in his personal blog is also a good read.  Recently I have found another site with lots of exapmle in tapestry.  Even the Tapestry360 is a fresh and new concept.I  really liked Mark Shead blog post is a good collection of usefull references about tapestry5.

    When you are thinking about java web framework I think tapestry should be one of the choices. If You compare tapestry with other web framework there will be lots of diffidence have a look at Matt Raible presentation about comparing jvm web frameworks also the matrix comparing the web frameworks in Java. Also there is a post from Joshua about why you should consider tapestry5.

    0 0

    Its been a while I was thinking about integration vs unit testing. Lots of googling, questions in stack overflow and looking in many books. In this post I would like share with you the information I have found and what decision I arrive at this.

    I think if you put this question to any Java developer, you will get an anwser supporting the unit test instantaneously. They will tell you that if you can not do unit testing, the unit of code you hava written is large and you have to bring it down to multiple testable unit. I have found these questions in Stack Overflow 1, 2, 3 and 4 useful in getting a good understanding of both terminologies.

    Unit testing is widly followed in Java domain with most of the projects now also enforcing the code coverage and unit testing. Integration testing is relativly new and misunderstood concept. Even through it is practiced much less than, unit testing there can be varios uses of it. Lets take a simple user story and revisit both.

    Lets consider it with a user story

    User will give an INPUT in a UI form and when the submit button is clicked, the PROCESSED output should be shown in the next page. Since the results should be editable, both INPUT and OUTPUT should be saved in the database.

    Technical Design

    Lets assume that our application will grow rapidly in the future and we will design it now keeping that in mind. 

    As shown in the above image it is a standard 4-tier design with view, service, dao. It has a application layer which contains the logic of how to convert the input into output. To implement the story we wrote 5 methods(1 in service, 2 dao to save input and output, 1 contains the business and 1 method in view layer to prepare the input.)

    Writing some Unit test cases

    If we were to unit test the story, we need to write 5 tests. As the different layers are dependent, we might need to use mock objects for testing. But apart from one method in application layer that does the original process, is there any need to unit test the other part? For example the method,

     public void saveInput(Input input){  
    Session session = sessionFactory.getCurrentSession();;

    When you unit test this, you will typically use a mock object of sessionFactory and the code willl always work. Hence I don't see much point in wiring a unit test here. If you observe carefully, apart from the application layer, all the other methods will be similar to what we have discussed.

    What can we acheive with integration test?

    Read here as a heads up for the integration test. As we have seen most of the unit tests for this story were not effective. But we can't skip testing as we want to find out the code coverage and make our code self testing. According to Martin flower in his article about Continuous Integration you should write the code that can test the other code. I fell the good integration tests can do this for you.

    Lets write a simple itegration test for this situation,

     @Configurable(autowire = Autowire.BY_NAME)   
    @ContextConfiguration(locations = {"classpath:applicationContext.xml"})
    public class SampleIntTest {
    private SamService samService;
    public void testAppProcessing(){
    Input input = new Input();
    //prepare input for the testing.
    Output output = samService.processInputs(input);
    //validate outpt gainst the given input.
    if(!isValidate(input,output)){"Validation failed!");

    I have skipped the view layer here as it not so relevent. We are expecting the INPUT from the UI in a bean Input and thats that we willl have in the service layer. Here, With this few line of coding, you can acheive the full functionality of the application from the service layer.

    It is prefered to use a in-memory database like H2 for integration tests. If the table structure is complicated it may not be possible in that case,you can use a test instance of DB and prepare a script to delete all the data and run it as part of the test so that the DB state is restored back. This is important because in the next run the same data will be saved again.

    Another advantage of integration tets is that if you are changing the implementation the test need not be changed because it ic concerned with the input and output.This is useful in refactoring the code without change in the test code. Also, you can schedule these tets to measure the stability of the appication and any regression issues can be caught early.

    As we have seen, integration test are easy to write and are useful, but we need to make sure it does not replace the unit testing completely. When ever there is a rule base system(like the LogicalProcesser in our case) it should be mandatory because you can't cover all the scenarios with the integration test.

    So as always JEE is about making choice asnd sticking to it. For the last few months we were practicing it in our teams and it is really going well. Currently we made integration test mandatory and unit tests and optional. Always review the code coverage and make sure you get good coverage in the core of the system(the LogicalProcesser in our case).

    0 0

    In this post I am going to write about the issues that we have faced during the up-gradation of the tapestry version from 5.0.18 to 5.2.5 in one our projects. Below are some of them. Hope this collection will help someone!

    1. Changes in the RequestPathOptimizer file inside tapestry.

    Issue Logs:-

    Caused by: java.lang.ClassNotFoundException: from BaseClassLoader@41c491{VFSClassLoaderPolicy@1d02b85{name=vfsfile:/D:/SVN/trunk/export/tools/jboss-5.0.1.GA/server/default/deploy/ROOT.war/ .......
    at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(


    Remove all the tapestry-spring dependancies to resolve this issue.


    Tapestry JIRA 
    Mailing list URL 

    2.Including the tapestry bean validator jar.


    Caused by: java.lang.ClassNotFoundException: javax.validation.ValidatorFactory from ......
    real=file:/D:/SVN/trunk/export/tools/jboss-5.0.1.GA/server/default/deploy/ROOT.war/WEB-INF/lib/XmlSchema-1.4.2.jar]] delegates=null exported=[]}} at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(


    There is new feature in Tapestry called bean validator that needs the validation api and implementation jars to be added it can be downloaded from the project homepage here.

    3.Changes in the tapestry spring integration.


    Caused by: java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(
    at org.apache.tapestry5.internal.spring.SpringModuleDef$3$1.invoke(
    at org.apache.tapestry5.ioc.internal.OperationTrackerImpl.invoke(
    ... 91 more
    java.lang.RuntimeException: Exception constructing service 'ApplicationContext': Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!


    From Tapestry 5.2.x it will load the spring context automatically and hence we need to remove the below from web.xml. This will help in live class loading of service class. Also the spring beans should be wired and not to be injected as services.As per this there will be changes in All the Page classes and web.xml


    Mailing list URL
    Tapestry Wiki-1 
    Tapestry Wiki-2

    As per the article "The changes below represent an unfortunate backwards compatibility issue. If necessary, you can still use tapestry-spring version 5.0.18 with the rest of Tapestry."

    If we want to continue using spring-tapestry 5.2.5 jar we have to make changes in each and every Page file where spring services are injected. Also the spring beans should be wired and not to be injected as services.

    4. Using Tapestry 5.2.5 inside the JBoss Application server.


    Caused by:
    at org.jboss.virtual.plugins.registry.DefaultVFSRegistry.getFile(
    at org.jboss.virtual.protocol.AbstractVFSHandler.openConnection(
    at Source)
    at Source)
    ... 85 more
    Caused by: Illegal character in path at index 159: vfszip:/D:/SVN/trunk/export/tools/jboss-5.0.1.GA/server/default/deploy/ROOT.war/WEB-INF/lib/tapestry-upload-5.2.5.jar/org/apache/tapestry5/upload/components/PK/
    at$ Source)


    As per the below links we need to use a patch to fix it.

    Mailing list URL-1
    Mailing list URL-2 
    Tapestry JIRA
    Tapestry Wiki

    5. Changes in the Locale implementation

    If you use the url to load pages and your application supports the multiple languages then you need to append the locale code infront of the url.

    For example:
    Current url: "http://localhost/superpopup" should be changed to "http://localhost/${localeInd}/superpopup" 

    Mailing List URL 

    6. Tapestry handling of transients instances ValueEncoder

    Mailing List URL

    7. Change in the way @Secure is handled in the page classes.

    Most of the applications we will have the Index page tagged with the @Secure annotation to force the usage of https protocol. Some how I could not get this done with the existing settings. To have this you need to add the below lines.

    configuration.add(SymbolConstants.SECURE_ENABLED, "true");

    Mailing List URL

    0 0

    Eclipse IDE project is started aiming to provide a universal tool set for development. Open Source IDE, mostly provided in Java, but the development language is independent. Eclipse market place hosts the list of plugins for the worlds most popular IDE. You can see the Top MPC Downloads and Top Favorites plugins are highlighted in the site. In this post I will introduce you some of the coolest eclipse plugins that I have used but were not part of the Top 10 list shown in the marketplace.

    Below are my favorite plugins which are already listed in the top 10 list.

    1. Mylyn 3.6
    2. Maven Integration for Eclipse
    3. Subclipse
    4. UMLet
    5. FindBugs
    6. CheckStyle
    7. AnyEdit

    Givern below the ones that don't made it to the top 10 list but can make it one day!

    General Purpose Tools

    1. Rabbit

    Rabbit is a time tracking plug-in for Eclipse. It runs silently in the background to record how you spend your time within Eclipse and reports the data back to you whenever you want it to - in a useful way.

    2. InstaSearch

    InstaSearch is an Eclipse plug-in for doing fast text search in the workspace. The search is performed instantly as-you-type and resulting files are displayed in an Eclipse view. It is a lightweight plug-in based on Apache Lucene search engine. Each file then can be previewed using few most matching and relevant lines. A double-click on the match leads to the matching line in the file.

    3. Open Extern

    This is an eclipse plugin, which you can use to open a shell (either a command prompt - CMD or a linux shell), or a folder (windows explorer, nautilus, konqueror) from eclipse's resource navigator or package explorer. Works on Linux and Windows.

    4. Eclipse Todo Editor

    Manage your todos in an easy to use text editor with syntax highlighting and code completion. Effectively structure and query your todo lists using projects and custom tags. 

    5. MailSnag

    With MailSnag, you can debug application generated emails within Eclipse. MailSnag creates a simple SMTP server to capture and inspect emails sent out by an application during development. You can view the email rendered as HTML, text or both. You can also view the raw data, embedded content and attachments.

    6. More Clipboard

    More Clipboard keeps track of the latest entries copied/cut into clipboard buffer and allows quick pasting from the popup list by pressing a hotkey. Inspired by Multi Clipboard plugin for Eclipse and Visual Assist for MS VS.

    7. FileSync 

    FileSync plugin for Eclipse is a file synchronisation tool. The main goal is to keep files outside of Eclipse projects in-sync with Eclipse project files. The plugin works as builder in Eclipse and will synchronize all changes on Eclipse project files with mapped external folders. E.g. if a file is created, changed or deleted in Eclipse, then the mapped (external) file will be created, changed or deleted too.

    8. AgileReview

    AgileReview provides you with an easy possibility to do code reviews in your favorite IDE. Code reviews are a powerful meaning for quality assurance, but switching between spreadsheets and code is very time consuming. With AgileReview you can comment and discuss code without leaving the IDE and more important: without leaving the code.

    Tools for Java Developers

    9. JAutodoc

    JAutodoc is an Eclipse Plugin for automatically adding Javadoc and file headers to your source code. It optionally generates initial comments from element name by using Velocity templates for Javadoc and file headers.

    10. JadClipse

     If you use JadClipse the Class File Viewer will be replaced with the JadClipse Class File Viewer that shows the decompiled source of the class. This task is accomplished by decompiling the corresponding class file in the background using Jad. Normal Java syntax highlighting as well as the Outline View are supported.

    Unit Testing

    11. JUnit Helper

    "JUnit Helper" helps JUnit users to cover all tests for public, protected and package local methods by saving much labor to start writing new test cases. Eclipse plugin also has an advantage of making it easier to go back and forth between developing class and test class by "Alt + 8" (test->dev) and "Alt +9"(dev->test).

    12. MoreUnit

    MoreUnit is an eclipse plugin that should assist you writing more unit test. The following features are implemented: - Decorate classes which have a testcase. - Mark methods in the editor which are under test. - Jump to a testcase in the editor via the menu or a shortcut (and back) - Generate a testmethod stub for the method under cursor-position in the editor via the menu or a shortcut. - Rename/move of classes / methods with corresponding testcases automatically starts refactoring for tests as well.

    Looging Helpers

    13. Logging code Cleanup for Eclipse

    Logging code Cleanup plugin for Eclipse is an extension of the Eclipse Cleaun Ups which detects invocations of logging methods with compound arguments (requiring computation before method call) and prefixes them with corresponding if statements.

    14. Log4E

    Log4E is an Eclipse Plugin which helps you to set up your logger easily in Java Projects. It assists you in several tasks: logger declaration, logger Insertions at certain method entries, substitution of System out's, modification of already existing logger statements. Log4E has active support for Log4j, Commons Logging and JDK 1.4 Logging. By defining your own templates you might be able to adapt your own logger to the Plugin. 

    UML and Code Analysis Tools

    15. ModelGoon UML4Java

    ModelGoon brings new points of view of a Java project. Thanks to its tight connection and interaction with the Eclipse Java Development Tools JDT. ModelGoon provides also round-trip features on Class Diagrams actually as beta.

    16. CodePro AnalytiX

    CodePro AnalytiX is the premier Java software testing tool for Eclipse developers who want to be active participants in improving the quality and security of the code they produce. CodePro AnalytiX seamlessly integrates into the Eclipse environment, using automated source code analysis to pinpoint quality issues and security vulnerabilities before code reaches QA, or worse, production!

    17. Sonar

    Sonar for Eclipse provides comprehensive integration of Sonar into Eclipse. It shows quality issues while browsing the source code. Developers are made aware of quality issues compared to corporate standards without leaving their favorite IDE and thus enabling for continuous improvement with no effort. No propagation of standards changes is required anymore as definition is centralized.

    18. MaintainJ

    MaintainJ generates the runtime sequence diagrams for a use case. MaintainJ generated diagrams are dynamic, easy to explore and help Java developers to understand, debug and document Java applications.

    19. EclEmma Java Code Coverage

    EclEmma is a free Java code coverage tool for Eclipse, available under the Eclipse Public License. It brings code coverage analysis directly into the Eclipse workbench

    20. eCobertura

    eCobertura enables you to launch your applications or tests in Cobertura-covered mode directly from within Eclipse. View your source files colored according to the coverage results. Browse through the detailed coverage results in a tree view.

    Note:- The numbering is arbitrary and does not imply the importance. The description about each plugins is copied from the Eclipse Market Place.

    0 0

    The debate over checked vs. unchecked exceptions goes way, way back. Some say it’s one of the best features Java included. Others say it was one of their biggest mistakes[1].

    It looks like the debate is over. In this post I will try to include the links to articles and books which speaks about this topic. I am not an expert voice in this, but I will try to explain you why did I reach the this conclusion.

    So, we are talking about,

    Unchecked exceptions :
    • represent defects in the program (bugs) - often invalid arguments passed to a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes : "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time."
    • are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, orIllegalStateException
    • a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)
    Checked exceptions :
    • represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
    • are subclasses of Exception
    • a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)
    The above are as told in Java Practices Page[2].

    In many of the projects I have worked on, I have seen different ways of coding and various different strategies, code formatting, class naming styles, databases and technologies. The one thing that remained same was, Exceptions. All the projects had custom exceptions, created by extending Exception class!

    I am sure that most us of know the difference between checked and unchecked exceptions, but very few thinks carefully before using them. I wanted all the details to be listed in single page so that I could convince my team to switch to Unchecked  exceptions.

    In his famous book, Clean code: a handbook of agile software craftsmanship[3], Robert C. Martin writes the below lines supporting Unchecked Exceptions.

    The debate is over. For years Java programmers have debated over the benefits and liabilities of checked exceptions. When checked exceptions were introduced in the first version of Java, they seemed like a great idea. The signature of every method would list all of the exceptions that it could pass to its caller. Moreover, these exceptions were part of the type
    of the method. Your code literally wouldn’t compile if the signature didn’t match what your code could do.

    At the time, we thought that checked exceptions were a great idea; and yes, they can yield some benefit. However, it is clear now that they aren’t necessary for the production of robust software. C# doesn’t have checked exceptions, and despite valiant attempts, C++ doesn’t either. Neither do Python or Ruby. Yet it is possible to write robust software in all of these languages. Because that is the case, we have to decide—really—whether checked exceptions are worth their price.

    Checked exceptions can sometimes be useful if you are writing a critical library: You must catch them. But in general application development the dependency costs outweigh the benefits

    The last line is most significant, where he speaks about the general application  development, Lets take an example,

    If you have to read an XML file using a DOM Parser, we need to deal with some checked exceptions[5] like ParserConfigurationException, SAXException and IOException . The API developer thought that if the XML was invalid, they should notify so that the consumer of the API(ie, the application developer) can decide how to handle the situations.

    Now, If You have some alternatives to proceed with the normal logic, you could do that, other wise you should catch these checked exceptions and throw and Unchecked exception. This way the method signatures will be clean also, we are stating that if the XML is invalid we are can not do much, and we are stopping the processing. Let the error handler written at the top layer take the appropriate decision on what to do.

    So, all we need to do is to create out custom exception class by extending RuntimeException.

    In the Java Tutorial hosted by Oracle, there is an interesting page about this debate[4], the page ends with the line, If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

    I have also found few article supporting this,

    The Tragedy Of Checked Exceptions by Howard Lewis Ship
    Exceptions are Bad by  Jed Wesley-Smith

    Also, few articles on general exceptional best practices,

    Exceptional practices By Brian Goetz

    0 0
  • 06/06/12--07:33: Doing more as a Programmer
  • In this post I want to write about my first talk titled Doing more as a Programmer. This presentation is about maximizing your value as a programmer by enhancing the way you interact with yourself, your surroundings, with community and to your career.

    I have attached the presentation here, it is available on SlideShare.
    I had fun presenting it in my office, hope you will enjoy it too.

    0 0

    Recently I have experimented with hibernate cache. In this post I would like share my experience and point out some of the details of Hibernate Second Level Cache. On the way I will direct you to some articles that helped me implement the cache. Let's get started from the ground.

    Caching in hibernate

    Caching functionality is designed to reduces the amount of necessary database access. When the objects are cached they resides in memory. You have the flexibility to limit the usage of memory and store the items in disk storage.The implementation will depend on the underlying cache manager. There are various flavors of caching available, but is better to cache non-transactional and read-only data.

    Hibernate provides 3 types of caching.

    1. Session Cache

        The session cache caches object within the current session. It is enabled by default in Hibernate. Read more about Session Cache. Objects in the session cache resides in the same memory location.

    2. Second Level Cache

         The second level cache is responsible for caching objects across sessions. When this is turned on, objects will be first searched in cache and if they are not found, a database query will be fired. Read here on how to implement Second Level Cache. Second level cache will be used when the objects are loaded using their primary key. This includes fetching of associations. In case of second level cache the objects are constructed and hence all of them will reside in different memory locations.

    3. Query Cache

    Query Cache is used to cache the results of a query. Read here on how to implement query cache.When the query cache is turned on, the results of the query are stored against the combination query and parameters. Every time the query is fired the cache manager  checks for the combination of parameters and query. If the results are found in the cache they are returned other wise a database transaction is initiated.  As you can see, it is not a good idea to cache a query if it has number of parameters or a single parameter can take number of values. For each of this combination the results are stored in the memory. This  can lead to extensive memory usage.

    Finally, here is a list of good articles written on this topic, 

    1. Speed Up Your Hibernate Applications with Second-Level Caching
    2. Hibernate: Truly Understanding the Second-Level and Query Caches
    3. EhCache Integration with Spring and Hibernate. Step by Step Tutorial
    4. Configuring Ehcache with hibernate

    0 0

    As a typical Java developer I never monitored the memory usage of my application apart from following typical best practices like closing the connections, streams etc.. Recently we were struck with few issues in our JBoss servers that I had to dig in to the memory management. 

    One of the best thing in java is that the developers are not required to handle the memory allocations when the objects are created. The JVM does that for us. Most of the time we just need the outer layer knowledge of heap memory and garbage collector. I will share some really interesting investigations that I had. I is a huge topic and I am writing from a point of view of a web application developer, what all minimum I thought we should understand about it.

    The Tools

    There are number of good tools available to profile the java applications some of them are,

    1. Your Kit Java Profiler

    2. JProfiler 
    3. Eclipse MAT
    4. Visual VM

    Out of these Your Kit and JProfilers needs licences and others are free to use products. We are going to use VisualVM. It is a simple yet powerful tool and comes bundled inside the JDK. It has power list of plugins that you can download and use. To start using VisualVM, go to your <JDK_HOME>\bin and run the jvisualvm.exe. I found the below articles it useful to get going. 

    1.Profiling With VisualVM
    2.VisualVM performance tuning tool
    3.How to Get VisualVM to Profile JBoss Without Crashing

    Since we are talking about memory here make sure you install the Visual GC plugin on the VisualVM as told in this article.

    Setting the stage - JVM Memory Structure

    The JVM Memory is divided in to 3 parts as shown in the below image. In our applications we are concerned about the Heap Memory. We can input this value to JVM using the parameters,

    -Xmx<size> - to set the maximum Java heap size
    -Xms<size> - to set the initial Java heap size

    JVM Memory Structure

    The non-Heap memory stores per-class structures such as runtime constant pool, field and method data, and the code for methods and constructors, as well as interned Strings.

    Here is a nice article with more details on the JVM memory sizes. Read Javin's article on JVM Heap space here

    The one common confusion is about the stack memory and heap memory. This is well explained here.Stack values only exist within the scope of the function they are created in. Once it returns, they are discarded. Java only stores primitives on the stack. This keeps the stack small and helps keeping individual stack frames small, thus allowing more nested calls. Objects are created on the heap, and only references (which in turn are primitives) are passed around on the stack.

    Now, Lets get real. Given below the image from Visual GC, a plugin inside the VisualVM as told earlier. We see many graphs here a detailed decription of the output is available here

    The Game begins - What happens when the application runs

    When the objects are created, they reside inside the Eden. When the Garbage collector(GC) runs, if the object is dead (means they are no active references) it is flushed out otherwise they are moved to S1(Survivor Space 1) or S2. This is called a GC cycle. Internal GM algorithm decides the frequency of the GC cycle. Eden + S1 + S2 section of Heap memory is called as Young generation. Objects that survives a fixed number of GC cycles are moved in to Old Gen space. Most number of java objects die as infant and never reach Old Gen. This typically includes local variables which are flushed after the methods are executed.

    The frequency of GC cycles inside the Old Gen is much lesser than Young Gen. Typical examples of Old Gen objects are singletons, cached objects and other application wide used data.

    When things do not go as per the plan

    In a typical application there will be less variation inside the Old Gen space. If the Old Gen space grows linearly with time even after the GC cycle that would lead to a OutOfMemoryError. This might be a indication of a memory leak inside the code. However we might need to use a profiler to find out the exact reason for the same. Here is a Dzon article on some of the Causes of Java EE Enterprise Performance Problems.

    These are the basic building blocks of how JVM memory is organized and reacts when the application is executed. From this point there are lots of topics including tuning the memory parameters and garbage collector. I will add some of the useful resources related to this.

    1. Java Performance Tuning, Profiling, and Memory Management
    2. InfoQ Presentation : Diagnosing Web Application OutOfMemoryErrors
    3. InfoQ Presentation : Everything I Ever Learned about JVM Performance Tuning @twitter
    4. InfoQ Presentation : Extreme Performance Java  
    5. Java theory and practice: Garbage collection and performance

    0 0

    In this post I would like to write on how to succeed in a technical interview based on my experience as an interviewer. Most of the interviews follows some patterns. If you understand it and frame your response in the same way you can clear any interview. If you don't know stuff this might not help you, but if you are prepared, this article will help you show of your full potential.

    If you are skillful the only reason you can loose an interview is by lack of preparation. You may know all the stuff but you still needs to prepare by reading books, article etc.. Theses may not teach you anything new but will help in organizing things that you already know. Once you have organized information it is really easy to access it. You should read not only for interviews, make it a practice and get better at your job.

    Most of the time interviewer is looking for a candidate who can work with him. The vacancy may be in other teams but they use this parameter to judge. Mostly this article contains general tips. These are targeted for 2 to 6 years experienced candidates.

    1. Be honest and don't bluff

    Answer what you know, confidently. If you have been asked a question that you don't know, Start by telling "I am not sure, but I think It is .....". Never tell a wrong answer confidently. That will make them doubt your correct answers also or may feel that they were guesses. You can't use this technique for every question, but I would think 25% is a good amount. Most importantly this shows your ability to think and a never die attitude. No one wants to work with people says "I can't do this". Try to do some thing about all the questions.

    2. Be ready to write Code

    If you are been asked to write some code, be careful and follow some basic standards. I heard people telling me "I forgot the syntax..." and this for the syntax of a for loop. No one expect you to remember everything but basics like looping, if conditions, main method, exceptions are never to be forgotten. If you did, brush them up. Always write the code with good indentation using lots of white spaces. That might make up for your bad handwriting!!

    3. Get ready to explain about your project

    As engineers you have to understand the business before you start code it. So you should be able to explain what is being done in your project. Write down 3-4 lines that will explain the project in high level. By hearing the lines some one out side your team should get an idea about it. Because we always works inside on features, most of the time it is difficult to frame these. Check your client's internal communications how they are marketing and get some clue from it. Practice what your are going to say with friends make make sure you are on to the point.

    Once you have explained about the business needs then you will be asked about the technical architecture of the project. You have to be prepared with a architecture diagram that shows how the interaction of components in your project. It don't have to be in any specific UML format, but make sure you can explain stuff relating to the diagram you have drawn. For example if you are working in a web application show how the data is flow from UI to DB. You can show different layers involved, technologies used etc.. The most important part is you should be clear in your mind about what you are currently working on. 

    4. Convert arguments to conversation

    Even if you know that that person is wrong do not argue and try to continue the conversation saying "Ok, But I am not so sure if that is correct, I will check that out". This keeps the person in good terms. Be an active listener during the interview use reference to your experience when you are answering. 

    5. Be prepared for the WHY question

    Good interviews focus on the question "Why?". It might start with "What" but will end in "Why?". For example in Java typical question would be "What is the difference between String and StringBuffer?". A follow-up why question will be like "Why is String has so-and-so" or "How is it done..?". Be ready to give inside information by answering "How?" and "Why" parts of he question.

    6. Tell about your best achievement

    During your work there might be something that you consider as your best achievement. It is important to describe it in such a way that interviewer feels that you have did something extraordinary there. So, prepare a believable story on how your abilities helped you complete that task. It is important to prepare this because it takes time to dig your memory and find situations.

    7. Do you have any questions for me?

    This question gets repeated in every single interview. Here you don't actually care about the answers; but you should make yourselves look good by asking "smart" questions. This article will help you in this.

    0 0

    Last week I was trying to create a report using Jasper. In this post I will document some of the resources and links so that it will be useful for any one looking for similar information. I will cover life cycle of Jasper reports, examples and Dynamic Jasper. 

    The Jasper Reports is the world's most popular open source reporting engine. It is entirely written in Java and it is able to use data coming from any kind of data source and produce pixel-perfect documents that can be viewed, printed or exported in a variety of document formats including HTML, PDF, Excel, OpenOffice and Word.

    JasperReport Life Cycle

    As in the image the life cycle has 3 distinct phases,

    1. Designing the Report

    In this step involves creation of the JRXML file, which is an XML document that contains the definition of the report layout. We can use the either iReport Designer or a text editor to manually create it. Using iReport Designer, the layout is completely designed in a visual way, so you can ignore the real structure of the JRXML file.

    Here is the detailed tutorial on designing a report using iReport. We can also use Dynamic Jasper described later in the article to design a report.

    2. Executing the report.

    Before executing a report, the JRXML must be compiled in a binary object called a Jasper file(*.jasper). This compilation is done for performance reasons. Jasper files are what you need to ship with your application in order to run the reports. Once the report is compiled it is filled with data from the application. The class net.sf.jasperreports.engine.JasperFillManager provides necessary functions to fill the data in the reports.

    The report execution is performed by passing a Jasper file and a data source to JasperReports. There are plenty of types of data sources, it's possible to fill a Jasper file from an SQL query, an XML file, a csv file, an HQL (Hibernate Query Language) query, a collection of Java Beans, etc... If you don't find a suitable data source, JasperReports is very flexible and allows you to write your own custom data source.

    JasperFillManager.fillReportToFile( "MasterReport.jasper" , parameters, getDataSource());

    This operation creates a Jasper print file (*.jrprint), which used to either print or export the report.

    3. Exporting to the desired format

    Using the Jasper print file created in the previous step we shall be able to export it into any format using JasperExportManager. Jasper provides various forms of exports. This means with the same input we can create multiple representation of the data. Jasper inernally uses different APIs to create documents. But these complexity are hidden by the simpler JasperExportManager.

    JasperExportManager. exportReportToPdfFile( "MasterReport.jrprint" );

    In a nutshell the life cycle can be summarized in the below image

    Image from Ramki Tech

    References and other good articles on Jasper Reports Life Cycle


    I have found it really hard to find a working example of Jasper report. But it is right there inside the package shipment!. Once you have downloaded the Jasper Library go to demo\samples, you will find a lot of sample programs. Many of these needs a working HSQL DB connection, to activate it go to demo\hsqldb and start the server. Every folder has a readme.txt file which will help you in understanding how to run it. All the examples can be executed using ant tasks.

    Here is a list of few other sources.

    Simplify report creation using Dynamic Jasper

    DynamicJasper (DJ) is an open source free library that hides the complexity of Jasper Reports, it helps developers to save time when designing simple/medium complexity reports generating the layout of the report elements automatically.

    The project homepage provides lots of examples and code snippets on how to use the library. I have been using it for some time and it is a pretty stable replacement for the JRXML file.While using dynamic jasper the report design is coded in Java. Which means every time the report is compiled, filled and exported. By using dynamic jasper we are replacing the first step in the above mentioned jasper life cycle. Even with dynamic jasper you need the jasper library and other dependent files.

    Here is some more examples of Dynamic Jasper usage.

    0 0

    Planning to start something new in this year? You can try online learning!!. Online education is gaining popularity over the last few years, as it should. I have tried few of them last year and will share my experience with them in this post. Since I am a software developer we are going to focus on the materials related to it.

    So, here is a list of 15 sites that you should visit before you make you make your choice. I have not used much on all of them, but worth a spending some time. The italic text below the title are taken from the respective sites. The order of names are arbitrary and does not carry any significance.

    OCW makes the materials used in the teaching of MIT's subjects available on the Web.

    Add caption

    2. Coursera

    We are a social entrepreneurship company that partners with the top universities in the world to offer courses online for anyone to take, for free. We envision a future where the top universities are educating not only thousands of students, but millions. Our technology enables the best professors to teach tens or hundreds of thousands of students.

    3. Khan Academy

    Learn almost anything for free

    6. Code School

    Code School teaches web technologies in the comfort of your browser with video lessons, coding challenges, and screencasts.

    Whether you are completely new to coding or a developer looking to learn a new language, LearnStreet courses make it engaging and fun to create with code. Our interactive courses are designed to help you learn by actually writing real code and getting immediate feedback. is a video tutorial web site offering cutting edge programming and computer tutorials. We specialize in focused and linear content. WiBit is a great place to start learning how to program, or to pick up new skills even if you've been at it a while.

    Solve interesting challenges and also get connected to amazing tech companies if you are interested. Join in to be among the elite group of talent in the world.

    10. PeepCode

    Specialize in screencast tutorials for professional web developers and designers. Learn advanced Ruby, JavaScript, Ruby on Rails, Node, Git, Design, and connect with developers you admire in our popular Play by Play series.


    At P2PU, people work together to learn a particular topic by completing tasks, assessing individual and group work, and providing constructive feedback.

    0 0

    This post is about 5 things that I am planning to do this year. I have created it for me to track my progress then thought it can be a good direction for anybody similar.

    1. Create an application using a NoSQL Data store and connect it with Java

    If you have yet not understood the NoSQL databases its the best time. Lots of choices on the NOSQL side, may be MongoDB or Hadoop can be a starting point. We can create applications using Spring Data or the native Java adapters to connect to the Data Store.

    2. Get the first app on Java PaaS on Cloud and ask your 5 friends to use it.

    You have many platforms available including Openshift backed by JBoss and Redhat , CouldFoundry backed by Spring source and VMware. Cloud is the future of application deployments and Software as service gaining more popularity. From a developer point of view nothing really changes apart from the configurations and deployment.

    3. What really is Software Design?

    Read the GOF Design Pattern catalog and Search your project for the usage of it. If you are not using them check if you have similar patters. If you have a Java enterprise application you can check for Java EE patterns. Take a existing use case and think of possible alternative implementations.

    4. Learn a new Programming Language and create a sample project

    I think here you have 2 broad choices, Ruby or a JVM functional language. There are a number of functional languages available. It will help you become a polygot programmer.

    5. Contribute to the community

    You should be doing it already if not it is the time to start. There are a number of ways including Community Forums, Stack overflow or write a blog
    on how your leanings.

    0 0

    I have been looking in to NoSQL databases for few months and would like to share my experience with it. This is a post might help you if you indent to start learning about the NoSQL Databases. I would try to link the resources which I found useful here.

    Step 1: What is NoSQL?

    NoSQL DEFINITION: Next Generation Databases mostly addressing some of the points: being non-relational, distributed, open-source and horizontally scalable. The original intention has been modern web-scale databases. The movement began early 2009 and is growing rapidly. Often more characteristics apply such as: schema-free, easy replication support, simple API, eventually consistent / BASE (not ACID), a huge amount of data and more. So the misleading term "nosql" (the community now translates it mostly with "not only sql").

    As seen on

    Martin Flower'sNoSQL page is a good starting point. His below talk on Goto Conference explains the need and structure of NoSQL data stores. Martin and Pramod has written a book titled  "NoSQL Distilled: A Brief Guide to the Emerging World of Polyglot Persistence"  and is a good read. It summarizes his talks and other blog post into a book.  Martin has been an influential speaker on this topic and has written number of articles on this. I have read and seen many introductions but his work helped me to get things in to my head.

    If you likes to view the slides, then the below presentation by Tobias Lindaaker on slideshare might inspire you. He gives similar ideas.

    MongoDB has an online course MongoDB for Java Developers  which is really useful if you are interested in trying out things.

    Step 2: How and for what are NoSQL used in Real world?

    Once you have some idea, try to find the usage patterns. The above presentations will give lot of information on how these systems are used. You could go through the below links, which explains how specific business problems are solved using NoSQL. This is important because we could easily relate the case studies and get more insights into the capabilities of these systems.

    1. MongoDB Customers page.
    2. Powerd By Haddop 
    3. Neo4J Customers Page
    Step 3 : Find Usage Patterns that you could work on!

    Once you have reached this point, you should try and implement the concepts. Look back at the application that you are working on and see if there is a need for an alternative data store. Do you store Product recommendations? Do you have issues with heterogeneous data? Can your application compromise ACID model for scalability? Do you store XML files or Images on you relational DB?  These are some of the questions that you could ask. This way you could determine if there is a serious need of a investigation for a alternative persistence mechanisms. This  is in no way means removing the RDBMS completely but moving to a polygot structure of data stores.

    If there is no opportunity to try out these concepts in your work, you could create your own test projects and implement them. This way you would encounter problems and will learn from them.

    0 0

    Most of the enterprise Java applications share some similarities in their design. Mostly the packaging of these applications are driven by the framework used by them like Spring, EJBs or Hibernate etc. Alternatively you can group you packages by features. Like any other item regarding modeling this is not free from any issues. Lets discuss some trade-off and how get around them. In this post we will discuss the pros and cons of both approaches against common usage scenarios.

    Package By Layer (PBL)

    This is a the first thing that developers do when the create an enterprise application in to split it to number of layers like DAO, SERVICE, VIEW etc.. This gives nice separation of code when we use different frameworks at different layers. For example if I were to use Hibernate, Spring and JSF, then I will have all my Hibernate dependent code in the DAO layer and JSF related code in the VIEW Layer. This is sort of good in case I need to migrate to a new framework only at the view layer or DAO Layer.

    Package By Feature (PBF)

    Package-by-feature uses packages to reflect the feature set. It places all items related to a single feature (and only that feature) into a single directory/package. This results in packages with high cohesion and high modularity, and with minimal coupling between packages. Items that work closely together are placed next to each other. They aren't spread out all over the application.

    This also increases coherence as a large percentage of a the dependencies of a class are located close to that class.

    Comparing the approaches

    Let me compare both the approaches in below dimensions.

    1. Adding a new Feature.

    In case of PBL code has to be added to VIEW, SERVICE and DAO Layers and it can be tedious. PBF solves this problem by grouping all the code related to same feature in to a single directory.

    2. Changing a framework used.

    As discussed already PBL makes it easier to change a framework as all the related code are kept at same place. Here we know exactly the scope of the change and its impact. In case of PBF we need to dig into all the feature set to see the framework related classes.

    If you choose to migrate the framework module by module, then it could be argued that PBF is better than PBL.

    3. Code Navigation.

    As developers needs to work on the features most of the time using PBF is easier for code navigation. When you know exactly know what has to be done its not much advantage.

    4. Keeping the Common Code.

    Every application will have some components which will be reused across the features ie, the features are not always exclusive. In such case if we package all the features separately the interactions between them can be quite messy. As a general principle we need to reduce such interactions and increase the cohesion inside the package. We can get around the situation be adding such entities to a common package. This approach is used in many projects including Hibernate.


    Most application will have 4 types of classes. ie,

    1. Domain Objects
    2. Business Services
    3. Data Retrieval Logic
    4. Data Representation Logic

    If we use PBF it gives us a good structural representation but does not give any functional representation. We need our architecture to resemble the problem domain. So its better to use Package By Feature style. We could internally classify the classes by using naming conventions like MyFeatureDAO or MyFeatureService . This way we could communicate the intend of the classes.

    I have found some discussions on this topic and hope that might also help you choose.

    0 0

    I have finished reading the book titled "NoSQL Distilled: A Brief Guide to the Emerging World of Polyglot Persistence" written by  Martin Fowler and Pramod J. Sadalage recently and thought of a writing short review. First of all it short book and you can run through the pages fast. As the title says, the book is really an introduction of No SQL databases.

    It was..

    The number one reason for the use of NoSQL databases is not performance and should be our use case. This means if our data model does not fit well in to the relational model, rather than twisting the data we can choose alternate data stores. This is absolutely critical if you want NoSQL to be used in most of the mid sized enterprise applications.  Also companies will start to believe that they should consider NoSQL it even if they are not Google or Amazon. 

    Normally the technology books written by its creators of it will only focus on the advantages of using it. It can be quite an issue if you do not do proper research before choosing your application architecture. Since both Martin and Pramod do not belong to this category, they does a fair evaluation of various choices available to us. The section which says where to use it and where not to use is particularly impressive on that front.

    Even though the book is selling you a new idea of NoSQL databases, it does not plays down the significance and importance of existing RDBMS. The book also brings light to some of the fundamental trade offs in the world of data stores like  consistency, availability and performance.

    and is also..

    When I was reading the book I thought that Polygot persistence is about using multiple data stores in same application depending on the use cases. But authors also seems to suggest that applications should wrap around the data stores with services ( like web services or REST). If we need to do this ideally we could only have one data store accessed by one service. Which would conflict the first statement. I am not sure about the reverence this question but I would love to have read more about using the different data store in the same application and its pros and cons.

    I mean to say, 

    This is a very great book if you are  looking get in to wild jungle of NoSQL databases. The authors does a great job in giving the brief introduction and making sure the basics are covered.

    0 0

    Recently I was reviewing Gang of Four Design Patterns and created a Trello board for the same. Well, Here is how it look like!

    Hope it could be useful for others as well.

(Page 1) | 2 | newer