Monday 13 June 2011

New Features in Java 5

Java 5 comes up with loads of new implementation which adds up to java 1.4 release. And also Java 5.o is known as Tiger release officially.

To start with, key features like Generics, Auto boxing/Unboxing, Var Args, Static Import, Enhanced For Loop, Type Safe Enums and Annotations.

There are couple of changes at the Virtual Machine, User Interface (Swing, AWT) and Base Library side as well.
As this post is targeted at the developers we would discuss on the Language features added to the ocean.

Generics
This long-awaited enhancement to the type system allows a type or method to operate on objects of various types while providing compile-time type safety. It adds compile-time type safety to the Collections Framework and eliminates the drudgery of casting. Refer to JSR 14.

Well, first of all, nobody can dispute that Generics are a solid concept that tends to improve the robustness of your code. The reason why they are so usually controversial regardless of the language is because of their implementation.
In a nutshell, I have this to say about Java generics: my code feels more robust, but it's harder to read.
So what's the problem?
Redundancy.
First of all, I have always had a hard time with the redundancy introduced by the necessity of casting in general. For example, instead of writing:
Map accounts = new HashMap(); // no generics ... Account a = (Account) accounts.get("Cedric");
why can't I just write:
Map m = new HashMap(); // no generics ... Account a = m.get("Cedric");
and let the compiler introduce a silent cast, since obviously, it's an object of type Account that I am trying to retrieve from the Map?
Obviously, Generics don't solve this problem entirely but they make a decent job at alleviating it somewhat. But they also make it worse in some other ways:
Map<String, List<Account>> accounts = new HashMap<String, List<Account>>();

Not only is the code significantly harder to read, but it fails to obey the DRY principle ("Don't repeat yourself"). What if I need to change the value type of this map from List<Account> Collection<Account>? I need to replace all these statements everywhere in my code. While IDE refactoring will help, it's still an awful lot of code for a modification of this kind that hardly impacts the semantics of this code.
Admittedly, there is no nice way to avoid this syntax when you are creating a new object, but what I am driving at is that I think Generics would have been better off if typedefs had been introduced with them.
Or so I thought at first.
But after thinking about it more, I realized that typedefs were the wrong solution to the problem, because simply put, they don't add anything to the use of a separate class to define your complex Generic type.
class AccountMap extends HashMap<String, List&lAccount>> { ... }
Except for the fact that you need to extend an implementation (HashMap, and not Map, obviously), this solution is probably better than introducing typedef, which has its own quirks.
I haven't gone to this trouble so far, but my recommendation would be: do it if you write the type more than three times (twice in the initialization and you use it more than once in your code).
Except for this little annoyance, I am quite happy with Generics overall and I particulary enjoy reading the TestNG Javadocs so nicely typed.

Enhanced For Loop
This new language construct eliminates the drudgery and error proneness involved in iterators and index variables when iterating over collections and arrays. ( impl of JSR 201)
Auto Boxing/UnBoxing
Easeness in conversions from primitives types to wrapper types. Say Integer to int, Boolean to boolean.

Check the below example for illustration
int i = 0;
i = new Integer(5); // auto-unboxing
Integer i2 = 5;  // autoboxing

Typesafe Enums
This flexible object-oriented enumerated type facility allows you to create enumerated types with arbitrary methods and fields.    It provides all the benefits of the Typesafe Enum pattern  without the verbosity and the error-proneness.

Variable Arguments simply VarArgs
Eliminates the manual ache to box up the array list arguments while invoking methods which accept variable arguments

Static Import
Avoids qualifying static members with class names without the shortcomings of the Constant Interface anti Pattern.

Annotations
Annotations basically does automation internally which does generate boiler plate code on the instruction of the developer. This leads to a declarative programming style where programmer specifies what to be done and the tool does the rest. Also eliminates the back up files to be kept up to date, instead the information is maintained the source file as meta data. (Refer to JSR 175)

Apart from these Language Feature Implementations, Java 5 also has crucial modifications done in the Tools section like  java compiler, javadoc tools.
Implementations at the Integration side also took place.
RMI, JDBC, CORBA, JNDI are the top level libraries modified to incorporate certain functionality.


New Features in Java 6

I was planning to post this for a long time, but found the time now. I looked at the JDK 6 and some new features are very good. Though I have to really get hands-on with this version, i managed to look under the hood and come up with a concise and "usable-for-everybody" list of new things.
First thing first – This version is a great great improvement on performnace. I did not do any profiling, but our programs are starting much faster. We deploy an EAR on JBoss. JDK 5 used to take atleast 75-80 seconds on my machine to come up, but with JDK 6, its consistently below 65 seconds on the same machine. JIT has also been improved, so I think part of it is coming from there.
Other features:
1. Scripting for Java (JSR 223): Now scripting languages can be used with Java. You get best of both worlds – flexiblity of scripting languages and power of Java. JDK 6 bundles a scripting engine for JavaScript (based on Mozilla Rhino). It also supports third party scripting engines and if you go to java.net, you can downaload and use engines for all popular scripting languages like PHP, Python, Ruby-on-Rails, AppleScript etc. The engines for XPath and XSLT are also available, though I have to see how to use them.
Scripting is good in many ways, like dynamic nature (no need of giving a datatype to a variable). Generally, a scripting language is good in doing few operations in a very efficient way, like PERL for text processing. These features can be exploited for faster implementation. Other advantage could be to integrate the legacy scripting code with new Java applications.
The new tool ‘jrunscript’ has been added to try out the things in scripting way.
2. Desktop features: There are many new features, but two are worth mentioning. One is ability to show the splash screen and other is the system tray icon. These two features are very useful and the overall experience of Java application will be more like a native application. The other thing is, everybody was doing it anyway in their own way. Now its not required as Java is here to help you out.
3. I/O: Two new good features. A new class ‘Console’ is added. It provides support for reading the passwords from console without displaying them.
Other is, in the File class new utility methods have been added for getting the total space on the disk, total free space on the disk and total usable space on the disk.
4. Networking: In JDK 6, cross platform NTLM is supported. It also comes with a default Cookie Manager. However, the biggest is that now JDK 6 gives you all required classes for creating a light-weight HTTP server. In fact, it also comes with a default implementation.
5. Monitoring and Management: Its very easy to find the deadlocked threads now using ‘findDeadlockedThreads’ method in ‘ThreadMXBean’. This could be very useful in error handling specially for enterprise applications. The error handler can restart the application when it detects the deadlock.
New classes and methods have been added to get a list of locks owned by a thread and also to find which stack holds the lock for a monitor. Another method that can help in desiging better application experience is ‘getSystemLoadAveage’. Apart from cosmetic value, this can be used to take certain runtime housekeeping opeartions.
I have to see what will be the performance penalty on using these methods. From the name of it, they look pretty expensive.
JMX has been upgraded to JMX 1.4 in JDK 6. JConsole, the swing based JMX client is now officially supported. It doesn’t work with JBoss though as JBoss comes with its own JMX implementation.
It is facinating to see how Java has transformed itself into JMX-aware machine. Most of the thing are controllable/viewable through JConcole.
6. Tools Package: A new package (javax.tools.*) is given for using the Java tools in programmatically. The most useful one, I guess is JavaCompiler. It allows you to invoke the compiler programatically in a standard way.
7. Others:
a. Profiles and debuggers can now attach to running VM. The VM doesn’t need to be started in a debugging-capable mode. This will be a huge help in the diagnosis.
b. RMI calls can be made over SSL.
c. Few new Collection interfaces are added.
d. JAR tool will maintain the timestamps of the files while extracting them.
e. JAXB has become part of JDK 6. ‘xjc’ tool also comes with JDK now to generate the binding classes. However, there is no compatible ANT task (so far), so you will have to use ‘exec’ in the build scripts for using ‘xjc’
f. DerbyDB (formerly Cloudscape) is bundled with JDK. This can be used for DB operations in the development time.

Following are the new features in SE 6.
  1. Changes in I/OThis is a new feature added in Java SE 6, which has the ability to read text from a terminal without having it echo on the screen through java.io.Console.
      
  2. Collections Framework EnhancementIn Collection framework, we are able to improve the performance hashing function that is used by java.util.HashMap. It provides some new Collection interfaces also.
      
  3. Changes in jar and zipJar and zip support has been enhanced in JDK 6. In this, two new compressed streams have been added. These are java.util.zip.DeflaterInputStream and java.util.zip.InflaterOutputStream.
      
  4. Java Web Start enhancements in version 6The cache format of Java Web Start and Plug-In has been fully changed. All dialogs have been redesigned and consolidated between Java Web Start and Plug-In to be more user friendly.
      
  5. JMX API EnhancementsEnhancements has been made to the JMX API in Java SE 6 like : JMX API now completely supports Generics, MXBeans have been added and much more?
      
  6. Java Platform Debugger Architecture EnhancementsJVMDI has been deleted in JAVA SE 6 and JPDA has been added. Some new Methods are included like boolean boolean canGetInstanceInfo() and much more?
      
  7. Java SE 6 Monitoring and Management EnhancementsAPI provided by JAVA SE allows you to monitor and manage the JVM in the package java.lang.management. JAVA SE 6 includes some enhancement to this API.
      
  8. New Package java.util.spi in JDK 6A new package Java.util.spi has been included in JAVA SE 6.
      
  9. Networking features and enhancements in Java SE version 6.0This feature include enhancement in networkInterface, support for Internationalized Domain Names, HTTP Negotiate Authentication and much more?
      
  10. Enhancements in java.lang.Class and java.lang.reflectSome new Methods are included in java.lang.Class like : getInterfaces(), getClasses(), getConsturctors(), getMethod(String, Class?) and much more?.
      
  11. Enhancement in RMI for JDKTM 6java.rmi.MarshalledObject now support generics
      
  12. JAVA SE 6 Security EnhancementsJAVA SE 6 has added support for some security functionality: the XML Digital signature API and implementation, Smart Card I/O API. And much more?
      
  13. Serialization Changes and Enhancements in JAVA SE Development Kit 6The new method ObjectStreamClass.lookupAny now used to obtain an ObjectStreamClass instance for a non-serializable Class
      
  14. JavaTM Virtual Machine TechnologyDTrace support has include in Java SE 6 HotSpot VM. The hotspot provider makes available probes that can be used to track the lifespan of the VM, thread start and stop events
      
  15. Scripting for the Java PlatformBy using this Features developers integrate Java technology and scripting languages by defining a standard framework and application programming interface (API)
  16. Leveraging Security in the Native Platform Using Java SE 6 TechnologyThe JAVA SE 6 provide a large set of security APIs. These Security APIs span a wide range of areas, including cryptography public key infrastructure, secure communication, authentication, and access control.
  17. JAX-Web Services 2.0 With the Java SE 6 PlatformMost exciting new features of the JAVA SE 6 is support for the Java API for XML Web Services (JAX-WS), version 2.0.

Thursday 9 June 2011

Spring Stored Procedure Example with Database as Sybase On Eclipse IDE

Advantage of using Spring Stored Procedure :

Some of the value-add provided by Spring's JDBC abstraction frameworkare below:
  • Define connection parameters
  • Open the connection
  • Prepare and execute the statement
  • Set up the loop to iterate through the results (if any)
  • Process any exception
  • Handle transactions
  • Close the connection
  • Spring takes care of all the grungy, low-level details that can make JDBC such a tedious API to develop against.


 Step by Step tutorial for writing and running a spring stored procedure example with eclipse IDE.

1)      Goto Eclipse > Help > Eclipse Marketplace >  click "Popular" tab
 Under “Popular” tab install Spring IDE



Click on image to zoom


2) Create a new Spring Project as shown below


Click on image to zoom


3)  Give the name of the new spring class as in below screen and click “Finish”

Click on image to zoom



4) Following spring directory structure will be created by eclipse

Click on image to zoom



5) Right click on the project > select properties > Java Build Path > libraries

Add all the spring libraries jars in the Build Path

Click on image to zoom


6) Now in the src folder create a java class as below

Click on image to zoom

7) Give the package name and the class name and click “Finish”

Click on image to zoom


8) Below class structure is created now write your code as in example Fig. 1





package com.springsrc;

import java.sql.Types;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.SqlReturnResultSet;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.object.StoredProcedure;
import org.springframework.util.CollectionUtils;

/**
 * SpringCallStoredProc provides the Spring implementation with Stored Procedure
 * @author ramantechnicaltutorial@gmail.com
 * @version     1.0
 **/


public class SpringCallStoredProc extends StoredProcedure{

     
          public static void main(String[] args)  {
            ApplicationContext appCtx = new ClassPathXmlApplicationContext("springbean.xml");
              DataSource dataSource = (DataSource) appCtx.getBean("dataSource");
                                      
            SpringCallStoredProc callProc = new SpringCallStoredProc();
            callProc.testDBConnection(dataSource);
              System.out.println("Stored Procedure executed successfully");
          }
         
          void testDBConnection(DataSource dataSource) {
            /* To connect to the SYBASE through Spring we can use either
             * org.apache.commons.dbcp.BasicDataSource or DriverManagerDataSource
             * the only important thing is to add the jconnect jar of SYBASE in the
             *  build path of the project as this jar contains the SYBASE driver
             * */

              MyStoredProcedure sproc = new MyStoredProcedure(dataSource);
              Map results = sproc.execute(4);
              /* printMap(results);*/            
              List employees = (ArrayList) results.get("Employees");
              if (!CollectionUtils.isEmpty(employees)) {
              /* Print the Employee id retrieved from procedure*/
                  System.out.println("Employee Id retrieved from Stored Proc : "+ ((Employee)employees.get(0)).getId());
            }
 
          }

          private class MyStoredProcedure extends StoredProcedure {
             
              private static final String PROC_NAME = "proc_sper_batch_details";

              public MyStoredProcedure(DataSource ds) {
                  super(ds,PROC_NAME);
                  setDataSource(ds);                              
                  declareParameter(new SqlParameter("4", Types.INTEGER));
                  declareParameter(new SqlReturnResultSet("Employees", new EmployeeMapper()));
                  compile();
              }

              public Map execute(int val) {
                  /* Pass input parameters Value*/
                  Map<String, Object> parameters = new HashMap<String, Object>(1);
                  parameters.put("4", val);
                  return execute(parameters);
              }
          }

          private static void printMap(Map results) {
              for (Iterator it = results.entrySet().iterator(); it.hasNext(); ) {
                  System.out.println(it.next()); 
              }
          }
      }
Fig. 1




9) Similarly create an Employee class as in Fig. 2 and EmployeeMapper class as in Fig. 3.




package com.springsrc;

public class Employee {
     
    private long id;
    private String contactname;
    private String orgname;
   
    public long getId() {
        return id;
      }
      public String getContactname() {
        return contactname;
      }
      public String getOrgname() {
        return orgname;
      }
      public Employee(long id, String contactname, String orgname) {
        this.id = id;
        this.contactname = contactname;
        this.orgname = orgname;
      }

}
Fig. 2



package com.springsrc;

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class EmployeeMapper implements RowMapper{

      public Object mapRow(ResultSet rs, int arg1) throws SQLException {
            Employee emp = new Employee(rs.getLong("NUMBER"), rs.getString("CONTACT_NAME"), rs.getString("org_Name"));           
            return emp;
      }

     
}
Fig. 3


10) Now create Bean configuration File. Right click on the peoject “src” and select “Spring Bean Configuration File”, give the name as “springbean.xml” and click “Finish” as shown below.





11) Define the bean properties in springbean.xml as in Fig.4
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
     
      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
          <property name="driverClassName" value="com.sybase.jdbc3.jdbc.SybDriver"/>
          <property name="url" value="jdbc:sybase:Tds:devase01:5000/database_web"/>
          <property name="username" value="eqa_user_dev"/>
          <property name="password" value="password"/>
    </bean>
     
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>
Fig.4


12) We have completed the coding part, now to build and run the example add the below jars.

  • Spring framework jars (Download from site http://www.springsource.org/download)
  • \apache\commons\dbcp\1_4\lib\commons-dbcp.jar (Download from site http://commons.apache.org/dbcp/download_dbcp.cgi )
  • \apache\commons\logging\1_0_3\core\commons-logging.jar(Download from site http://commons.apache.org/logging/download_logging.cgi)



13) Finally to run the stored procedure example right click on “SpringCallStoredProc” class and run as Java Application as shown below.




14) Eclipse Console retrieves the result from stored procedure and prints the desired output as shown below.








Explanation of Code

org.springframework.jdbc.object
Class StoredProcedure

java.lang.Object
  org.springframework.jdbc.object.RdbmsOperation
      org.springframework.jdbc.object.SqlCall
          org.springframework.jdbc.object.StoredProcedure