Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, May 18, 2015

Solve Spring NoUniqueBeanDefinitionException

I encountered the NoUniqueBeanDefinitionException where-in Spring was unable to which class to inject for an Autowired variable even though the it was properly qualified!

This happened because the Qualifier did not get post-processed and so multiple implementations of the Interface type of the variable being injected were now available in the classpath. So Spring found more that one instance and was unable to decide which instance to inject for the particular Autowired target.

The turn on the default AutowiredAnnotationBeanPostProcessor which processes the @Qualifier , you need to add the line to the beans section of your spring configuration. Since this was missing from the beans section of the configuration file, the Qualifier annotation was ignored in this code:

    @Autowired
    public void setDao(@Qualifier("myDaoImpl") MyDAO dao) {

And here is a snippet of the exception that was logged:

 java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Injection of autowired dependencies failed for class [class my.package.impl.name.MyBeanClassName]; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void my.package.impl.name.MyBeanClassName.setDao(my.package.intf.name.MyDAO); nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [my.package.intf.name.MyDAO] is defined: expected single matching bean but found 4: myDaoImpl,secondDaoImpl,thirdDaoImpl,fourthDaoImpl

This error was resolved after adding the below line to the beans section of spring configuration:

<context:annotation-config></context:annotation-config>

Friday, May 15, 2015

Upgrade Hibernate 3..x to Hibernate 4.3.x

NOTE: This is a partial guide to upgrade your Hibernate 3 project to Hibernate 4.3.x

Hibernate has a come a long way from version 3.x to the latest version Hibernate 4.3.x with lots of major changes, bug fixes and enhancements:
  • Started using gradle for builds
  • Redesign the way SessionFactory is built
  • Improved metamodel
  • Initial osgi-fication by package splitting (public, internal, spi)
  • Migration to i18n logging framework (using jboss logging)
  • JDK 1.6 (JDBC4) as baseline

The following hibernate jars are required to be downloaded from the Maven Repository:

  1. hibernate-core-4.3.9.Final.jar
  2. hibernate-annotations-3.5.6-Final.jar
  3. hibernate-commons-annotations-3.2.0.Final.jar (DO NOT USE 3.3.0.ga version)
  4. hibernate-entitymanager-4.3.9.Final.jar
  5. hibernate-validator-5.1.3.Final.jar
  6. jboss-logging-3.1.3.GA.jar
Do not use hibernate-commons-annotations-3.3.0.ga.jar as it is a release mistake and will create more problems.

You can download the corresponding javadoc and source files by going to the Maven website and searching for: 
g:"org.hibernate" AND a:"hibernate-core" AND v:"4.3.9.Final"

Now that all the required jars are downloaded, hibernate3.jar will need to be replaced by hibernate-core jar; here is a simple guide to when to include rest of the jars.

To resolve the below error, add hibernate-commons-annotations-3.2.0.Final.jar to classpath and the JBoss library path:
NOTE: DO NOT USE hibernate-commons-annotations-3.3.0.ga.jar as it is a release mistake
java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/MetadataProvider
at org.jboss.hibernate.jmx.Hibernate.buildConfiguration(Hibernate.java:194)
at org.jboss.hibernate.jmx.Hibernate.buildSessionFactory(Hibernate.java:228)
at org.jboss.hibernate.jmx.Hibernate.startService(Hibernate.java:155)
at org.jboss.system.ServiceMBeanSupport.jbossInternalStart(ServiceMBeanSupport.java:289)
at org.jboss.system.ServiceMBeanSupport.jbossInternalLifecycle(ServiceMBeanSupport.java:245)
at sun.reflect.GeneratedMethodAccessor3.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

To resolve the below error, add jboss-logging-3.2.1.Final.jar to classpath and the JBoss library path:
Not resheduling failed loading task, loadTask=org.jboss.mx.loading.ClassLoadingTask@1219665{classname: org.hibernate.internal.CoreMessageLogger, requestingThread: Thread[main,5,jboss], requestingClassLoader: org.jboss.mx.loading.UnifiedClassLoader3@1b06041{ url=null ,addedOrder=2}, loadedClass: nullnull, loadOrder: 2147483647, loadException: java.lang.NoClassDefFoundError: org/jboss/logging/BasicLogger, threadTaskCount: 0, state: 1, #CCE: 1}
java.lang.NoClassDefFoundError: org/jboss/logging/BasicLogger
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)

Follow the Hibernate Code Migration Guide to make the appropriate changes as required:

  1. Initial move to ServiceRegistry.  For now, see design wikis or sources for more information.  Not all "services" have been migrated to this model yet.  The main ones (JDBC and transaction stuff) as well as lowever level one (classloading and such) have been migrated.  The rest will be moved during Alpha2 development.
  2. In an initial push toward osgi we started splitting up packages a little bit differently in this release. 
    1. The reason is to identify classes which are intended as
      1. public API, which are fully expected to be used in application code.
      2. internal implementation details, which are only intended for Hibernate use.
      3. SPI contracts, whch define
        1. extension contracts
        2. contracts with Hibernate internals exposed to these extensions
    2. This will potentially lead to some  packaging changes needed in user code:
      1. org.hibernate.dialect.resolver.DialectResolver -> org.hibernate.service.jdbc.dialect.spi.DialectResolver
  3. Deprecated methods that have been removed:
    1. References to org.hibernate.type.AbstractSingleColumnStandardBasicType and org.hibernate.type.SingleColumnType methods should be changed as indicated:
      1. nullSafeGet(ResultSet rs, String name) should be changed to 
        nullSafeGet(ResultSet rs, String name, SessionImplementor session)
      2. get(ResultSet rs, String name) should be changed to 
        get(ResultSet rs, String name, SessionImplementor session)
      3. nullSafeSet(PreparedStatement st, T value, int index) should be changed to nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
      4. set(PreparedStatement st, T value, int index) should be changed to set(PreparedStatement st, T value, int index, SessionImplementor session)
    2. References to org.hibernate.usertype.UserType methods should be changed as indicated:
      1. nullSafeGet(ResultSet rs, String[] names, Object owner) should be changed to   
        nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
      2. nullSafeSet(PreparedStatement st, Object value, int index) should be changed to nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
    3. Session.reconnect() - manual disconection and reconnection is now only supported for user-supplied-connection scenarios (JDBC Connection passed in while opening the Session)
    4. Session.connection() - use Session.doWork(), Session.doReturningWork() or Session.sessionWithOptions()...openSession() as replacement depending on need
    5. Most of the overloaded SessionFactory.openSession methods.  Use SessionFactory.withOptions()...openSession() instead
  4. Deprecated classes/interfaces that have been removed:
    1. org.hibernate.classic.Session
    2. org.hibernate.classic.Validatable
    3. org.hibernate.classic.ValidationException
  5. org.hibernate.jdbc.BatcherFactory, Batcher, and their implementations have been replaced by org.hibernate.engine.jdbc.batch.spi.BatchBuilder and Batch, with default implementations in org.hibernate.engine.jdbc.batch.internal. You can override the default BatchBuilder by defining the  "hibernate.jdbc.batch.builder" property as the name of a BatchBuilder implementation, or by providing a BatchBuilder in a custom ServiceRegistry.
  6. hibernate.cfg.xml no longer supported as means of specifying listeners.  New approach invloves using an org.hibernate.integrator.spi.Integrator which works based on "service discovery". 




Thursday, May 14, 2015

Upgrade from Spring 2.5.x to Spring 4.1.x - JBoss

After completing the steps mentioned in my previous post for Upgrading Spring 2.5.x to Spring 4.1.x, the project compiles without problems, however, JBoss deployment does not work as it does not get all the required new Spring Jars.

The Spring component jars also need to be added to the JBoss classpath. However, here are a few specific exceptions that point to requiring specific jars in the JBoss classpath as below.

To resolve the below error, add spring-context.jar to JBoss library path:
java.lang.ArrayStoreException: sun.reflect.annotation.TypeNotPresentExceptionProxy
at sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:653)
at sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:460)
at sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:286)
at sun.reflect.annotation.AnnotationParser.parseAnnotation(AnnotationParser.java:222)
at sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:69)
at sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:52)
at java.lang.Class.initAnnotationsIfNecessary(Class.java:3079)


To resolve the below error, add spring-beans.jar to JBoss library path
java.lang.NoClassDefFoundError: org/springframework/beans/factory/BeanFactory
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2436)
at java.lang.Class.getDeclaredMethods(Class.java:1793)
at org.jboss.ejb3.interceptor.InterceptorInfoRepository$AnnotationInitialiser.getInfo(InterceptorInfoRepository.java:704)
at org.jboss.ejb3.interceptor.InterceptorInfoRepository.initialiseFromAnnotations(InterceptorInfoRepository.java:469)
at org.jboss.ejb3.interceptor.InterceptorInfoRepository.getOrInitialiseFromAnnotations(InterceptorInfoRepository.java:451)
at org.jboss.ejb3.interceptor.InterceptorInfoRepository.getInterceptorsFromAnnotation(InterceptorInfoRepository.java:341)
at org.jboss.ejb3.interceptor.InterceptorInfoRepository.getClassInterceptors(InterceptorInfoRepository.java:139)
at org.jboss.ejb3.EJBContainer.initialiseInterceptors(EJBContainer.java:737)
at org.jboss.ejb3.EJBContainer.getClassInterceptors(EJBContainer.java:429)

Hopefully this should resolve all issues for a successful upgrade of Spring 2.5.x to Spring 4.1.x!


Wednesday, May 6, 2015

EasyMock Exceptions when mocking Classes instead of Interfaces

EasyMock as the name suggests, provides an easy way to mock objects for testing where-in you mock interfaces of the classes you want to test. EasyMock then generates mock objects on the fly using Java's proxy mechanism and then simulates it in a simple way and also verifies whether it is used as expected.
When creating some new mock objects for testing using EasyMock 2.5.x, I noticed the below exceptions:
java.lang.IllegalArgumentException: org.hibernate.dialect.Dialect is not an interface
 at java.lang.reflect.Proxy.getProxyClass0(Proxy.java:470)
 at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:690)
 at org.easymock.internal.JavaProxyFactory.createProxy(JavaProxyFactory.java:12)
 at org.easymock.internal.MocksControl.createMock(MocksControl.java:37)
 at org.easymock.EasyMock.createMock(EasyMock.java:43)

To solve this, change your import as:
org.easymock.EasyMock.createMock => org.easymock.classextension.EasyMock.createMock

And another set of exceptions popped up:
java.lang.IllegalArgumentException: not a proxy instance
 at java.lang.reflect.Proxy.getInvocationHandler(Proxy.java:769)
 at org.easymock.EasyMock.getControl(EasyMock.java:1336)
 at org.easymock.EasyMock.replay(EasyMock.java:1280)

To solve this, change your imports as:
org.easymock.EasyMock.replay => org.easymock.classextension.EasyMock.replay
org.easymock.EasyMock.verify => org.easymock.classextension.EasyMock.verify

Viola! and now we are good!
When mocking classes that are not an interface, we need to use the createMock, replay, and verify methods FROM the class org.easymock.classextension.EasyMock and NOT the ones we regularly use from org.easymock.EasyMock
However, since EasyMock 3.0, the separate classextension package has been deprecated and left in place for backward compatibility and the above changes are not required. So it is recommended that if possible, one should upgrade to the latest 3.x version of EasyMock instead of going for the above changes.

Wednesday, April 22, 2015

Upgrade from Spring 2.5.x to Spring 4.1.x

I am upgrading Spring libraries of a critical project from Spring 2.5.x to the latest available release which is Spring 4.1.6 right now. One of the major issues I faced is that the packaging strategy was changed in Spring 3.0 release. Earlier, a single spring.jar with all jars and required libraries was provided, but this was discontinued from the 3.0 release. Now we would need to include each jar individually as per requirements - one jar for all situations doesn't exist anymore.

So, now you need to download individual spring component jars from the Maven Repository. The jars required are:
  1. spring-aop.jar
  2. spring-beans.jar
  3. spring-context.jar
  4. spring-core.jar
  5. spring-expression.jar
  6. aopalliance-1.0.jar - third-party jar
The third-party jar aopalliance-1.0 is required only if you use org.springframework.aop and it can be downloaded from here. This was earlier on bundled in the spring.jar and so now has to be added separately as required.

You can download the corresponding javadoc and source files by going to the Maven website and searching for:
  • g:"org.springframework" AND v:"4.1.6.RELEASE" - for Spring components
  • g:"aopalliance" - for aopalliance


Now that all the required jars are downloaded, spring-core jar will need to be included in most projects; here is a simple guide to when to include rest of the jars.

Add spring-beans.jar to classpath when you see the below or similar error during compilation:
Caused by: java.lang.ClassNotFoundException: org.springframework.beans.factory.NoSuchBeanDefinitionException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)


Add spring-context.jar to classpath when you see the below or similar error during compilation:
Caused by: java.lang.ClassNotFoundException: org.springframework.context.access.ContextSingletonBeanFactoryLocator
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)


Add spring-expression.jar to classpath when you see the below or similar error during compilation:
Caused by: java.lang.ClassNotFoundException: org.springframework.expression.ParserContext
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)


Add spring-aop.jar to classpath when you see the below or similar error during compilation:
The type org.springframework.aop.TargetSource cannot be resolved. It is indirectly referenced from required .class files
OR

Caused by: java.lang.ClassNotFoundException: org.springframework.aop.framework.ProxyFactoryBean


Add aopalliance-1.0.jar to classpath when you see the below or similar error during compilation:
The type org.aopalliance.aop.Advice cannot be resolved. It is indirectly referenced from required .class files
OR

Caused by: java.lang.ClassNotFoundException: org.aopalliance.intercept.MethodInterceptor


That's it - you should be all set and upgraded to the latest version of Spring after this exercise - no code change required!

Wednesday, April 16, 2014

Maven Compile error

Maven Compile Plugin by default uses version 2.0.2 and JDK1.3 as the target for the compilation of Java code if you do not specify the compiler plugin version and the Java source & target versions. Due to this, you may get the below error when compiling:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.0.2:compile (default-compile) on project scratch: Compilation failure
[ERROR] /home/projects/java/scratch/src/main/java/com/test/MavenCompileTest.java:[50,26] error: for-each loops are not supported in -source 1.3

To resolve this problem, you need to specify the compiler plugin version and the Java -source and -target versions in the pom.xml of your project as below:


  
    
      org.apache.maven.plugins
      maven-compiler-plugin
      3.1
      
        1.7
        1.7
      
    
  


You can figure out the latest version of the Compiler Plugin by reading the version number on the top right of the Compiler Plugin page.

Saturday, April 12, 2014

Throttle task submission in Java - Simple solution

JDK provides a convenient java.util.concurrent.Executors factory with useful methods to return various java.util.concurrent.Executor implementation instance pre-configured with commonly used settings. However, there is no implementation or configuration available for an implementation that throttles task submission. Here I provide my take on a very simple solution for this requirement.

private void submitTasks(List tasksList) {
  final ThreadPoolExecutor executor = new ThreadPoolExecutor(MIN_POOL_SIZE,
                                                             MAX_POOL_SIZE,
                                                             60L,
                                                             TimeUnit.SECONDS,
                                                             new LinkedBlockingQueue());
  for (Runnable task : tasksList) {
    while (executor.getQueue().size() > MAX_Q_SIZE) {
      // Throttle for WAIT_FOR_SECONDS seconds if queue is full
      try {
        log.info("Waiting " + WAIT_FOR_SECONDS + " seconds as Queue size is: " + executor.getQueue().size());
        Thread.sleep(WAIT_FOR_SECONDS * 1000);
      } catch (InterruptedException e) {
        // Ignore
      }
    }
    executor.execute(task);
  }
  // inform the executor there are no more tasks
  executor.shutdown();
}

Instead of using the factory to get a pre-configured executor, I create my own ThreadPoolExecutor using a LinkedBlockingQueue. This allows us access to the underlying queue for the throttling feature. Before submitting the task, I check if the current queue size is greater than a certain size and if so, then wait for a configured time repeatedly till the queue is smaller.
This implementation is very useful for the scenarios where you have lots of short running tasks that need to be processed by a fixed small number of threads.

Saturday, March 22, 2014

The mystery of the missing WhiteSpace in XML Attribute values

My expectation when testing the component that handles the import & export of xml data for the system, was that the input & output xml data should be the same if the component works properly. However, I noticed minor whitespace differences in attribute values between the two xml files and I couldn't find any code that was trimming attribute values during either the import nor the export of xml. A closer look showed that the spaces in attribute values were being trimmed and multiple occurrences of space replaced by a single space when the attribute values were being read in!

This was very intriguing so digging around in the XML Specs, says that in the canonical form of an XML document, attribute values are normalized by the XML processor. The Attribute Value Normalization section further lists out the exact algorithm to be used by the XML processor where-in all occurrences of whitespace are replaced by a space. Furthermore, if the attribute type is not CDATA, then the XML processor must further process the normalized attribute value by trimming leading and trailing space and by replacing sequences of spaces by a single space. Also, there is a separate section to handle new line characters which states that all line-breaks or occurrences of CR & LF must be replaced by a LF character.

Tuesday, July 23, 2013

Split String into Fixed Length chunks using Java

I needed to split a large string into fixed length chunks of equal size using Java Apart from the regular method of looping and doing a substring for the required length, I was wondering in what other way was it possible to achieve the same. Of course, it's Mr. Regex to the rescue for this task at hand! Here was the regex I used to do this:
String largeString = "This is a very large and totally useless and meaningless string";
int chunkLength = 5;
String[] chunks = largeString.split("(?<=\\G.{" + chunkLength + "})");
System.out.println("Number of chunks: " + chunks.length); // Should print 13
System.out.println("Chunk size: " + chunks[0].size()); // Should print 5 == chunkLength
The regular expression is a Positive Look-Behind looking for any chunkLength characters beginning at the position where the last match ended. So the first time around, it matches the beginning of the string and then after that, it keeps matching every set of chunkLength characters.
This makes me think I should write a more detailed post about regular expressions, especially on Look-Ahead and Look-Behind - stay tuned!

Thursday, April 18, 2013

Java 5 - Summary of new & important features

Here is a summary of the useful features that were introduced in Java 5.

Generics simplify code
Adds compile-time type safety and eliminates the necessity for type casting without any performance hit

Enhanced For loops - also known as For/Each
Simplifies looping code but does not make the iterator visible. Loops through each entry of the collection/array returning one properly cast value at a time for processing - without requiring to define an Iterator.

Typesafe Enums
Better than public static final String variables - allows us to create enumerated types with arbitrary methods and fields

Metadata Annotations
Reduces coding issues like overloading instead of overriding with the use of pre-defined annotations. Allows
for a more declarative style of programming reducing boiler-plate code with user-defined annotations.

Varargs provides flexibility
Methods can accept a multiple number of parameters defined at runtime with a few restrictions - they have to be the last set of parameters of the method and all have to be of the same data type. The ellipsis "…" is used to indicate that the argument might appear a variable number of times.

Auto Boxing / Unboxing
Implicit conversion between primitives and their wrapper classes - convenient, but can have lower performance as primitives are stored on the stack while the actual objects are stored in the heap.

Synchronization changes in java.util.concurrent package
Introduction of Locks concept to provide better semantics than "synchronized" keyword and many more useful features like Read/Write locks.

Static import
Makes code more readable and reduces redundant typing for qualifying the static members (methods & fields) of a class with the class name in each occurance

Performance improvements with better GC, StringBuilder, etc

Formatter allows for better printing with printf
No more clumsy println's with string concatenation - use C-style printf with format strings.

Scanner simplifies basic parsing
Easier than String.split and Integer.parseInt

These are too numerous and important to detail all of them in a single post - so each will be covered in detail with code examples in posts of their own soon.


Check out the Summary of Java 7 features that make Java even better!

Friday, March 29, 2013

Benchmarking the performance of Java & web Frameworks/Platforms

The guys over at TechEmpower put some of their time to great use for the benefit of the community and put together a meaningful test to benchmark the performance of Java and web frameworks / platforms that are popular these days. The results were very surprising - Netty, Vertx and Servlets outperformed all others by a very big margin!

However, one of the major eye-poppers was raw PHP (no ORM framework) and MySQL database with multiple queries per request - which is likely the practically used business case - performed amazingly well! Add to this the dearth of available good PHP programmers and low hosting costs, no wonder many small businesses opt for rolling their own custom PHP apps & websites than going for big frameworks.

Check out the full blog post with the graphs and details of the test in the TechEmpower blog post here.
You can also check out their code on Git here and join in on the conversation at HackerNews here.

Let the flame wars begin!  :P   ;P

Tuesday, August 2, 2011

Java 7 Summary of New Features

Here is a summary of the new features released in Java 7 as part of Project Coin language enhancements are:
  1. Improved Numeric Literals - Binary integral literals and Underscore in numeric literals
  2. Strings in switch
  3. Diamond operator or simpler type inference for generic instance creation
  4. try-with resource statement
  5. Multi-catch and more precise throw
  6. Simplified varargs method invocation
  7. Fork & Join enhancements
  8. NIO 2.0 & File system access enhancements
These are explained in detail below.

Improved Numeric Literals
Integral types (byte, short, int, and long) can also be expressed using the binary number system by prefixing "0b" or "0B" to the number's binary representation as:
int binaryLiteral = 0b110011

You can have underscores in numeric literals to make them more readable like:
int tenMillion = 10_000_000;

Strings in switch
Till Java6, only numbers or enums could be used in switch statements. Now strings are also allowed:
String switchString = getStringValue();
switch(switchString) {
    case "foo": doFoo();
                break;
    case "bar": doBar();
                break;
    case "fuu": doFuu();
                break;
    default: doDefault();
             break;
}
Diamond operator
This is a short cut to reduce typing and make it simpler to infer generic types during instance creation
Map<String, List<Pair<String,BigDecimal>> myMap = new HashMap<>();

Simplified varargs method invocation
When a programmer tries to invoke a *varargs* (variable arity) method with a non-reifiable varargs type, the compiler currently generates an "unsafe operation" warning. This proposal moves the warning from the call site to the method declaration. This merits more detailed explanation and a separate post.

Multi-catch and more precise throw
Now you can catch multiple exceptions in the same catch clause and also re-throw final exceptions without declaring the method with the "throws" clause.  More Precise Rethrow allows you to catch a high level exception instead of each possible exception, but when you re-throw this caught exception, the correct sub-class is thrown instead of the higher level exception. This merits more detailed explanation and a separate post.


Fork & Join threading enhancements
New Fork / Join framework as an implementation of the ExecutorService to help take advantage of mulit-core / multi-processor machines.


NIO 2.0 & File system access enhancements
NIO 2.0 & File system related changes make it easier for traversing file system trees and access file properties.
There are numerous changes and these could be a good candidate for a separate book in itself.


Check out the Summary of Java 5 features that are also hold good and are very useful.

Java Diamond "<>" operator

As part of Project Coin - Language enhancements, Java 7 has introduced the Diamond operator "<>".
In reality, this is just a short cut for a simpler type inference for generic instance creation.
So instead of this:

List<String> stringList = new ArrayList>String>();

one can use this in Java7:
List<String> stringList = new ArrayList<>();

So you say "big deal"?! The real benefits show when the type being inferred is very complicated and has multiple types nested in it like:
Map<String, List<Pair<String,BigDecimal>> myMap = new HashMap<>();

You are saved from repeating the same thing - less typing and less errors!

Friday, July 29, 2011

Eclipse support for Java7

Good news for Eclipse users is that all new builds of Eclipse 3.7.1, 3.8 and 4.2 will now fully support Java 7.
Earlier development of Java7 support in Eclipse was being done in BETA_JAVA7 branch which now has been fully merged into the HEAD and the R3_7_maintenance branch.


So the implication is that if you want Java7 support, you need to move to the latest builds of Eclipse Indigo (3.7.x) or higher. Cannot use Eclipse Helios (3.6.x) or even the initial versions of Indigo as the older JDT & Core packages do not understand the new Java7 features as Eclipse uses its own compiler and the ones built into older versions of Eclipse do not support Java 7. Also, as noted in the Project Plan For Eclipse Project, version Helios, support for Java 7 is deferred and decoupled from the 3.6 release since Java 7 release will be after the official release of 3.7.

Note that you will need to download a 3.7 maintenance build (>= M20110729-1400), a 3.8 build (>= I20110729-1200), a 4.1 maintenance build (coming soon) or a recent 4.2 build (>= I20110729-0200) to get Java7 support in Eclipse.

Java 7 GA release finally available

Java 7 was finally release into the wild today and made "GA" - Generally Available!
Download the latest from here.
Here's a very high level list of the new features/changes that made into Java7:

VM
  • Support for dynamically-typed languages using the new InvokeDynamic instructions
  • Strict class-file checking

Language
  • Small language enhancements from Project Coin like Strings in switch statements, try-with-resources statements, diamond operator, etc.

Core
  • Upgrade class-loader architecture to avoid deadlocks in non-hierarchical class-loader topologies
  • Concurrency and collections updates in form of a lightweight fork/join framework, flexible and reusable synchronization barriers, transfer queues, concurrent linked double-ended queues, and thread-local pseudo-random number generators

Internationalization
  • Support for Unicode 6.0
  • Separate handling of locales to separate formatting locales from user-interface language locales

I/O & Networking
  • New APIs for filesystem access, scalable asynchronous I/O operations, etc
  • New NIO.2 filesystem provider for zip and jar files
  • API for the Stream Control Transmission Protocol (SCTP) on Solaris
  • SDP (Sockets Direct Protocol) support for reliable, high-performance network streams over Infiniband connections on Solaris and Linux
  • Networking code modified to use the Windows Vista IPv6 stack, when available, in preference to the legacy Windows stack
  • Support for Transport Layer Security version 1.2

Security & Cryptograpphy
  • Implementation of the standard Elliptic Curve Cryptographic (ECC) algorithms to allow Java programs to support it out of the box

Database Connectivity
  • JDBC 4.1 and Rowset 1.1

Client
  • New Java2D graphics pipeline based upon the X11 XRender extension, which provides access to much of the functionality of modern GPUs
  • New platform APIs for features originally implemented in the 6u10 release namely Translucent and shaped windows, and heavyweight/lightweight component mixing
  • Cross-platform Nimbus look-and-feel for Swing
  • SwingLabs JXLayer component decorator added to the platform
  • New Gervill sound synthesizer created and made available

Web
  • Upgrade of the components of the XML stack to the most recent stable versions: JAXP 1.4, JAXB 2.2a, and JAX-WS 2.2

Management
  • Enhanced MBeans to report the recent CPU load of the whole system, the CPU load of the JVM process, and to send JMX notifications when GC events occur 

Pheww - that was a long list to say the least ;) No wonder the release date for Java7 was a very difficult moving target.
I will be putting out a detailed post on each of the features soon - so keep watching this space!

Thursday, July 21, 2011

Conditional Breakpoints in Eclipse

If you have a big data set that you are using to test changes that apply to specific scenarios or rows, Eclipse conditional breakpoints can help to make life easier and simpler.

In Debug View (obviously!), right-click on the breakpoint that you want to make conditional and in the window that opens up, check "Enabled" box and then the "Conditional" box. This enables the textarea below it where you can enter any valid java expression which should trigger this breakpoint when true.

Optionally, you can also check the "Hit count" box and enter a positive number to make this breakpoint trigger after that many number of iterations.

Tuesday, April 5, 2011

Array Equality in JUnit

Till JUnit4.2.*, the only way to compare equality of arrays was to use the following snippet of code:

assertTrue(java.util.Arrays.equals(primitiveArray1, primitiveArray2));

JUnit4.3.* added the assertArrayEquals methods but surprisingly omitted a method to compare arrays of primitive doubles so, one had to fall back to the above mentioned way to compare them.

This important feature was added in JUnit4.6 so if you are using that or a later version, you can do the following:
assertArrayEquals(doubleArray1, doubleArray2, delta)
where delta is the allowed tolerance.

The advantage with using the assertArrayEquals method over the previous method is that this method clearly indicates the first element which differed. For example, when the below basic test is run, it gives the error message:
arrays first differed at element [2]; expected:<2.3124> but was:<2.3224>

Here is a sample class file showing implementation of the above test:

import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;

public class AAETest {

    @Test
    public void testAAEDouble() {
     double[] da1 = {1.002d, 1.234d, 2.3124d, 3.91293d};
     double[] da2 = {1.003d, 1.2345d, 2.3224d, 3.91293d};
     double tol = 0.001d;
     assertArrayEquals(da1, da2, tol);
    }
}

Wednesday, March 17, 2010

SQuirreL behaving weird on Ubuntu

I needed to access MySQL & MS SQL databases from my Ubuntu 9.04 laptop and was at a total loss. After a bit of research, SQuirreL sql client looked like the best choice.
However, since this is not available through the Synaptics Package Manager so it had to be downloaded and installed manually - which is the way software used to be installed on *nix boxes originally.

At that time, SQuirreL 3.0.2 was the latest version and all versions starting from 3.0 require Java6 - this I was able to install from the Synaptics Package Manager. Installing SQuirreL was simple: Run the command sudo java -jar squirrel-sql-3.0.2-install.jar and it was installed.

However I was unable to access MS SQL Server DB yet as I did not have the proper JDBC drivers for that. After narrowing down my choices, I found I was left with jTDS which is an open source 100% pure Java (type 4) JDBC 3.0 driver for Microsoft SQL Server (6.5, 7, 2000, 2005 and 2008) and Sybase (10, 11, 12, 15). Just put the jtds jar file in the squirrel install lib folder and then add the new driver from the UI.

After this, I was able to access MS SQL server but often, the program would just freeze or become unresponsive after a few minutes of use (or lack thereof). I would need to kill the java process and restart it. Also, the automatic updates never worked and so the software remained the same version till I decided to take things into my hands.

At this time the latest version available was 3.1 which was good news indeed - I was expecting a full solution to my problems! However, the website offered no documentation on how to upgrade the software, only how to install it. So I went ahead and installed it in a similar fashion - but this time it installed in a different folder. The previous install was in the folder /usr/local/SQuirrel SQL Client/ and the new one was in the folder /usr/local/squirrel-sql-3.1/

I then tried to uninstall the older version by running the uninstall.jar from the Unintall folder of the previous install. However that did not do much and so I just removed that whole folder - just like we used to remove software from *nix in the "good old days"! The good news was that the configuration was stored in my home folder in the .squirrel-sql folder so all aliases/connections/drivers etc were intact and I was able to use them immediately.

But alas! Even after all this effort, the problem of SQuirreL freezing after a few minutes of use still did not go away!

Please let me know if you see any solution to this problem or if you come across a better SQL Client for Ubuntu which can access MySQL & MS SQL!

Wednesday, November 18, 2009

Java EE 6 coming soon

Attended a presentation on Java EE 6 at NYJavaSIG by Alexis Roos & Eric Bruno.

JSR 316: Java EE 6 Specification is up for final approval ballot and should be finalized by end of this month. Java EE 6 looks very promising & exciting; it's main features are pruning and profiles.


Pruning will be remove APIs which are no longer relevant/supported/useful/popular. This implies that the pruned APIs need need not be supported by application server vendors. For example, EJB 2.x Entity Beans CMP have been axed in favor of the lighter and simpler POJO based JPA persistence model introduced as part of EJB 3 in Java EE 5. Similarly, the enhanced & more robust, feature-rich and popular JAX-WS API supercedes JAX-RPC for Web Services.

Profiles allow users to take only the components they want instead of being forced to take the whole stack. This reduces the footprint & the costs. Currently only two profiles are included - Web Profile & Full Profile. However, there is scope for creating custom profiles as well.

There are major changes to GlassFish - it is now lighter and comes up faster. It now also supports redeployment with session retention - this is a huge plus for testing/debugging complex applications.

A new glue layer called Web Beans 1.0 has been introduced which will intergrate the persistence & web layers. The persistance layers (EJB 3.0, JTA, JCA and JPA) and the presentation layers (Servlets, JSP and JSF) were segregated and featured no closed interaction. This gap has been filled with Web Beans 1.0 which are designed to be compatible with both the tiers. The Web Beans have been equipped with beans that could interact with multiple tiers and are influenced by the popular frameworks JBoss Seam and Google Guice.

Apart from these major changes, there are a lot of small things that I liked:
  • EJB 3.1 now supports CRON like scheduling from inside the container
  • EJB 3.1 now do not require business interfaces to be created - developers can now write session beans without business interfaces
  • War structure has been simplified and EJB components can be packaged directly in a WAR file instead of creating an intermediate JAR file
  • EJB Lite has been introduced as a lighter & simpler version of EJB - supports only Session Beans & JPA
  • Servlets 3.0 introduces annotations such as such as @WebServlet, @ServletFilter, etc. to reduce web.xml configuration
  • Servlets now support Asynchronous processing to support AJAX calls
  • JSF 2.0 has major enhancements and new features like request processing lifecycle is now AJAX-aware, bookmarkable JSF pages and a mechanism to easily access persistent store
  • Very good support for REST programming through JAX-RS
  • Better support for AJAX

Check out the Release Notes and the good Tutorial for Java EE 6.

Friday, July 10, 2009

JSF2.0 Coming soon

Had been to the NYJavaSig meeting at Sun' office recently where Kito D. Mann (author of the book "JSF in Action") presented the new features of the upcoming JSF2.0 release.
JSF had been long overdue for a rewrite/overhaul and so this is a welcome change with very good features, AJAX support, very easy process for creating widgets/components, very less configuration, etc.
Lets wait & see how the final product turns out to be!

LinkWithin

Related Posts Plugin for WordPress, Blogger...