w3hJava

What, Why, When and How of Java, JavaFX and related technologies

Archive for the ‘Java’


Published August 13th, 2008

Java + PDF !

Java is such a big language now, that we ofter need to handle all type of application with Java. You may end up with a situation where you want to call MS word from Java, or Open Document from Java. Now, months back, I got a situation where I need to call some PDF formats from Java and need to do some operation on its pages. At that time, I have explored the Project - PDF Renderer on java.net site. Its an awesome project and cool operations.

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.

Published July 29th, 2008

Use default client for mailing - JDK6

Sending mails or messaging from Java is never been a tough process but still most of us has to write Java Messaging API or Java Mail API to do this, which is a cumbersome process in itself.

JDK6 came with a new Desktop class in which you can give user the option to work on the default mail client, do whatever you want to do and after closing the default client the control will go back to the java code. Here is a small code to do that:

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;

public class DefaultMail {
public static void main(String[] a)throws Exception {
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}

desktop.mail(”mailto”, “vaibhav.choudhary@sun.com”, null);
}
}

The idea is clean I guess, the default client will give more option than Java mail API or anything else. Desktop class give lot more other functionality as well, which we will discuss later.

Published June 28th, 2008

BOJUG Talk and Presentation

Last Friday, I have given a talk on Java SE 6u10 features in BOJUG meet. Here is the presentation.

These slides basically talks about Java SE 6u10 features. Some of them are cool like

-> Next Generation Plugin where you can drap plugin outside the browser.

-> Kernel JRE. Download small JRE.

-> Nimbus Look And Feel

-> New Applet feature which we talk in prev. blog.

And many more.

Please provide your comment on the presentation.

Published June 21st, 2008

How to use JDK 6 to solve memory issues?

Take care of disk space when you are writing a big program :). Use JDK 6 features:

import java.io.File;

public class DiskSpaceCheck {
public DiskSpaceCheck() {
File file = new File("E:");
System.out.println("E:");
System.out.println("Total:  " + file.getTotalSpace());
System.out.println("Free:   " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());

file = new File("E://movie");
System.out.println("E://movie");
System.out.println("Total:  " + file.getTotalSpace());
System.out.println("Free:   " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());

file = new File("/");
System.out.println("n/");
System.out.println("Total:  " + file.getTotalSpace());
System.out.println("Free:   " + file.getFreeSpace());
System.out.println("Usable: " + file.getUsableSpace());
}

public static void main(String[] args) {
new DiskSpaceCheck();
}
}

I was actually very suprised that why this feature came so late.

Published June 17th, 2008

Test your applet on different JRE’s

In last post on StringBuffer, Dimitris Andreou commented that it was an old thing. ;-). So, I decided to write something new which is currently going on in Sun Microsystems. Finally I zeroed down on Java SE 6u10 features. Some of them I blogged on my Sun site but here are some more.

Very often this happens. You made a UI in applet and want to check whether the application is working fine on all JRE’s or not. If you are not, then please do it :).?I have seen people still using JDK 1.3. I, myself use jdk1.4.2 for many reasons and it still survive somewhere in the company standards. Now, if you want to check the applet on all JRE’s, welcome to the world of JRE 6u10 features.

Here is the demo:

Write a normal applet code, say Hello World.

import java.awt.*;
import java.applet.Applet;

public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World",50,50);
} // end of paint
} // end of applet

And now the interesting part, write the HTML file like:

<APPLET CODE="HelloWorld.class" WIDTH=200 HEIGHT=100>
<PARAM name="java_version" value="1.5.0_20">
</APPLET>

It will run the applet on JRE 1.5.0_20(if exists on machine). For more generic once, write:

<APPLET CODE="HelloWorld.class" WIDTH=200 HEIGHT=100>
<PARAM name="java_version" value="1.4*">
</APPLET>

It will check any flavor of 1.4 like 1.4.2_01 or 1.4.2_10 on your machine. 6u10 rocks ! Remember it will work in IE6 or + and FF3 or +. Ah, I remember, today is FF3 download day. So, please don’t forget to download FF3.

Published June 4th, 2008

Final can improve performace !

Last month, me and Abhishek was discussing about some performance issue. Finally we came on a good conclusion and so I decided to write a blog. One of the Orkut users posted a question on our community

“As we know that by declaring method as final, we cant override them. By performing this function, it provides a performance enhancement but i unable to understand how ????? can anyone help me out…… “

(I don’t know why people are using so many of dots and question marks)

Yes this is correct, writing final (can) improve the performance. WHY ?
When you define a method final, that means it can’t be overridden into its derived classes. Knowing that into the fact complier (can) inline that method into its derived classes. But but but, this is not a safe way to inline a method. WHY AGAIN ?
Because, if by any chance if method will not be final (fool the VM) in base class, then inline entry in derived class will be wrong and things can be screwed. Now very rare but this is possible in Java. Remember in Java you can write your own ClassLoader and you can make a ClassLoader where you can ignore(any how) the final declaration.
So, for those compiler in which final method be inlined before loaded into VM(unlike JIT), there is quite a high risk and hence compiler can’t do this. But in JIT compiler, this is what is happening !

In 2 line, I want to write about JIT(Just in time compiler) - at the time of interpretation,interpreter saw there is a for loop, for say 50 times. It takes the code out from interpreter and give it to runtime compiler(c1 and c2 compiler). As we know compilation is faster than interpreter. Compiler do the work and then control goes back to Interpreter. Details are quite interesting.

And this is how we finally ended our discussion :). Correct me if I am wrong.

In next post, we will discuss how to write a custom ClassLoader.

Published May 28th, 2008

Multi-threading in Java

One of the greatest features in Java is support for multi-threading. Generally we have misconceptions about the concepts of threading. We tend to think it more as a part of coding and hence take it only at coding time. Threading is all about designing and not about coding. If you want to write a good threading code, think of it before writing the code. Sometime back, I had made a presentation on multi-threading in Java with some demos. Have a look here :)

here

Presentation is very basic and talk simple things. Your comments are most welcome.

Published May 18th, 2008

Memory Retention

Finalization is mostly used in Java to reclaim resources, native resources. Say, you are writing one program using Windows Font(OS font). So, its the programmers duty to reclaim the font resource associated with any object.

If you are an application developer and uses lot of native resource then I would say stop reading this blog and read the latest Article(yes,Sep 2007) by Tony Printezis on sun site. This article is awesome and covers all the cases and its solution that can happen with Memory Retention. The simplest of that is what I am going to talk here.

class PlayWithFont {
String someText;
String newText;
private native method getFont();
void get() {
getFont();
}
// always be called by any method of this class only
private native method releaseFont();
void release() {
releaseFont();
}
protected void finalize() {
release();
}
}

Now, here I have some text and I am taking OS font, converting that text into some fancy text and then releasing the resource of Operating Systems. We have a class called PlayMoreWithFont which basically
inherits PlayWithFont and converting some String[] text into new String[] text (just a fictitious example)

class PlayMoreWithFont {
String[] someMoreText ; // lets consider it here some big chucks of memory
String[] newMoreText;
}

PlayMoreWithFont don’t have any finalize method defined, but off course its going to take one from PlayWithFont.

GC maintain a finalization queue. When a object is unreachable, object is added to the finalization queue. After that only, object goes into finalized state. Now when we called :

play = new PlayMoreWithFont;
play = null;

Now instance of PlayMoreWithFont become unreachable, but reclamation of big chunks like someMoreText and newMoreText has to wait until the instance is finalized. And this is one of the major causes of memory retention.
Moreover the problem is difficult to find if the class hierarchy is big and finalize is sitting some where very deep. There are some good solution which we can discuss in next.

Published May 13th, 2008

Listing Process from Java Code

A month back, I wanted to find out all processes running on my machine from java code for some stupid purpose. I tried to write some code and was pretty successful. Java can’t play with system process and hence invoking a runtime is only solution to get all process and here it is:

import java.io.*;
class ListProcess {
    public static void main(String[] args) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        String cmds[] = {”cmd”, “/c”, “tasklist”};
        Process proc = runtime.exec(cmds);
        InputStream inputstream = proc.getInputStream();
        InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
        BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
        String line;
        while ((line = bufferedreader.readLine()) != null) {
            System.out.println(line);
        }
    }
}

Code is written exclusively for Windows Machine :). And one line change in this code will list you only java running process.

String cmds[] = {”cmd”, “/c”, “jps”}; this is nothing but running jps.exe file in bin (jdk6 onwards). Its not all done. Writing Runtime code is not the real solution as there is little of platform dependencies. So, I have decided to write the code for getting List of Java Process. Again, I have checked by OpenJDK code for jps(search on jps.java file :) ) and I got some hint how to do it and here it goes:


import java.util.*;
import sun.jvmstat.monitor.*;
public class ListJavaProcess {
    public static void main(String[] args) throws Exception {
        /* Checking for local Host, one can do for remote machine as well */
        MonitoredHost local = MonitoredHost.getMonitoredHost(”localhost”);
        /* Take all active VM’s on Host, LocalHost here */
        Set vmlist = new HashSet(local.activeVms());
        for (Object id : vmlist) {
            /* 1234 - Specifies the Java Virtual Machine identified by lvmid 1234 on an unnamed host.
            This string is transformed into the absolute form //1234, which must be resolved against
            a HostIdentifier. */
            MonitoredVm vm = local.getMonitoredVm(new VmIdentifier(”//” + id));
            /* take care of class file and jar file both */
            String processname = MonitoredVmUtil.mainClass(vm, true);
            System.out.println(id + ” ——> ” + processname);
        }
    }
}

I have written good amount of comment as it is all together a sun import rather than java or javax import. This import resides in tools.jar, so even running simple javac and java will not work. So, running the program will go here:

E:\Program Files\Java\jdk1.6.0_10\bin>javac -classpath "E:\Program Files\Java\jdk1.6.0_10\libtools.jar" ListJavaProcess.java
E:\Program Files\Java\jdk1.6.0_10\bin>java -classpath .;"E:\Program FilesJava\jdk1.6.0_10lib\tools.jar" ListJavaProcess
3700 ------> ListJavaProcess

Right now only one java process is running. Now in the second code, you can play with some of the java process, but with native process in the above code you can’t do anything except watching it :)

No idea how to do this in JDK 1.5 or backwards(runtime is off course one option).

Published May 11th, 2008

Number of JREs on my Windows machine?

Sometime back, we were discussing something about JRE and one of my friends Lawrence asked me “How to find the number of JRE  installed on system with the help of Java Code ?

After giving much thought to it, I don’t think Java has any such API which will tell how many JRE are installed on the System and what are they ? One of my another friend Vikram told me that JRE installation records information in Registry. With this knowledge at the hindsight, I tried to write this piece of code.

It will only run on Windows :) because I have used Runtime class. I would love to know how the same could be achieved in Unix Systems. This code is not doing anything great, just queries the registry and reflects the answer on the console.

import java.io.*;
class NoofJRE {
    static String REG_PATH = "reg query " +
                          "\"HKLM\Software\JavaSoft\Java Runtime Environment";
       public static void  getJREInfo() {
            try {
            Process process = Runtime.getRuntime().exec(REG_PATH);
                  InputStream inputstream = process.getInputStream();
                  InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
                  BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
                  String line;
                  while ((line = bufferedreader.readLine()) != null) {
                           System.out.println(line);
                  }
          }
            catch (Exception e) {
                  System.out.println("I am in Exception");
        }
      }
      public static void main(String s[]) {
            getJREInfo();
        }
}

And here is my output:

E:\Program Files\Java\jdk1.6.0\bin>java NoofJRE
! REG.EXE VERSION 3.0
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment
CurrentVersion REG_SZ 1.6
BrowserJavaVersion REG_SZ 1.6.0_01
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.4.2_17
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.6
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.6.0
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\1.6.0_01

Which sounds true in my case. It is clearly telling me that I have JRE 1.4.2_17, 1.6.0 and 1.6.0_01. I have old bad habit of not uninstalling JRE’s :).

Please do let me know if there is any other way to know how many and which JRE is/are installed in my system.

To know where the JRE is installed, one has to do a simple query of JAVA_HOME in the registry.