>

Vaibhav's Blog Space

XML Event in JDK6

Thursday Jul 03, 2008

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>
   <instructions>
     <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>
   </instructions>
 </recipe>

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) {
                    System.out.println(e.toString());
                    }        
                  if(e.getEventType()==2) {
                    System.out.println(e.toString());
 
                    }
    }
   }
}

and the output:

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

[2] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

BOJUG meet at Sun Campus

Tuesday Jul 01, 2008

Here is my last week BOJUG meet slides. I have talked on Java SE6u10 features. Thanks to all the participants and organizers. Nice to see lot of Non-Sun people in Sun Campus to attend the meet.

[0] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Why JDK6 again ?

Saturday Jun 28, 2008

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();                   
        ob.addItems(v);
        java.util.Date now1 = new java.util.Date();
        System.out.println(now1.getTime()-t1);
    }
    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 :-)


[8] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Talk about Core Java New book !

Wednesday Jun 25, 2008

Talk of Cay Horstmann in Second Life happened to be cool. I got some problem in audio because of my low internet bandwidth. Here are some of the snaps.

 He covered some of the new features of SE5/6 in his talk. How those features get covered in book.

[1] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Second Life session - Core Java, Volume II—Advanced Features

Monday Jun 23, 2008

News for those who are not in Second Life(people there already know :-)) . Here is the Java Talk by Cay Horstmann. So, join the world of SecondLife and do attend the session. Here goes the detailed information:

SMI Press Author Chat with Cay Horstmann
Hosted by SDN
June 25, 2008 - 9am PT/SL
Where: Sun Pavillion, Andromeda Theater

http://slurl.com/secondlife/Sun%20Microsystems%201/128/81/71

Cay Horstmann will be talking about his new SMI Press books - Core Java, Volume II—Advanced Features and Core Java, Volume I-Fundamentals, Eighth Edition. Come listen to Cay (professor of computer science at San Jose State University and a frequent speaker at computer industry conferences) talk about his latest book and then participate in a chat with him during the Q&A!

See you there !

[2] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

6u10 features - Presentation

Thursday Jun 19, 2008

Here is the presentation I made for the BOJUG meeting. It's not the final presentation. Please provide suggestions. I have tried to cover some of the important features of 6u10.

[0] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Java Deployment Toolkit - 6u10

Wednesday Jun 18, 2008

Java Deployment Toolkit, yes again I am talking of 6u10. It deploy applets and applications to a large variety of clients with JS. I have written some one liner which has some great capability to do:

<HTML>
<BODY>
<script src="http://java.com/js/deployJava.js">
deployJava.installLatestJRE();
</script>
</BODY>
</HTML> 

It looks small code but it can install the latest JRE on your machine. Just copy paste the code in a HTML page and run it. And here is the second one:

<HTML>
<BODY>
<script src="http://java.com/js/deployJava.js"></script>
<script>
    var list = deployJava.getJREs();
        var result = "";
           result = list[0];
        for (var i=1; i<list.length; i++) {
                result += ", " + list[i];
        }
            alert("You have the following Java Platform(s) installed: \n" + result);
</script>
</BODY>
</HTML> 

This code will tell you the installed JRE's on your machine.  In all this game, the important thing is deployJava.js which has lot of other cool method. Check the link in the code for details :-). We just need to use those functions for our need. There are some better example is on sun site.


[0] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Firefox World Record

Wednesday Jun 18, 2008

Here goes the certificate of helping in world record of FireFox3 download :). Just loved it, that's why blogged.


[2] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Flop Show :( - FF3 download

Tuesday Jun 17, 2008

Very annoying, I am not able to download FF3 from original site yet. I am working from last 35 minutes. And this is what we are afraid off. In morning, I was talking that server is going to be thrashed, but my friends have view that all open source servers are going to support download. I was hoping something great but :-(

Still I am trying these links:

http://www.spreadfirefox.com/en-US/worldrecord/getinvolved

http://www.spreadfirefox.com/en-US/worldrecord

I am not happy.

[0] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Project PDF-Renderer

Monday Jun 16, 2008

Today I have raised the observer permission for project PDF-Renderer. Awesome project which help Java Developer to work on PDF format. A complete viewer and render. API's are strong and I have just check this code from site itself. This code put the first page of your PDF file inside PagePanel. No doubt PDF is one of the open format used worldwide across all OS. In such a case, support from Java is something like adding more flavor in sweet.


import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PagePanel;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.swing.*;

/**
 * An example of using the PagePanel class to show PDFs. For more advanced
 * usage including navigation and zooming, look ad the 
 * com.sun.pdfview.PDFViewer class.
 *
 * -AT-author joshua.marinacci@sun-DOT-com
 */
public class Main {

    public static void setup() throws IOException {
    
        //set up the frame and panel
        JFrame frame = new JFrame("PDF Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        PagePanel panel = new PagePanel();
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);

        //load a pdf from a byte buffer
        File file = new File("Amityform.pdf");
        RandomAccessFile raf = new RandomAccessFile(file, "r");
        FileChannel channel = raf.getChannel();
        ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY,
            0, channel.size());
        PDFFile pdffile = new PDFFile(buf);

        // show the first page
        PDFPage page = pdffile.getPage(0);
        panel.showPage(page);
        
    }

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {⁞
                    Main.setup();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}

Just download the jar file from project site. And then :

javac -cp PDFRenderer.jar Main.java

java -cp PDFRenderer.jar;. Main

It is pretty fast as well, because IO operation has been done by NIO and channels are superb.  Thanks guys for making such a great project.

[0] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Add JRE/ Run Old JRE - 6u10 :)

Sunday Jun 15, 2008

Yesterday, I have started making a presentation on J2SE 6u10. And I will be like delighted again seeing the new features of Plug-in which we called Next Generation Plug-in. Some of the common problems I used to face while doing my job :

Installation and Un-Installation of JRE's - This was a region of major concern. Most of the time I never install JDK or JRE, I love to untar or unzip it, so that it will not play with my registry. But the problem with those when I run Applet. Untar JDK/JRE not used to be a suitable candidate for applet because it takes only the installed JRE. But now, we can point our applet to the untared/unziped JRE and it will all work. Uncheck all the other JRE's which is not required, run the applet. It will all rock :)



I have clicked on the Find button and added the JRE 1.7. Now, I unchecked all the other JRE and ran my applet. It will run on JRE 1.7 (Remember IE6+ and FF3 or + only)

Here is the snap shot of old Java Control Panel:





And now we will also get rid of running applet on older installed JDK/JRE. Initially it used to be if I have to check one applet on 2 different JRE, I have to install and uninstall it again. But now it all work with one checkBox option :)

[0] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Double on 64 bit OS on 64 bit JVM

Friday Jun 13, 2008

Weeks back, one of our colleagues came with a problem. Customer asked them "Any way to get more precision for double on a 64 bit OS on  a 64 bit JVM". I guess it is not possible. I checked the same with this small code.

 
class checkDouble {
    public static void main(String[] args) {
        double num = 1.232432537658635234534645768d;
        System.out.println("Number" + num);
    }
}
Hopefully this code will tell the precision.  I have checked the same code on 64 bit machine with -d64 flag like

>> java -d64 checkDouble

but results on the same output. It should be actually, else class file will behave differently on different OS, different processor. 64 bit JVM we use to make operation faster on a 64 bit OS, there can't be any other rocket science possible with 64 bit OS support. And if you want to go for higher precision use BigDecimal :-)

[4] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

It is damn fast, last post is idiotic work :)

Wednesday Jun 11, 2008

I have done a blunder mistake in my last post, thats what I am correct it. Because reading to the post topic, it seems that Java Sorting API is slow but it is not. As mentioned in the comment section by Chris Elving, Array Class get loaded while the BubbleSort class is not in the previous scenario. And so we need to write code like:

import java.util.*;
public class BubbleSort1 {

    public static void main(String[] args) {
        int numbers[] = {10,20,5,14,1,56,0,56,56,3,2,5,466457,765,34,5,346,45676,23435,767,2545,62432,3,2,33,3,3,6,78,8,3435,7,3454567,35,50};
        int numbers1[] = {10,20,5,14,1,56,0,56,56,3,2,5,466457,765,34,5,346,45676,23435,767,2545,62432,3,2,33,3,3,6,78,8,3435,7,3454567,35,50};
        int length = numbers.length;
        long startTime1 = System.nanoTime();
        BubbleSort.sortIt(numbers,length);
        long endTime1 = System.nanoTime();
        System.out.println("Time taken in Sorting  : " + (endTime1-startTime1)+ " nanoseconds"); 
        showIt(numbers);
        long startTime2 = System.nanoTime();
        sortbyAPI(numbers1);
        long endTime2 = System.nanoTime();
        System.out.println("Time taken in Sorting  : " + (endTime2-startTime2)+ " nanoseconds"); 
        showIt(numbers);
    }

    public static void sortIt(int numbers[], int length) {
        int temp;
        for(int i=length-1;i>=0;i--) {
            for(int j=1;j<=i;j++) {
                if(numbers[j-1]>numbers[j]) {
                    temp = numbers[j-1];
                    numbers[j-1] = numbers[j];
                    numbers[j] = temp;
                }
            }
        }
    }

    public static void showIt(int numbers[]) {
        for(int i=0;i<numbers.length;i++) {
            System.out.print(numbers[i] + "    ");
        }
    }
 
    public static void sortbyAPI(int numbers[]) {
        Arrays.sort(numbers);
    }
} 

And then in a different class:
 import java.util.*;
public class BubbleSort {

    public static void sortIt(int numbers[], int length) {
        int temp;
        for(int i=length-1;i>=0;i--) {
            for(int j=1;j<=i;j++) {
                if(numbers[j-1]>numbers[j]) {
                    temp = numbers[j-1];
                    numbers[j-1] = numbers[j];
                    numbers[j] = temp;
                }
            }
        }
    }
}

And here is the output speed: D:\jdk1.6.0_05\bin>java BubbleSort1

Time taken in Sorting  : 624777 nanoseconds

0    1    2    2    3    3    3    3    5    5    5    6    7    8    10    14   20    33    34    35    50    56    56    56    78    346    765    767    254 5    3435    23435    45676    62432    466457    3454567 

Time taken in Sorting  : 71916 nanoseconds

0    1    2    2    3    3    3    3    5    5    5    6    7    8    10    14   20    33    34    35    50    56    56    56    78    346    765    767    254 5    3435    23435    45676    62432    466457    3454567

Huh.. 9 times faster :D 

[2] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Avoid Array Sorting API for small list ?

Wednesday Jun 11, 2008

All my personnel opinion, so can be wrong. But I have not found Array.sort very efficient for small lists and yes, it is not meant for small array list as well. I have written one small code where I have compared Sort API with the worst of all sorting algorithm, that is, bubble sort. Here is the code:

import java.util.*;
public class BubbleSort {

	public static void main(String[] args) {
		int numbers[] = {10,20,5,14,1,56,0,56,56,3,2,5,466457,765,34,5,346,45676,23435,767,2545,62432,3,2,33,3,3,6,78,8,3435,7,3454567,35,50};
		int numbers1[] = {10,20,5,14,1,56,0,56,56,3,2,5,466457,765,34,5,346,45676,23435,767,2545,62432,3,2,33,3,3,6,78,8,3435,7,3454567,35,50};
		int length = numbers.length;
		long startTime1 = System.nanoTime();
		sortIt(numbers,length);
		long endTime1 = System.nanoTime();
		System.out.println("Time taken in Sorting  : " + (endTime1-startTime1)+ " nanoseconds"); 
		showIt(numbers);
		long startTime2 = System.nanoTime();
		sortbyAPI(numbers1);
		long endTime2 = System.nanoTime();
		System.out.println("Time taken in Sorting  : " + (endTime2-startTime2)+ " nanoseconds"); 
		showIt(numbers);
	}

	public static void sortIt(int numbers[], int length) {
		int temp;
		for(int i=length-1;i>=0;i--) {
			for(int j=1;j<=i;j++) {
				if(numbers[j-1]>numbers[j]) {
					temp = numbers[j-1];
					numbers[j-1] = numbers[j];
					numbers[j] = temp;
				}
			}
		}
	}

	public static void showIt(int numbers[]) {
		for(int i=0;i<numbers.length;i++) {
			System.out.print(numbers[i] + "    ");
		}
	}
	
	public static void sortbyAPI(int numbers[]) {
		Arrays.sort(numbers);
	}
} 

This are very clear from output:

E:\Program Files\Java\jdk1.6.0\bin\SoringPrograms>java BubbleSort

Time taken in Sorting : 90514 nanoseconds

0 1 2 2 3 3 3 3 5 5 5 6 7 8 10 14 20 33 34 35 50 56 56 56 78 346 765 767 2545 3435 23435 45676 62432 466457 3454567

Time taken in Sorting : 190527 nanoseconds

0 1 2 2 3 3 3 3 5 5 5 6 7 8 10 14 20 33 34 35 50 56 56 56 78 346 765 767 2545 3435 23435 45676 62432 466457 3454567

I have decided to check the code in OpenJDK(\src\share\classes\java\util\Arrays.java). And I find lot of interesting things there:

- The sorting algorithm is a tuned quicksort (written in the documentation)

- In the real code, for short array, Insertion sort has been used, for big array pseudomedian  and so many thing ..

- It means it should be fast for any sorting array, but not the case with me :-(. I am making any mistake ? Huh, need time to check the code !

[3] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg

Starting JavaFX - Animation

Sunday Jun 08, 2008

From last 5 months or so I was thinking to start posting on JavaFX. It's no doubt a powerful language and off course it should be, because its for designers not for developers. I have written a small code. This code runs (move is a better word) a car on a road :D... both the images are on network. See the number of lines of code you need to write for this. I have written 16 lines of code which includes 3 line in header file addition.


import javafx.ui.*;
import javafx.ui.canvas.*;

var scroll_time;
scroll_time = [600..100] dur 4000 linear continue if true;
var h = 50;
var car = ImageView {
    transform: bind translate(scroll_time, 0)
    image: Image { url: "http://blogs.sun.com/vaibhav/resource/car.png"}
};
var road= ImageView {
      image: Image { url: "http://blogs.sun.com/vaibhav/resource/11.PNG"}
};
Canvas {
    content: [road, car]
}

One should be delighted if animation will go so small :D.



[2] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg