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.

Trips to NITs for campus hiring

February 26, 2007

This year I participated in my company’s campus hiring program and as part of that I visited three campuses. I had always wanted to go for campus hiring and this year I got my chance. The campuses I visited are, NIT Warangal (near Hydrabad), NIT Suratkhal (near Mangalore) and Guindy College of Engineering, Chennai. It was a mixed experience, but one thing was common that the new crop is not so serious about programming. Some of the candidates were very good in data structures and other theoratical concepts, but in programming just average!

I got to know lot many other things and it was really fun to be there. The NITs, or National Institute of Technology are known as RECs or Regional Engineering Colleges earlier. Professor Venugopalan at NIT Warangal told me interesting history behind all this name change and all. In REC days, these colleges were goverened by State Governments and were in a pathetic conditions. It was evident from the look of NIT Warangal campus. It was looking like that building have never been painted or repaired ever since they were built, somewhere in 1950s. I was just taking a walk and passed through a building which looked like locked to me. When I got closer I realized that it was Deptt. of Electrical Engineering :-)

Dr. Murli Manohar Joshi (in NDA era) gave this idea of making RECs as NITs. As part of this transformation, NITs would become autonomus bodies, just like IITs and will be funded by Centre. It was a good concept. As part of the execution, 12 directors were appointed for the first 12 converted NITs. But in our country, everything is politically driven. In the present government, Mr Arjun Singh (yes, the same reservation guy) didn’t like the idea. He threw out all the directors, and now most of the NITs are running without a director. Now, most of the colleges have funds but no person to lead the effort in making NITs as world class institutes like IIT.

I was most impressed by Professor Venugopalan at NIT Warangal. He organized the overall hiring program in an exceptional way. Deptt of Placement was very good and it displayed all the numbers. I was awed to see that last year NIT Warangal has generated as many as 708 offers. All the B.E./B.Tech. students got placed and only few M.Tech. student didn’t get the placement. This year, the story is even better. All the top companies were visiting the campus.

While arrangements were really cool at Warangal, it was opposite in NIT Suratkhal. Actually, it was opposite in many ways. The campus is nice. In fact, this is the only college in India which has its own private beach!!!  No kidding. This campus is 20 KMs from Mangalore. The road between Mangalore and Suratkhal is hell and it took us more than an hour to reach there. The students were nice, but placement coordinator was keen on talking about himself rather than students. No planning, no arrangements, nothing. While I was giving presentation, another company arrived and I was asked to finish early!!! I liked Mangalore as city and I think state govt. should put more efforts in developing it as big city. Infosys has a centre there. Mangalore, though small, is a very advanced town. At least two nationalized banks (Canara Bank and Corporation Bank) started from there. Karnatka Bank also started from there. This city has given lots of hoteliers as well. The beach was nice and I had lot of fun there. The city has lots of Ice Cream parlours and ‘Gadbad’ is famous ice cream from Ideal Icecream Parlour. Another famous thing I couldn’t try is Golli Bajji. I hope I will try it next year.

Chennai was no-event kind of experience.  

Overall, it was a nice experience and a good way to learn about the history and geaography of places. I am hoping that next year I will be visiting to new places.

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;
  }
  }

School admissions

November 16, 2006

Before I had finished celebrating my daughter’s admission, a new diktat has come from Karnatka Education Minister, Mr. Horatti. He says that schools cannot give admissions to pre-nursary students before April next year. The is done for the parents who will be transferred to Bangalore next year. This is rubbish!!! For less than 1% students, 99% will have to suffer. I just wish that these ministers do something useful rather than passing these useless rules. Schools affiliated to CBSE/ICSE are saying that they cannot be govenrned by these rules, but lets see what happens.

Keeping my fingers crossed!

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.

My daughter’s school admission

November 11, 2006

My daughter is turning 3 and she would be going to school from next year. Getting admission in a Bangalore school is really difficult and I finally managed to get admission in Greenwood High (www.greenwoodhigh.com) . I was trying for three schools in Kormangala as it would be near to home and creche.

NPS – They clearly said while giving out forms that its tough to get admission there. They have two parallel systems – Montessory and Nursary. For Montessory, my daughter is over-age and for nursary, she is under-age. Funny thing. Never have a baby in December!!!

Bethany High – The entire process is very cumbersome. I have to write an application to get an application form. With the application form, address proof, birth certificate and medical certificate (yes, its true) has to attached. They don’t have the bus facility for pre-nursery and nursery students, so though this school has the best location for me, it will not fit nicely. After submitting the form, I was told to remember the form number. They will display the list of candidates for interview on 20th December and they will just display the form number there. Overall experience was not very nice and it gave a government school kind of impression.

Greenwood High – This school is from the same management as Bethany high. The queue is very long and the school in Koramangla is upto UKG only. The main school is on Sarjapur Road. The school has created a good impression and has grown rapidly, one indicator is that their admission fee is doubling every year!!

Of the above, Greenwood seemed to be the best choice.

These schools are pretty expensive. Not sure trying admission in these schools is the right thing to do as I also believe that I don’t have to spend that much money to get good education for my kid.

Hello world!

November 11, 2006

Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!


Follow

Get every new post delivered to your Inbox.