Posts

Showing posts with the label Java SE 6

SecretKeyFactory is broken in JDK 1.6 update 22

If you upgrade JDK to 1.6 update 22 (build 04), the SecretKeyFactory is broken. As a result you will not be able to load any PKCS12 key stores. You will get NoSuchAlgorithmException thrown. I have reported this issue in the bug database. You can view the bug here . I guess it will take upto a day for this bug to be externally visible, if you don't have a SDN account. Here is the sample program to reproduce the issue: public static void main(String[] args) { SecretKeyFactory instance = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); System.out.println("Returned instance: " + instance.getAlgorithm()); } You will get the exception below: Exception in thread "main" java.security.NoSuchAlgorithmException: PBEWithSHA1AndRC2_40 SecretKeyFactory not available at javax.crypto.SecretKeyFactory.<init>(DashoA13*..) at javax.crypto.SecretKeyFactory.getInstance(DashoA13*..) at main.TestClient.main(TestClient.java:96) Work ...

Issue of autoboxing and reflection

Problem: Consider that you want to have a method called "Object invokeAndGet(Object targetObject, String methodName, Object... args)". This method should be able to invoke the given method on the target object and return the value returned by the invocation. If the method has overloaded forms, then depending on the argument types, the invokeAndGet method should invoke the correct form. Solution: Though this problem looks trivial and seems like it can be solved by using reflections APIs, it gets really tricky when you have to deal with primitive types. This is due to the fact that autoboxing converts the primitives into their corresponding wrapper types. For e.g. an integer value is autoboxed into Integer object, etc. To begin with let us assume that we have the following implementation of the method: public static Object invokeAndGet(Object obj, String methodName, Object... args) { try { Class<?>[] argsTypes = new Class[args.length]; ...

Cobertura and Spring auto proxying

If you are using Cobertrua to get coverage reports, you may run into the error message shown below (lines folded for clarity): Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myBean' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type '$Proxy28 implementing net.sourceforge.cobertura.coveragedata.HasBeenInstrumented, org.springframework.aop.SpringProxy, org.springframework.aop.framework.Advised' to required type 'com.mydomain.MyDao' for property 'myDao'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [$Proxy28 implementing net.sourceforge.cobertura.coveragedata.HasBeenInstrumented, org.springframework.aop.SpringProxy, org.springframework.aop.framework.Advised] to required type [com.mydomain.MyDao] for ...

Bean properties printer - a useful debugging tool

There are many instances when I wanted to just log the properties of a given object (most of the time its a bean). This will be useful in two ways: 1) learn about the concrete type of the object 2) serves as a good learning aid to understand what are all the properties that can be get/set in that object. Of course, if you have the documentation and the source code for the class in question, that would be the ultimate aid. Nevertheless, the following piece of code would be useful to print the properties of the given object/bean, using the getter methods that are available in the object.     public static void printProperties(String msg, Object o) {         String className = o.getClass().getName();         if(msg != null && msg.length() > 0)             logger.info("{} (type {})", msg, className);         Method[] methods ...

Logging three or more arguments in slf4j

I use slf4j for logging purposes. All the logging methods (Logger.info, Logger.debug, etc.) provide an efficient way of passing one or two argument objects. For e.g. logger.info("The response from server is [{}]", serverResp); logger.debug("Key [{}], Value [{}].", key, value);  But if you want to pass three or more arguments you have to create an object array yourself and pass. Like this: logger.info("Status [{}], message [{}], time taken [{} ms].", new Object[]{status, msg, timeTaken}); Doing a new everywhere in the code doesn't seem like an elegant way of doing it. I was thinking about a cool way of doing it, and this is what I came up with. Here is a utility method that makes use of varargs: public static Object[] toObjArr(Object... args) {     return args; } In the code we can use this utility function like this. import static com.mydomain.Utils.toObjArr; ...     logger.info("Status [{}], message [{}], time taken [{} ms].", toOb...

Creating a Collection with a single element

Question: What is the most efficient way of creating a collection (Set, List or Map) with a single element? Answer: The most efficient way of creating a collection with a single element would be to make use of the Collections.singletonXXX() methods. Collections.singleton - To create a set that has only one element. Collections.singletonList - To create a list that has only one element. Collections.singletonMap - To crate a map that has only one entry. The collections returned from these methods are immutable. Compare these methods with Collections.unmodifiableXXX() methods. The umodifiableXXX methods already accept a collection as an argument.

Returning an empty collection instead of null

For one of my recent projects, I had to work with legacy code. There were methods that are returning collections, like lists or sets. These collections were created by reading data from the database. Whenever there is no data to form the collection, these methods return null. Now that is bad! One of the issues of returning null is that the caller always have to check for null. Most of the time the caller either searches for a particular value in the returned collection or iterate through the elements in the returned collection. The code will look like this: List rows = myDao.getRowsFor("key"); if(rows != null) {   for(Row row:rows) {     // Do something with the row   } } As you can see, it is easy to avoid the null pointer check if the getRowsFor() returned an empty list instead of a null pointer when there is no data in the database. The clutter caused out of the null pointer checks all over the code. You can read more about this simple principle in ...

A note on Java's Calendar set() method

Remember that the Calendar's internal fields include year, month, date, hour, minutes, seconds, milliseconds and time zone. Whenever you are calling a set() method with multiple fields, like set(year, month, date), it will not affect the rest of the fields. Remember that there is no set() method with multiple fields available to set the milliseconds. If you would like to set the milliseconds, you must use set(Calendar.MILLISECOND, value). Likewise, if you are planning to set all the fields, its a good idea to reset all the fields using clear() method. This will clear milliseconds as well. Most of the times, millisecond field may not be of interest to you. But if you are going to use the UTC milliseconds, by calling getTimeInMillis(), then make sure you set the right values for milliseconds as well.

Eclipse - issue with setting break points

I recently ran into a weird issue. I had to debug a piece of code that I wrote. So I launched the application in Eclipse in debug mode, and set a few break points. Though I can see that the log messages related to all the break points appear in the log, it didn't stop in all the break points. In some break points it stopped and in some other it didn't stop. I checked the output directory, I checked the flags to the compiler, even I downgraded to Ganymede. Nothing seemed to work. When I asked the question in the stackoverflow.com, I got the answer in five minutes . Looks like JDK 1.6 update 14 has an issue with debugging. So upgrading to JDK 1.6 update 16 helped. But still I am seeing the issue occasionally.

Paper on garbage-first (G1) garbage collector

This is the paper on garbage-first (G1) garbage collector. It is an interesting read.

A better way of printing heap usage in Java

If you rely on getting the heap usage by methods provided in Runtime, then consider making use of the MemoryPoolMXBeans. The code to print the memory usage is extremely simple: List mpool = ManagementFactory.getMemoryPoolMXBeans(); for(MemoryPoolMXBean b:mpool) { System.out.println(b.getName() + ": " + b.getUsage()); } You will see something like this when you run this: Code Cache: init = 163840(160K) used = 468672(457K) committed = 491520(480K) max = 33554432(32768K) Eden Space: init = 917504(896K) used = 202792(198K) committed = 917504(896K) max = 4194304(4096K) Survivor Space: init = 65536(64K) used = 0(0K) committed = 65536(64K) max = 458752(448K) Tenured Gen: init = 4194304(4096K) used = 0(0K) committed = 4194304(4096K) max = 61997056(60544K) Perm Gen: init = 12582912(12288K) used = 108360(105K) committed = 12582912(12288K) max = 67108864(65536K) Perm Gen [shared-ro]: init = 8388608(8192K) used = 6162160(6017K) committed = 8388608(8192K) max = 8388...

Finding native-endian in Java

I was getting curious about if its possible to write a Java program that finds if the underlying native platform is little- or big-endian. I guess its not possible to write such a program without having part of the code in C/C++ and using JNI. If anyone reading this blog feels otherwise, please let me know. There is an API available from NIO to find out the native-endian. I think this API should use some native code underneath.

Notes on ObjectOutputStream.writeObject()

If you write the same object twice into the ObjectOutputStream using writeObject() method, typically you would expect that the size of the stream should increase approximately by the size of the object (and all the fields within that recursively). But it wouldn't happen so. It is very critical to understand how writeObject() method works. It writes an object only once into a stream. The next time when the same object is written, it just notes down the fact that the object is already available in the same stream. Let us take an example. We want to write 1000 student records into an ObjectOutputStream. We create only one record object, and plan to reuse the same record within a loop so that we save time on object creation. We will use setter methods to update the same object with next student's details. If we use writeObject() to carry out this task, changes made to all but the first student's records will be lost. (Go ahead and try the program given below) To achieve the ...

Learning a system and the use of profiler

Here is a question: When you are given a huge system with source code and asked to learn the system, where will you start? Think for a moment and answer. My answer goes like this: Run the system through a debugger that would give you a fair idea about the system (where to start, what are all the functions called, etc.) Run the system under truss or strace (or whichever tool is applicable to your platform), which will give you a very good idea of what are all the resources the system is using. (INI files, resource files, etc) Observe what functions are called while different functionalities are accessed in the system (what happens in my server after I click the "Submit" button, what is the function invocation sequence when I login, etc.) If you venture into studying the system brute force by going through the source code at random points, you might waste time at unnecessary places. The activities mentioned above should help you at least which piece of source code you should l...

System.identityHashCode() - What is it?

Today I learnt about a function called System.identityHashCode(). To understand where it is used, let us consider the following program. // // What will be the output of toString() if we override hashCode() function? // public class HashCodeTest { public int hashCode() { return 0xDEADBEEF; } public static void main(String[] argv) { HashCodeTest o1 = new HashCodeTest(); HashCodeTest o2 = new HashCodeTest(); System.out.println("Using default toString():"); System.out.println("First: " + o1); System.out.println("Second: " + o2); System.out.println("Using System.identityHashCode():"); System.out.println("First: " + System.identityHashCode(o1)); System.out.println("Second: " + System.identityHashCode(o2)); } } This program overrides the function hashCode() which is perfectly legal. As a result of this, you cannot find out the real identity of the object as it would be printed in the default toString() method. The ou...

Java SE 6 Trouble Shooting Guides

Ever since I tried Java back in 2000, I have felt a little uncomfortable about the not-so-powerful and not-so-intuitive set of tools accompanying JDKs. That was one of the reasons why I didn't pursue my interests seriously in programming in Java. But the notions are changing and I mean it. From the hoopla going on about Java SE 6, I was tempted to try that. Hence you might be seeing some Java SE 6 specific posts in future too. There are a lot of powerful tools (jhat and jmap for instance) that are bundled in this SE for the pleasure of the system programmer. I came across this excellent list of tutorials when I was browsing through Mandy Chung's blog . She is the person leading the Java Management & Monitoring Tools API (java.lang.management) effort. You would find this list of tutorials extremely useful. Though most of them are specific to Java SE 6, I guess some of them should be applicable to earlier JSEs too.