Tuesday Dec 22, 2009

LiveConnect improvement in JDK6

JDK6 has done lot of changes in LiveConnect. LiveConnect is a feature in the browser for communication between Java Applet and JavaScript. With the new Plugin2, most of the work has been left on browser to do. Initially it was Java which do a good amount of work. So, now the Java Plug-in will operate like any other scriptable Plug-in. ..............
[Read More]

Tuesday Jan 06, 2009

Managing Java Process from Java Code

Back to Java :). Here is a small blog on how to manage Java Process from Java itself.

Long back, I had written one blog on how to list Java Process running on System by Java Code. But with the new features of JDK6, you can not only see the list but can manage the other running Java Process. This is possible using class LocalVirtualMachine. This class has a list of methods :


Here I am just showing a simple code, which will again tell you all the running Java Process.

import sun.tools.jconsole.\*;
import java.util.\*;
public class Main {

public static void main(String[] args) {
Map map = LocalVirtualMachine.getAllVirtualMachines();
Iterator iter = map.values().iterator();
LocalVirtualMachine vm = null;
while (iter.hasNext()) {
vm = (LocalVirtualMachine)iter.next();

A very very small code :). Note that this class is not in rt.jar so we need to add jconsole.jar and tools.jar in the classpath section.
So, for running we need to use :

D:/Program Files/Java/jdk1.6.0_11/bin/ControlJavaApp>../javac -cp "D:/Program Fi
les/Java/jdk1.6.0_11/lib/jconsole.jar" Main.java

D:/Program Files/Java/jdk1.6.0_11/bin/ControlJavaApp>../java -cp .;"D:/Program F
iles/Java/jdk1.6.0_11/libjconsole.jar";"D:Program Files/Java/jdk1.6.0_11/lib/t
ools.jar" Main

Or we can modify classpath in Env. Variables.

Right now, in my system it is displaying:

org/netbeans/modules/javafx/preview/Main 1
That means, this code itself and Netbeans is running as a java process.

In next blog, we will try to see how to manage(not listing) other running java code from a java code. I am not able to find too much of doc from net, so things are slow :).

Monday Sep 15, 2008

A nasty Problem - Java Code

Few days back, I got a problem in which actually I have to get the fields, constructor and method name from a java class. One can think of using reflection API and the problem is easy to solve, but that is not the case. Reflection API can only be used on class files not Java file. Than a quick idea came into mind to compile the file internally, use reflection and then delete the class file, if user don't want to see it. This is never be a tough job if I use JDK6 JavaCompiler code which is :

import java.io.IOException;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class JDK6FirstCompile {
  public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int results = compiler.run(null, null, null, "HelloWorld.java");
    System.out.println("Success: " + (results == 0));

class HelloWorld {
  public static void main(String args[]) {
    System.out.println("Hello, World");

But but, I was constraint to use JDK5 or less. So, this JDK6 API is not worth for me :-(. Finally, came up with a small code, which probably can do this in all the case. Hoping it will not lose any generic behavior and run in all cases.

Here is the code:

import java.io.\*;

public class CompileCheck {

public void compileClasses2() {
        try {
            String command = System.getProperty("java.home")+File.separator + ".." + File.separator+"bin"+File.separator+"javac " + "HelloWorld.java";
    } catch (Exception e) { }

    public static void main(String[] args) {
        CompileCheck c = new CompileCheck();

In place of HelloWorld, I can surely use any path where the java file resides. And off course, I can use \*.java as well :-). Please let me know your opinion or any other method easier than this from which I can get class methods, attributes and all from a java file.

Monday Aug 04, 2008

Java API + Flickr API

I decided to play with Flickr API's for Java FX coding. But in between I found myself in hell and I started with Java :-). As all of you know Flickr Support hell lot of API to view Image, to search image, to search comment, Image translation, Image upload and many more. Check out here for detailed API. Now using these API's are not at all tough, because its all a game of XML.

Here I have written a small code, which do this :

1. It search one image(it can work for more than one image) from search API of Flickr.
2. It writes the search data on a XML, which I am copying at D:\\Hello1.xml.
3. And finally the code is using XML parsing techniques to get the information required for image view.
4. Then I use JDK6 feature of Desktop and open the default browser with the parsed URL. And
Congratulations, you can see the image.

Code, can look little big because of bad coding and writing lot of repetitive things :D.  

package flickrapp;

import java.awt.Desktop;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import java.io.\*;
import java.net.\*;
import java.util.\*;

public class Main {

    public static void main(String args[]) throws Exception {
        URLConnection uc = new URL("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=e3471e67d4ac10c64055420d9b211b4f&per_page=1&text=Bangalore").openConnection();
        DataInputStream dis = new DataInputStream(uc.getInputStream());
        FileWriter fw = new FileWriter(new File("D:\\\\Hello1.xml"));
        String nextline;
        String[] servers = new String[10];
        String[] ids = new String[10];
        String[] secrets = new String[10];
        while ((nextline = dis.readLine()) != null) {
        String filename = "D:\\\\Hello1.xml";
        XMLInputFactory factory = XMLInputFactory.newInstance();
        System.out.println("FACTORY: " + factory);

        XMLEventReader r = factory.createXMLEventReader(filename, new FileInputStream(filename));
        int i = -1;
        while (r.hasNext()) {

            XMLEvent event = r.nextEvent();
            if (event.isStartElement()) {
                StartElement element = (StartElement) event;
                String elementName = element.getName().toString();
                if (elementName.equals("photo")) {
                    Iterator iterator = element.getAttributes();

                    while (iterator.hasNext()) {

                        Attribute attribute = (Attribute) iterator.next();
                        QName name = attribute.getName();
                        String value = attribute.getValue();
                        System.out.println("Attribute name/value: " + name + "/" + value);
                        if ((name.toString()).equals("server")) {
                            servers[i] = value;
                            System.out.println("Server Value" + servers[0]);
                        if ((name.toString()).equals("id")) {
                            ids[i] = value;
                        if ((name.toString()).equals("secret")) {
                            secrets[i] = value;
        String flickrurl = "http://static.flickr.com/" + servers[i] + "/" + ids[i] + "_" + secrets[i] + ".jpg";
        try {
            URI uri = new URI(flickrurl);
            Desktop desktop = null;
            if (Desktop.isDesktopSupported()) {
                desktop = Desktop.getDesktop();

            if (desktop != null) {
        } catch (IOException ioe) {
        } catch (URISyntaxException use) {

Now see this line :

URLConnection uc = new URL("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=e3471e67d4ac10c64055420d9b211b4f&per_page=1&text=Bangalore").openConnection();

Here some important thing to see :

http://api.flickr.com/services/rest/?method=flickr.photos.search    -> this is the way to write Flickr API.

api_key=e3471e67d4ac10c64055420d9b211b4f  -> required for service. This is my api_key, you can have your own. Just go to flickr service and generate your API_key

per_page=1  -> Here is what I meant one image, if you can change this to 10. It will gather information of top 10 images in XML file.

text=Bangalore  -> Sorry, I have hard coded it for now. This is the search string.

Now, look at the XML file get generated in D:\\Hello1.xml. You can see one entry with tag photo inside photos. So, we need to take some data from this XML file and add in proper style to get the correct URL and that is here:

String flickrurl = "http://static.flickr.com/" + servers[i] + "/" + ids[i] + "_" + secrets[i] + ".jpg";

Again, lot of things are hard coded(which I will correct in next post). Since only one image (i=0). I am assuming its a jpg image :D. Now calling Desktop API, you can load this image on default browser.

Now, this is still a live question, for certain keyword search, it gives the same result like when I search for keyword "Vaibhav", code and search box of Flickr provided the same result(which is not my photo :-( )  whereas if I search on things like "Bangalore", result is not similar for many cases. I don't know how Flickr handles it internally.

Probably next I will try to upload image or translate image but in Java FX :-)

Thursday Jul 03, 2008

XML Event in JDK6

Java SE 6, added the new class XMLEvent in the package javax. xml. stream.events. This is the base event interface for handling markup events. Not only that,  Events may be cached and referenced after the parse has completed.

I have simply tried to write a code which can find the skeleton of my XML file and show me only tag structure. 10 lines of code is enough to do this job. And with the strong API of XMLEvent , you can play with thousands of things in a XML file.

Here is my XML file(taken somewhere from Internet):

 <recipe name="bread" prep_time="5 mins" cook_time="3 hours">
<!-- this is comment section -->
   <title>Basic bread</title>
   <ingredient amount="8" unit="dL">Flour</ingredient>
   <ingredient amount="10" unit="grams">Yeast</ingredient>
   <ingredient amount="4" unit="dL" state="warm">Water</ingredient>
   <ingredient amount="1" unit="teaspoon">Salt</ingredient>
     <step>Mix all ingredients together.</step>
     <step>Knead thoroughly.</step>
     <step>Cover with a cloth, and leave for one hour in warm room.</step>
     <step>Knead again.</step>
     <step>Place in a bread baking tin.</step>
     <step>Cover with a cloth, and leave for one hour in warm room.</step>
     <step>Bake in the oven at 180(degrees)C for 30 minutes.</step>

And here is the small code, helped me to find out the tag structure.

import java.io.FileInputStream;
import javax.xml.stream.\*;
import javax.xml.stream.events.\*;

public class EventParse {
    public static void main(String[] args) throws Exception {

        String filename = "hello.xml";
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLEventReader xmler = factory.createXMLEventReader(filename,new FileInputStream(filename));
        System.out.println("Skeleton of XML file:");
        while (xmler.hasNext()) {
            XMLEvent e = xmler.nextEvent();
                 if(e.getEventType()==1) {
                  if(e.getEventType()==2) {

and the output:

<recipe cook_time='3 hours' name='bread' prep_time='5 mins'>
<ingredient amount='8' unit='dL'>
<ingredient amount='10' unit='grams'>
<ingredient amount='4' unit='dL' state='warm'>
<ingredient amount='1' unit='teaspoon'>

Saturday Jun 28, 2008

Why JDK6 again ?

Again a comparison and reason why JDK6. Weeks back one of our team member gave a presentation on JVM performance improvement in Mustang. I have just collected a useful point here and try to compare with older JDK version. Here is the code:

import java.util.\*;

public class RuntimePerformanceGC {
    public static void main(String[] args) {
        RuntimePerformanceGC ob = new RuntimePerformanceGC();
        Vector v = new Vector();
        java.util.Date now = new java.util.Date(); 
        long t1 = now.getTime();                   
        java.util.Date now1 = new java.util.Date();
    public void addItems(Vector v) {
        for(int i =0;i<500000;i++)
        v.add("Item" + i);

And the output in ms is:

JDK1.4.2: 984

JDK 6: 578

You can see a massive difference. 37 percent improvement in time. Why ? Here goes :

This is because of Runtime Performance Optimization. The new lock coarsening optimization technique implemented in hotspot eliminates the unlock and relock operations when a lock is released and then reacquired with no meaningful work done in between those operations. And this is what happening in our example. Since, Vector do thread safe operation, it takes the lock for add, release the lock and then takes it again. 

So, I just tried to give one more reason why use JDK6 ;-). This is off course not the only reason for big improvement, I will try to cover some more in upcoming blogs :-)

Monday May 12, 2008

Nimbus Look And Feel

Good news for all the user, using JDK6. Though I am little late in
writing blog on this but its OK ;). JDK6 current update comes with a
new L&F(Look And Feel) called Nimbus.

Nimbus provide more lively look and feel in Swing UI. Here are some examples:

Default Look And Feel(Click to see enlarged mode)
Nimbus Look And Feel((Click to see enlarged mode)

the image is little small and related to my Online Java Project(which I
can't change), so I provide another example here from my last blog code.

Default Look And Feel
Nimbus Look And Feel

more interesting is focus traversal on components. For Default L&F,
you can see that there is a dotted rectangle on Button 3, which says
"Focus is here" whereas in Nimbus you can see Button 1 with little
bluish highlight which says "Look at my focus" :)

Quickest way to try, command line:

Run my previous (or any UI code) with the following option:

java -Dswing.defaultlaf=com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel LayoutCheck

Off course, you can do it with code :

Use try, catch and respect Exception handling as well.

Friday Nov 30, 2007

Java SE6 and FX Presentation @ College

This Diwali I got time to visit my college. My college is very special to me as we are the first batch of the college. We saw the arrangements of bricks,layers of cement,the time when college was one lecture hall big. And now its so cool. Anyway, given the presentation/demo on Java SE6 and a small one on FX. Here are the slides

Presentation on Java SE6
Presentation on JavaFX

and here is the demo code:

Code used for Demo in Java SE6.

If I missed something just drop a comment.  



Vaibhav Hi, I am Vaibhav Choudhary working in Oracle with JDK team. This blog is all about simple concept of Java, JVM and JavaFX.


« June 2016