Wednesday, May 30, 2012

Convert char[] array to byte[] array in Java

I have spent a few hours trying to convert a char[] returned by a JPasswordField into a byte[] that I can encrypt in Java. Here is the conversion code that I finally came up with :
      public void testArrayConversionJapanese() {  
           String hello = new String("こんにちは世界");  
           char[] charArray = hello.toCharArray();  
           byte[] byteArray = new byte[charArray.length*2];  
           for (int i=0; i < charArray.length; i++) {  
                byteArray[i*2] = (byte) ((charArray[i] & 0xFF00) >> 8);  
                byteArray[i*2+1] = (byte) (charArray[i] & 0x00FF);  
           }  
           char[] chars2 = new char[byteArray.length/2];  
           for(int i=0; i < chars2.length; i++) {  
                //bytes must be & with 0x00FF to convert negative values into unsigned positive values  
                chars2[i] = (char) (((byteArray[i*2]&0x00FF) << 8) + (byteArray[i*2+1]&0x00FF));  
           }  
           String hello2 = new String(chars2);  
           assertEquals(hello, hello2);  
      }  
As you can see above, I have used basic array and shift operations for the conversion. This is much more efficient than using java.lang.Character, String and Byte classes to do the conversions.

Tuesday, May 29, 2012

NoClassDefFoundError in Eclipse after upgrade

Sometimes when you open a project for the first time after upgrading your Eclipse IDE, you may find that the project does not run. All the classes and package structure look fine in the Package Explorer but the application fails to run with a NoClassDefFoundError. Even your JUnits fail with the NoClassDefFoundError and the stacktrace usually looks like this:

 Exception in thread "main" java.lang.NoClassDefFoundError: com/vj/test/javatext/TestByteCharConversion  
 Caused by: java.lang.ClassNotFoundException: com.vj.test.javatext.TestByteCharConversion  
  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:307)  
  at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)  
  at java.lang.ClassLoader.loadClass(ClassLoader.java:248)  
 Could not find the main class: com.vj.test.javatext.TestByteCharConversion. Program will exit.  


The root cause of this could be builders that your project depends upon but are no longer available in the upgraded version of Eclipse. For example, you may have AspectJ code that depends on the AJDT plugin being available in Eclipse. You can confirm this by opening Project -> Properties -> Builders. If you find any "Missing builder" entries, download the appropriate plugins from the Eclipse Marketplace. This should solve your problems. Here is a sample screenshot.


Hope this post helped you.