Archive for the ‘Java’ Category

Capture Screenshot in Java

March 2, 2007

I was trying to generate the thumbnail of an HTML page through Java. I could not find a great way, but in the process I found how to capture the screen in a Java program. It is pretty easy. The following program opens the IE in a full screen mode and then captures the screen. This image can be used later on to get the smaller sized image.  

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.io.File;


public class ScreenCapture {
  public static void main(String[] args) throws Exception {
  Runtime rt = Runtime.getRuntime();
  String[] cmd = new String[3];
  cmd[0]="C:/Program Files/Internet Explorer/iexplore.exe";
  cmd[1]="-k"; // Open the browser in full screen mode
  cmd[2]="java.sun.com";
  Process process = rt.exec(cmd);
  // Sleep for some time so that page can be loaded fully by browser
  Thread.currentThread().sleep(20*1000);
  Robot robot = new Robot();
  // Capture the screen shot
  BufferedImage bi=robot.createScreenCapture(
  new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
  ImageIO.write(bi, "jpg", new File("C:/imageTest.jpg"));
  // Kill the browser
  process.destroy();
  }
}

New features in JDK 6

February 26, 2007

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.

I will post my experiments with this release in the coming days.

Equality problem with an Object and its dynamic proxy.

January 11, 2007

I met with this problem while working on something else. In a hashmap I was using an object and its proxy as the key. What I saw was that, even if I put both the object and proxy, the hashmap will take only one object. I was confused for some time and then I realized that internally, when HashMap invokes ‘equals’ method, the InvocationHandler of the proxy delegates that method as well to the actual object, so that will always return true. Hence, I will never be able to have both as keys. To make it clear

MyObject obj ; //say it is some valid object implementing MyIntf interface.ProxyOfMyObject proxy ; //say this is the valid proxy of obj

obj.equals(proxy) returns false. That is understood.

proxy.equals(obj) will return true. This happens because the invocation handler will call the obj.equals(obj) internally.

To fix this, I created one more interface ‘ForEqualsMyIntf’ that extends ‘MyIntf’. This interface doesn’t have any methods. I will create the proxy using this ‘ForEqualsMyIntf’ interface, rather then the usual ‘MyIntf’. And in the ‘inovke’ method of Invocation Handler, I will check if the object passed in ‘equals’ method is instanseof ‘ForEqualsMyIntf’. So, when proxy.equals(obj) is invoked, since the obj is not implemeting ‘ForEqualsMyIntf’, it will return false. I am giving the sample code for this invocation handler below.

class MyInvocationHandler implements InvocationHandler {
  private MyObject obj;
public MyInvocationHandler(MyObject obj) {
  this.obj = obj;
  }

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  if(method.getName().equals("equals")) {
  Object other = args[0];
  if(other instanceof ForEqualsMyIntf) {
  if(other == proxy) {
  return new Boolean(true);
  } else {
  return new Boolean(false);
  }
  } else {
  return new Boolean(false);
  }
  }
  Object result = method.invoke(obj, args);
  if(method.getName().equals("toString")) {
  return "Proxy - " + result;
  }
  return result;
  }
  }

Experience with Generics and ScheduledThreadPoolExecutor in Java 5

November 11, 2006

I got a chance to use generics recently. We are building a J2EE application that will work as a server for another client product. As all other server, we needed a Scheduler to schedule various background tasks. I thought I will do it and with Java 5 it is kind of straight forward with ScheduledThreadPoolExecutor. To add more fun to it, I added few more features and there I ran into problems with Generics.

  1. The biggest problem is very basic. Generics are compile-time constructs and hence the power of generics is greatly limited. There are reflection APIs but they are of no use as I can’t use them to do anything functional.
  2. The code becomes very difficult to understand.
  3. The classes that uses parameters are not good candidates for serialization and de-serialization. There is no way to push the types while de-serializing and this is again due to compile-time nature of it.

Looking at all above, I decided the cut the scope of generics in my module and its pretty much managiable.

About ScheduledThreadPoolExecutor, its a great funtionality. I just wanted that there is way to relate the task that is submitted and Runnable that is created by the executor. This is required in many utility methods like RejectedTaskHandler, where in I might want to invoke a funtion on the rejected task. There could be lot more applications for this. In Sun’s implementation I found out that it basically uses the returned ‘Future’ object only as runnable, but I cannot write code on the knowledge of internal implementation. It can change anytime and my program will break.