The following exception throws while batch updating using Hibernate 3.x with JDBC driver 9.2.0.1:
java.lang.NullPointerException
at oracle.jdbc.dbaccess.DBData.clearItem(DBData.java:431)
at oracle.jdbc.dbaccess.DBDataSetImpl.clearItem(DBDataSetImpl.java:3528)
at oracle.jdbc.driver.OraclePreparedStatement.clearParameters(OraclePreparedStatement.java:3401)
I found the solution from a posting in Oracle forum (http://forums.oracle.com/forums/thread.jspa?threadID=190963) and that says:
Oracle seems to have corrected one line in in
oracle.jdbc.dbaccess.DBData, method void clearItem(int i)
version 9.2.0.1:
if(m_items == null && i >= m_items.length) {
version 9.2.0.3:
if(m_items == null || i >= m_items.length) {
----
Another way to avoid this NPE is to avoid using the JDBC2 batch update feature.
For our (hibernate) implementation this corresponds to setting the property 'jdbc.batch_size' to zero.
Featured Post
The great debacle of healthcare.gov
This is the first time in history when the president of the United States of America, or probably for any head of state around the world,...
Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts
Wednesday, March 5, 2008
Date difference dependens on the underlying JVM
If you write a utility method to get the difference between two dates, don't trust your system that it's gonna give you the same result all the time (Don't confused it with the Java slogan 'write once, run anywhere' !). The result you would get is totally dependent on the JVM, on which you are running your code. Follow the below case:
1. Create a date object from the Calendar:
Calendar cal = GregorianCalendar.getInstance();
cal.set(2008, Calendar.JANUARY, 31);
startDate = cal.getTime();
cal.set(2014, Calendar.MARCH, 31);
endDate = cal.getTime();
2. Get the difference in days:
long time1 = startDate.getTime();
long time2 = endDate.getTime();
long inDays = (time2 - time1) / 1000 * 60 * 60 * 24;
3. The result is 2250 days in -
Java(TM) 2 Runtime Environment, Standard Edition (IBM build 1.4.2_12-b03 20061117 (SR6 + 110979) ) and 2251 in Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_04-b05).
The true platform independent solution for the above issue is to add the hour:min:sec
as 23:59:59 while getting the date from the calendar.
cal.set(2014, Calendar.MARCH, 31, 23, 59, 59);
And through that you can write once and run anywhere until any new issue come up.
Note: Though I'm not yet sure but I found some posting that says this happens only if the date falls in some leap year.
1. Create a date object from the Calendar:
Calendar cal = GregorianCalendar.getInstance();
cal.set(2008, Calendar.JANUARY, 31);
startDate = cal.getTime();
cal.set(2014, Calendar.MARCH, 31);
endDate = cal.getTime();
2. Get the difference in days:
long time1 = startDate.getTime();
long time2 = endDate.getTime();
long inDays = (time2 - time1) / 1000 * 60 * 60 * 24;
3. The result is 2250 days in -
Java(TM) 2 Runtime Environment, Standard Edition (IBM build 1.4.2_12-b03 20061117 (SR6 + 110979) ) and 2251 in Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_04-b05).
The true platform independent solution for the above issue is to add the hour:min:sec
as 23:59:59 while getting the date from the calendar.
cal.set(2014, Calendar.MARCH, 31, 23, 59, 59);
And through that you can write once and run anywhere until any new issue come up.
Note: Though I'm not yet sure but I found some posting that says this happens only if the date falls in some leap year.
Tuesday, November 13, 2007
Implement Spring in a Struts project
- To prepare a project for Spring, first of all, we've to ensure that Inversion of Control Design concept is followed through out the application. And for that preparation the team might need to undergo thorough refactoring and/or redesigning, depending on the existing implementation and design.
- Write or re-write the business logic and data logic (DAO) classes with DI pattern. Create the Spring context XML file for the business and DAO classes. Inject the business logic objects into the Action classes using any Spring Context.
- After refactoring the existing code enabling Dependency Injection, second step is to prepare the Struts action classes to integrate with Spring. In this case the same DI needs to be enabled in the Action classes. The Action class shouldn't be burdened with redundant logic codes other than controlling logics. Use the Delegation Proxy to create the Struts Action classes through Spring. Before that ensure that the injection of
- Remove all logging cross-cut codes from the classes and use Spring Interceptor (BeforeMethod advice) and implement the logging
- To manage the application's transaction using Spring declarative transaction, implement it through proxy. The transaction declaration needs more time to analyze rather than implement. Do the homework on transaction grouping and then implement it in the xml file. Rigorously testing requires to confirm functional and performance requirements.
Struts-Spring Integration Using Proxy
DelegatingActionProxy is the object that plays the role to create Struts Action class when the request is invoked.
1. Modify your struts-config.xml file to give the DelegatingActionProxy to play its role
type="org.springframework.web.struts.DelegatingActionProxy"
input="/someOtherAction.do">
2. Add an entry for the path, in this case, '/someAction' in the spring configuration
Open View in transaction in Spring with Hibernate
1. Create a Filter to handle the transaction:
org.springframework.web.filter.DelegatingFilterProxy
2. Set the Filter to accept any request ends with .d0
3. Set the Listener that loads Spring's WebAppContext
4. set the parameter value of the configuration file that configures the Transaction Filter and Transaction Manager
/WEB-INF/WebContext.xml
5. Configure the Filter
6. Implement the Filter class
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
if (!TransactionSynchronizationManager.hasResource(sessionFactory)) {
session = SessionFactoryUtils.getSession(sessionFactory, true);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}
status = transManager.getTransaction(def);
chain.doFilter(req, res);
//commit
getTransactionManager().commit(status);
//rollback
getTransactionManager().rollback(status);
//Close the Session
TransactionSynchronizationManager.unbindResource(sessionFactory);
SessionFactoryUtils.closeSession(session);
Resources:
http://springtips.blogspot.com/ - Spring tips
Spring-Struts integration - Spring integration with Struts Action
Spring transaction blog - A compact discussion of spring transaction implementation
Useful RAD keyboard shortcuts
I used Rational Application Developer (RAD 7.0) to test the below keyboard shortcuts. All of the shortcuts are for the Java/J2EE perspectives:
Editor
Ctrl+M -> Maximize/Minimize the current editor
Ctrl+W -> Close the current editor
Ctrl+E -> Show all editor
Ctrl+D -> Delete line from cursor position
Ctrl+T -> Open the Type, if on method or class then shows the available subtypes
Cntrl+O -> Open the members
Ctrl+Shift+F6 -> Show available Editors
Ctrl+Shift+F7 -> Show available views (need to check)
Ctrl+Shift+F8 -> Show available perspectives (need to check)
Alt+ Arrow keys -> move forward/backword to the last change position
F12 -> Activate the editor
F3 -> Open the declaration
Cntrl+Shift+M -> Add import statement for the Class used in the code (shows error as underline red
for the class used but not imported the class i.e. import statement isn't written
Cntrl+Shift+O -> Organize the import statements i.e. if you've removed some classes from your
code but the important statement wasn't deleted this command will clean up those
unused import statements
Cntrl + F4 -> to close the currently active tab on the Editor
Search
Cntrl+Shift+R -> Search for Resources
Cntrl+Shift+T -> Search for Types
Cntrl+K -> Go to the next search result
Cntrl+Alt+H -> Show the call hierarchy of a method (highlight on the method you want to see the call trace)
Cntrl+Shift+H -> To search for Java Classes (Type)
Code structure change
Alt+Shift+R -> Rename (refactor) of class/member
Note: To change the keyboard shortcut mapping, go to Windows -> Preferences -> Workbench -> Keys
Editor
Ctrl+M -> Maximize/Minimize the current editor
Ctrl+W -> Close the current editor
Ctrl+E -> Show all editor
Ctrl+D -> Delete line from cursor position
Ctrl+T -> Open the Type, if on method or class then shows the available subtypes
Cntrl+O -> Open the members
Ctrl+Shift+F6 -> Show available Editors
Ctrl+Shift+F7 -> Show available views (need to check)
Ctrl+Shift+F8 -> Show available perspectives (need to check)
Alt+ Arrow keys -> move forward/backword to the last change position
F12 -> Activate the editor
F3 -> Open the declaration
Cntrl+Shift+M -> Add import statement for the Class used in the code (shows error as underline red
for the class used but not imported the class i.e. import statement isn't written
Cntrl+Shift+O -> Organize the import statements i.e. if you've removed some classes from your
code but the important statement wasn't deleted this command will clean up those
unused import statements
Cntrl + F4 -> to close the currently active tab on the Editor
Search
Cntrl+Shift+R -> Search for Resources
Cntrl+Shift+T -> Search for Types
Cntrl+K -> Go to the next search result
Cntrl+Alt+H -> Show the call hierarchy of a method (highlight on the method you want to see the call trace)
Cntrl+Shift+H -> To search for Java Classes (Type)
Code structure change
Alt+Shift+R -> Rename (refactor) of class/member
Note: To change the keyboard shortcut mapping, go to Windows -> Preferences -> Workbench -> Keys
Sunday, October 28, 2007
Java 5: Tiger @ a glance
New Features of Java 5, the Tiger
The code name Tiger for the Java 1.5 which is officially recognized as Java 5, comes with lot of new features. Those features enrich the capability of Java and also overcome some limitations of faster programming. There are some features those also changed some core beliefs of Java such as Compile time error handling rather Runtime surprising.
Note: This gist is mostly taken from Java 1.5 Tiger: A Developers Notebook from Oreilly
Generics
This is the feature that existed long before in the C++ language, known as Template. This feature provides Java the capability to tag a Collection to a specific Object types so that the Collection can only handle the tagged Object type. The main benefits to the programmer are the type safe Collection and avoiding unnecessary type casting.
Type safe Collection
Generic let you to trust the Collection contains a specific type by limiting the type that a particular Collection will accept. You don’t need to cast to the specific object again.
List example:
List myList = new LinkedList();
String str = myList.iterator().next();
Map example:
HashMap myMap = new HashMap();
Limitation: There is a limitation in the Generic Type Safety. This can be broken by using reflection.
Writing Generic types
You can write your own Generic type Collection.
Public class Box
{
private List list;
public Box()
{
this.list = new ArrayList();
}
// Other methods implementation….
}
Miscellaneous
Arrays
Tiger has provided some very useful static method for this type of objects. Those are:
deepToString():This method takes an Array object and prints out it’s contents
deepEquals(): provided to compare multidimensional arrays.
Queues
Two cool methods have been provided: offer() and poll() methods are best alternatives add() and remove() methods respectively. The later method throws exception when the Queue is full (for add()) or it is empty (for remove()) but the former method pair returns false and null respectively.
PriorityQueue collection has been given as an alternative to FIFO. This Queue uses a Comparator object to filter; otherwise it works just like a Queue.
The following code is used to print lowest to highest for even and odd numbers.
PriorityQueue pq = new PriorityQueue (20, new Comparator( )
{
public int compare(Integer i, Integer j)
{
int result = i%2 - j%2;
if (result == 0)
result = i-j;
return result;
}
}
);
for (int i=0; i<20; i="0;" string=""> antMessages = new EnumMap(AntStatus.class);
antMessages.put(AntStatus.INITIALIZING, “Initializing Ant…..);
………
String theMsg = antMessage.get(AntStatus.INITIALIZING)
EnumSet has similar uses. See EnumSet JavaDoc API for details
Adding Methods in Enum
You can add methods in an enum just like any other class.
Public enum GuiterFeatures{
ROSEWOOD(0),
MAHOGONY(4),
ZIRICOTE(3)
…..
…
private float upCharge;
private GuiterFeatures(float upCharge)
{
this.upCharge = upCharge;
}
public String getDescription()
{
switch(this){
case ROSEWOOD: return “Rosewood back and side”;
….
…..
}
}
}
Manipulating Enum
Autoboxing and Unboxing
Convertion of Primitives and Wrappers
You can now create any Wrapper class (Integer, Float, Double etc.) without concerning the manual conversion of primitives to wrapper object. Both of the following statements are true:
Integer value = new Integer (10)
Integer newValue = 10;
It is also hassle free to convert the object to primitive type:
int primValue = newValue;
Method overload resolution
Method overloading seems bit confusing in the new Java environment due to the auto boxing and unboxing features. Which overloaded method should be invoked when convert (10) is called if the overloaded method signatures are like follow:
Public int convert(Integer value)
Public int convert(int value);
Tiger has three-pass process to resolve the issue:
i. The compiler attempts to locate the correct method without any boxing, unboxing, or vararg invocations. This will find any method that would have been invoked under Java 1.4 rules.
ii. If the first pass fails, the compiler tries method resolution again, this time allowing boxing and unboxing conventions. Methods with varargs are not considered in this pass.
iii. If the second pass fails, the compiler tries method resolution one last time, allowing boxing and unboxing, and also considers varargs methods.
Varargs
This relatively simple feature aides you to write simple, cleaner and more flexible code
Creating and iterating
Public void addInstrument(String id, String version, String… features)
{
this.id = id;
this.version = version;
// here features is the String[] type. You can also convert varargs to List using Arrays.asList(..)
this.features = features
}
The above method signature accepts variable length of features for the instrument. Those three dots (…) are the syntax of declaring varargs. The following code shows hot it is called:
addInstrument(“1”, “2.2”, “Cool GUI”, “Slow refresh”, “medium startup time”);
addInstrument(“1”, “2.2”, “Cool GUI”, “Slow refresh”);
addInstrument(“1”, “2.2”, “Cool GUI”);
All the above method call will hit the previously declared method with varargas. Great!
Avoiding automatic Array conversion
Loop
The loop has gone through a dramatic change in the new release. It is more easy to code now to iterate through collection and string. The new syntax is:
for (declaration : expression)
statement
Example for collection:
For( Object obj : myList)
{
System.out.println((String)obj);
}
Advantages of new loop:
i. You can ditch the usage of Iterator as it is done by the Compiler during byte code conversion
Compiler convert the for loop in the following fashion for an collection (in the expression)
for ( Iterator #i = (expression).iterator( ); #i.hasNext( ); )
{
declaration = #i.next( );
statement
}
ii. Unnecessary type casting can be avoided by directly using the reference
List wordList = new ArrayList();
for(String word : wordlist)
{
System.out.print(word + " ");
}
Apart from above, the new for loop structure (foreach) reduces code in the control structure (you don't need to assign new variable to count and loop through and also another line of code to retrieve the object from the collection
There are some further points about the syntax of the for/in loop that you should be aware of:
1. Expression must be either an array or an object that implements the java.lang.Iterable interface. The compiler must be able to ensure this at compile-time—so you can't use a List cast to Object, for example, and expect things to behave.
2. The type of the array or Iterable elements must be assignmentcompatible with the type of the variable declared in the declaration . If the assignment won't work, you're going to get errors.
3. The declaration usually consists of just a type and a variable name, but it may include a final modifier and any appropriate annotations (see Chapter 6 on Annotations). Using final prevents the loop variable from taking on any value other than the array or collection element the loop assigns. It also emphasizes the fact that the array or collection cannot be altered through the loop variable.
4. The loop variable of the for/in loop must be declared as part of the loop, with both a type and a variable name. You cannot use a variable declared outside the loop as you can with the for loop.
Import
Static import
Now on you can use the static method name without showing its Class name in every instance through the use of static import.
import static java.lang.System.out;
import static java.util.Math.*;
These following codes are valid now in the class:
out.println(“Whatsoever”);
double x = sqrt(y * PI)
You can even use the same name in the static import.
Importing multiple members with the same name
Annotations
Standard annotation types
There are three standard annotation types:
i. Deprecated
ii. Override
iii. SuppressWarning
There are three categories of annotation:
i. Marker annotation
ii. Single-value annotation
iii. Full annotation
You can create your own annotations by using the @interface. The ‘@’ symbol is used to indicate the Interface class to Annotation class.
Yet to cover
Threading
Handling uncaught exception
Using Thread safe Collection
Queues blocking
Separating Thread logic from execution logic
Using callable objects
Executing tasks without and ExecutorService
Scheduling Tasks
Advance Synchronization
The code name Tiger for the Java 1.5 which is officially recognized as Java 5, comes with lot of new features. Those features enrich the capability of Java and also overcome some limitations of faster programming. There are some features those also changed some core beliefs of Java such as Compile time error handling rather Runtime surprising.
Note: This gist is mostly taken from Java 1.5 Tiger: A Developers Notebook from Oreilly
Generics
This is the feature that existed long before in the C++ language, known as Template. This feature provides Java the capability to tag a Collection to a specific Object types so that the Collection can only handle the tagged Object type. The main benefits to the programmer are the type safe Collection and avoiding unnecessary type casting.
Type safe Collection
Generic let you to trust the Collection contains a specific type by limiting the type that a particular Collection will accept. You don’t need to cast to the specific object again.
List example:
List
String str = myList.iterator().next();
Map example:
HashMap
Limitation: There is a limitation in the Generic Type Safety. This can be broken by using reflection.
Writing Generic types
You can write your own Generic type Collection.
Public class Box
{
private List
public Box()
{
this.list = new ArrayList
}
// Other methods implementation….
}
Miscellaneous
Arrays
Tiger has provided some very useful static method for this type of objects. Those are:
deepToString():This method takes an Array object and prints out it’s contents
deepEquals(): provided to compare multidimensional arrays.
Queues
Two cool methods have been provided: offer() and poll() methods are best alternatives add() and remove() methods respectively. The later method throws exception when the Queue is full (for add()) or it is empty (for remove()) but the former method pair returns false and null respectively.
PriorityQueue collection has been given as an alternative to FIFO. This Queue uses a Comparator object to filter; otherwise it works just like a Queue.
The following code is used to print lowest to highest for even and odd numbers.
PriorityQueue
{
public int compare(Integer i, Integer j)
{
int result = i%2 - j%2;
if (result == 0)
result = i-j;
return result;
}
}
);
for (int i=0; i<20; i="0;" string=""> antMessages = new EnumMap
antMessages.put(AntStatus.INITIALIZING, “Initializing Ant…..);
………
String theMsg = antMessage.get(AntStatus.INITIALIZING)
EnumSet has similar uses. See EnumSet JavaDoc API for details
Adding Methods in Enum
You can add methods in an enum just like any other class.
Public enum GuiterFeatures{
ROSEWOOD(0),
MAHOGONY(4),
ZIRICOTE(3)
…..
…
private float upCharge;
private GuiterFeatures(float upCharge)
{
this.upCharge = upCharge;
}
public String getDescription()
{
switch(this){
case ROSEWOOD: return “Rosewood back and side”;
….
…..
}
}
}
Manipulating Enum
Autoboxing and Unboxing
Convertion of Primitives and Wrappers
You can now create any Wrapper class (Integer, Float, Double etc.) without concerning the manual conversion of primitives to wrapper object. Both of the following statements are true:
Integer value = new Integer (10)
Integer newValue = 10;
It is also hassle free to convert the object to primitive type:
int primValue = newValue;
Method overload resolution
Method overloading seems bit confusing in the new Java environment due to the auto boxing and unboxing features. Which overloaded method should be invoked when convert (10) is called if the overloaded method signatures are like follow:
Public int convert(Integer value)
Public int convert(int value);
Tiger has three-pass process to resolve the issue:
i. The compiler attempts to locate the correct method without any boxing, unboxing, or vararg invocations. This will find any method that would have been invoked under Java 1.4 rules.
ii. If the first pass fails, the compiler tries method resolution again, this time allowing boxing and unboxing conventions. Methods with varargs are not considered in this pass.
iii. If the second pass fails, the compiler tries method resolution one last time, allowing boxing and unboxing, and also considers varargs methods.
Varargs
This relatively simple feature aides you to write simple, cleaner and more flexible code
Creating and iterating
Public void addInstrument(String id, String version, String… features)
{
this.id = id;
this.version = version;
// here features is the String[] type. You can also convert varargs to List using Arrays.asList(..)
this.features = features
}
The above method signature accepts variable length of features for the instrument. Those three dots (…) are the syntax of declaring varargs. The following code shows hot it is called:
addInstrument(“1”, “2.2”, “Cool GUI”, “Slow refresh”, “medium startup time”);
addInstrument(“1”, “2.2”, “Cool GUI”, “Slow refresh”);
addInstrument(“1”, “2.2”, “Cool GUI”);
All the above method call will hit the previously declared method with varargas. Great!
Avoiding automatic Array conversion
Loop
The loop has gone through a dramatic change in the new release. It is more easy to code now to iterate through collection and string. The new syntax is:
for (declaration : expression)
statement
Example for collection:
For( Object obj : myList)
{
System.out.println((String)obj);
}
Advantages of new loop:
i. You can ditch the usage of Iterator as it is done by the Compiler during byte code conversion
Compiler convert the for loop in the following fashion for an collection (in the expression)
for ( Iterator #i = (expression).iterator( ); #i.hasNext( ); )
{
declaration = #i.next( );
statement
}
ii. Unnecessary type casting can be avoided by directly using the reference
List
for(String word : wordlist)
{
System.out.print(word + " ");
}
There are some further points about the syntax of the for/in loop that you should be aware of:
1. Expression must be either an array or an object that implements the java.lang.Iterable interface. The compiler must be able to ensure this at compile-time—so you can't use a List cast to Object, for example, and expect things to behave.
2. The type of the array or Iterable elements must be assignmentcompatible with the type of the variable declared in the declaration . If the assignment won't work, you're going to get errors.
3. The declaration usually consists of just a type and a variable name, but it may include a final modifier and any appropriate annotations (see Chapter 6 on Annotations). Using final prevents the loop variable from taking on any value other than the array or collection element the loop assigns. It also emphasizes the fact that the array or collection cannot be altered through the loop variable.
4. The loop variable of the for/in loop must be declared as part of the loop, with both a type and a variable name. You cannot use a variable declared outside the loop as you can with the for loop.
Import
Static import
Now on you can use the static method name without showing its Class name in every instance through the use of static import.
import static java.lang.System.out;
import static java.util.Math.*;
These following codes are valid now in the class:
out.println(“Whatsoever”);
double x = sqrt(y * PI)
You can even use the same name in the static import.
Importing multiple members with the same name
Annotations
Standard annotation types
There are three standard annotation types:
i. Deprecated
ii. Override
iii. SuppressWarning
There are three categories of annotation:
i. Marker annotation
ii. Single-value annotation
iii. Full annotation
You can create your own annotations by using the @interface. The ‘@’ symbol is used to indicate the Interface class to Annotation class.
Yet to cover
Threading
Handling uncaught exception
Using Thread safe Collection
Queues blocking
Separating Thread logic from execution logic
Using callable objects
Executing tasks without and ExecutorService
Scheduling Tasks
Advance Synchronization
Subscribe to:
Comments (Atom)