Showing posts with label Java5 / tiger. Show all posts
Showing posts with label Java5 / tiger. Show all posts

Thursday, April 28, 2011

Annotations in java5

  1. Java defines seven built-in annotations.
  2. Four are imported from java.lang.annotation: @Retention, @Documented, @Target, and @Inherited.
  3. Three, @Override, @Deprecated, and @SuppressWarnings, are included in java.lang.
Seeing them one by one:
@Override
@Deprecated
@SuppressWarnings
@Retention
@Documented
@Target
@Inherited

Thursday, April 14, 2011

USING SPRING’S STOREDPROCEDURE

One very useful portion of the Spring Framework is the StoredProcedure wrapper’s and the RowMapper objects. Together these allow you to call a stored procedure and then parse the result set back into a collection of objects with very little pain. Below is an example of how to do just this for a simple query like a user query.

public class MyStoredProcedure extends StoredProcedure {

    public MyStoredProcedure (DataSource ds, String spname,
            Map map, String sqlOutKey, Integer returnType,
            RowMapper rowmapper) {
        super();
        setDataSource(ds);

        /* resultset has to be declared first over other declare parameters */
        if (rowmapper != null) {
            declareParameter(new SqlReturnResultSet(sqlOutKey, rowmapper));
        }

        if (map != null) {
            Iterator itr = map.keySet().iterator();
            while (itr.hasNext()) {
                String key = (String) itr.next();
                Integer value = (Integer) map.get(key);
                declareParameter(new SqlParameter(key, value.intValue()));
            }
        }

        /*
         * sql out paramter has to be declared based on the order in stored
         * procedures, In all our stored procedures we have it after input
         * parameters
         */
        if (returnType != null) {
            declareParameter(new SqlOutParameter(sqlOutKey, returnType
                    .intValue()));
        }

        setSql(spname);
        compile();
    }
}

Next, we have the Mapper class:

public class UserMapper implements RowMapper {
    public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
        User user = new User();
        user.setUserId(rs.getString(Constants.USER_ID));
        user.setFirstName(rs.getString(Constants.FIRST_NAME));
        user.setLastName(rs.getString(Constants.LAST_NAME));
        user.setOrganizationName(rs.getString(Constants.ORGANIZATION_NAME));
        return user;
    }
}

Next, we have to query the actual stored procedure from a DAO. Here’s a sample method that would do just such a thing:

public Collection searchUsers(User user) throws Exception {

        Map lhm = new LinkedHashMap(4);
        lhm.put(Constants.USER_ID, new Integer(Types.VARCHAR));
        lhm.put(Constants.FIRST_NAME,new Integer(Types.VARCHAR));
                lhm.put(Constants.LAST_NAME,new Integer(Types.VARCHAR));
                lhm.put(Constants.ORGANIZATION_NAME,new Integer(Types.VARCHAR));

        UserMapper mapper = new UserMapper();

        // Call Stored Procedure
        EntitlementsStoredProcedure proc = new EntitlementsStoredProcedure(
            ds, StoredProcedureConstants.USER_SEL, lhm,
            Constants.RESULTSET, null, mapper);

        // Collect the criteria for the search
        Map map = new LinkedHashMap(4);
        map.put(Constants.USER_ID, user.getUserId());
        map.put(Constants.FIRST_NAME, user.getFirstName());
        map.put(Constants.LAST_NAME, user.getLastName());
        map.put(Constants.ORGANIZATION_NAME, user.getOrganizationName());

        Map results =  proc.execute(map);
        List resultList = (LinkedList)results.get(Constants.RESULTSET);

        //iterate of results list and print
        for (Iterator it=resultList.iterator(); it.hasNext(); ) {
            User user1 = (User)it.next();
            System.out.println(user1);
        }

        return resultList;
    }

That’s all there is to it! This shows just how simple it is to do queries in an object oriented way, and have generic row mappers. There are full object relational mapping solutions, such as Hibernate, that do a great job of solving the working with relational data in an OO way paradigm, but they take a LOT of configuration and can be daunting if you’re not accustomed to working with them. This solution, however, I feel works very well in simpler scenarios. It also allows someone who is used to looking at code to quickly read through and get an idea of how to use this.

One point to note: this gets even simpler when using generics that are introduced in Java 1.5.

Static Imports in Java 5

Static keyword is used to allow access to an attribute/ a method or a class without creating instance of it. (Some of you may argue that this is not object oriented way, but we leave that discussion aside for now.) We use static for those elements which do not change from instance to instance of a class. An example would be constant variables in a program. These values are stored using ‘public static final’ keywords. In enum article we have seen one way of managing logically linked constants. Static import tries to improve the way we store and use static elements in program.
Java says it has tried to address an anti-pattern – using interface for constants. Some of us may have used this type of design in programs, where constants are grouped in an interface and used by implementing that interface. This approach is wrong because it alters the purpose of having interfaces in a Java application. Interfaces are used to define highest level of abstract behavior and also to expose a contract to the world in terms of method signatures. Thus, we cannot use interfaces to store constants. An alternative is having them in respective functional classes or in a separate class which can be reused.
When we use this class, we import it and use it wherever the variable is required. Here is the example.
Constants class
package constants;  

public class MyConstants {  

public static final String CONSTANT1 = "constant 1";  
public static final String CONSTANT2 = "constant 2";  
public static final String CONSTANT3 = "constant 3";  
}  

 Class using constants without static import
import constants.MyConstants;  

public class WithoutStaticImport {  

public static void main(String[] args) {  
System.out.println(MyConstants.CONSTANT1);  
}  

}  


 
If you have many such constants, then every time you need to use these constants with class name in front of it. With static import, you can get rid of the class name and use constants directly. Let us see how.

Using Static Constant

import static constants.MyConstants.CONSTANT1;  

public class WithStaticImport {  

public static void main(String[] args) {  
System.out.println(CONSTANT1);  
}  

}  


Important Considerations:

  • Java suggests – use static imports sparingly because these reduce readability and maintainability of a program considerably.
  • Use it when you feel you are going to wrongly use inheritance (i.e. interfaces).
  • When number of variables is less and you can maintain the readability by using meaningful names.
Benefits of static import with already present static java fields
Here are some examples:
  • instead of System.out.println you can use out.println:
    Import the field:
    import static java.lang.System.out;

    So now in code you can write:
    out.println("Hello, World!");
  • PI instead of Math.PI
    area = PI * R * R
    look so much nicer than
    area = Math.PI * R * R
    

    Wednesday, April 13, 2011

    Pre-java 5 style enums

    Enumerations already existed in other languages like C, C++, SmallTalk etc. Enums are used primarily to handle a collection of logically grouped constants.
    But in java, in prior releases, the standard way to represent an enumerated type was the int Enum pattern:
    // int Enum Pattern - has severe problems!
    public static final int SEASON_WINTER = 0;
    public static final int SEASON_SPRING = 1;
    public static final int SEASON_SUMMER = 2;
    public static final int SEASON_FALL   = 3;

    Drawbacks of This Approach:

    • Type Safety: All statuses above may carry some business meaning, but in Java language context, these are just int values. This means any int value is a status for this Java program. So the program using these statuses can break with any int value not defined in this group.
    • Compile Time Constants: All these constants are compiled and used in the program. If you want to add any new constant then you will have to add it to the list and recompile everything.
    • Uninformative: When printed, these are just numbers for a reader. E.g. if a program prints status = 3, the reader will have to go and find out what does it actually mean. Amount of information available with the print is minimal.
    • Restricted Behavior: If you want to use these values in a remote call, or compare them, then you will have to handle it explicitly. Serializable, Comparable interfaces offered by Java for same purpose cannot be used. Also there is no room to add any additional behavior to the statuses, e.g. attaching basic object behavior of hashCode(), toString() and equals() methods.
    • Meaningless Switch-Case Use: When you use statuses above in switch case, you cannot use the variable names; instead you will have to use the meaningless/uninformative numbers to compare. Readability of program goes down considerably in this case.
    • Non-Iterative List: This is a list of values, but you cannot iterate over it the way you can on any collection.
    The solution to above problem is Enum data type in Java 5. Concept of Enum is obtained from the counterpart technologies like C, C++, C# etc. and also considering the Typesafe Enum design pattern in Effective Java book by Joshua Bloch:


    You can read this pattern here.

    Thursday, March 3, 2011

    Varargs in Java: Variable argument method in Java 5

    I think I am late for writing about varargs. The feature of variable argument has been added in Java 5 since its launch. Still I will write something about varargs.
    varargs has been implemented in many languages such as C, C++ etc. These functionality enables to write methods/functions which takes variable length of arguments. For example the popular printf() method in C. We can call printf() method with multiple arguments.

    1
    2
    printf("%s", 50);
    printf("%d %s %s", 250, "Hello", "World");

     

    Syntax

    Varargs was added in Java 5 and the syntax includes three dots (also called ellipses). Following is the syntax of vararg method for method called testVar :

    1
    public void testVar(int count, String... vargs) { }
     
    Notice the dots … in above code. That mark the last argument of the method as variable argument. Also the vararg must be the last argument in the method.
    Now let us check simple hello world varargs code.
     
    Example:
    public class HelloWorldVarargs {

    public static void main(String args[]) {
    test(215, "India", "Delhi");
    test(147, "United States", "New York", "California");
    }

    public static void test(int some, String... args) {
    System.out.print("\n" + some);
    for(String arg: args) {
    System.out.print(", " + arg);
    }
    }
    }




    In above code, the test() method is taking variable arguments and is being called from main method with number of arguments.


    So when should you use varargs?

    As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.

    Tuesday, September 21, 2010

    Enums in java

    In prior releases, the standard way to represent an enumerated type was the int Enum pattern:
    // int Enum Pattern - has severe problems!
    public static final int SEASON_WINTER = 0;
    public static final int SEASON_SPRING = 1;
    public static final int SEASON_SUMMER = 2;
    public static final int SEASON_FALL   = 3;
    
    But these are not type safe, and clearly naming them is bit of a problem.
    See here more for details. So in Java 5, they introduced Enums.

    Defining Enums
    Eg.
    enum Season { WINTER, SPRING, SUMMER, FALL } 
    public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
    SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }
    
    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }  
    public enum Shape { RECTANGLE, CIRCLE, LINE } 
      
    Note on Semicolon ( ; )
    Enum embedded inside a class. Outside the enclosing class, elements are referenced as Outter.Color.RED, Outter.Color.BLUE, etc.
    public class Outter {
    public enum Color {
    WHITE, BLACK, RED, YELLOW, BLUE
    }
    }

    Declaring enum variables and using enum values

    The enum class name can be use like any other class type in declarations. Usually enum values must be prefixed with the enum type name.

    Shape drawing = Shape.RECTANGLE;   // Only a Shape value can be assigned.

    Looping over all enum values with foreach loop

    The static values() method of an enum type returns an array of the enum values. The foreach loop is a good way to go over all of them.

    for ( Color c :Color.values() ) {
             System.out.print( c + " " );
    }


    Getting an integer equivalent of an enum value

    Each enum value in an enum class has an associated default value, starting with zero for the first value and incrementing by one for each additional value. This may be accessed with the ordinal() method.
    System.out.println(drawing.ordinal());     // Prints 0 for RECTANGLE.
     

    Input (Convert string to enum)

    The valueOf() method can be used to convert a string value to an enum value. Here is an example of reading in a Shape value from a Scanner object in.
    drawing = Shape.valueOf(in.next());
     
    or
    drawing = Shape.valueOf("RECTANGLE");
     
    The static methods valueOf() and values() are created at compile time and do not appear in source code. 
    They do appear in Javadoc, though; 
     
    Read more in Effective java for better practises.
     

    Chitika