Friday, August 27, 2010

Java : Simple program to get system properties

If you want to know your system properties or you want to create properties file listing all properties of your system. Lets see a simple java program which lists all system properties of your computer.

/* MySystemProperties.java */

import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

public class MySystemProperties {
  
    public static void main(String[] args) {
      
        System.out.println("# My System Properties");
      
        Properties properties = System.getProperties();
      
        Set<String> propertiesSet = properties.stringPropertyNames();
      
        Iterator<String> iterator =  propertiesSet.iterator();
      
        String name;
      
        while (iterator.hasNext()) {
          
            name = iterator.next();
            System.out.println(name+" = "+properties.getProperty(name));
        }
      
    }

}


Output (output may differ depending on your computers properties)

# My System Properties
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jre6\bin
java.vm.version = 17.0-b17
java.vm.vendor = Sun Microsystems Inc.
java.vendor.url = http://java.sun.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
sun.java.launcher = SUN_STANDARD
sun.os.patch.level = Service Pack 3
java.vm.specification.name = Java Virtual Machine Specification
user.dir = C:\MY\Code\Test
java.runtime.version = 1.6.0_21-b07
java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs = C:\Program Files\Java\jre6\lib\endorsed
os.arch = x86
java.io.tmpdir = c:\temp\
line.separator =

java.vm.specification.vendor = Sun Microsystems Inc.
user.variant =
os.name = Windows XP
sun.jnu.encoding = Cp1252
java.library.path = C:\WINXP\system32;.;C:\WINXP\Sun\Java\bin;C:\WINXP\system32;C:\WINXP;C:\WINXP\system32;C:\WINXP\;C:\WINXP\System32\Wbem;C:\WINXP\system32\nls;C:\WINXP\system32\nls\ENGLISH;C:\Program Files\UltraEdit\;C:\Program Files\CA\SC\CAWIN\;C:\Program Files\IBM\Personal Communications\;C:\Program Files\IBM\Trace Facility\;C:\WINXP\system32;C:\WINXP;C:\WINXP\System32\Wbem;C:\WINXP\system32\nls;C:\WINXP\system32\nls\ENGLISH;c:\Program Files\Novell\ZENworks\;C:\PROGRA~1\CA\SC\CAM\bin;C:\Program Files\CA\DSM\bin;C:\Program Files\SSH\SecureCRT\;C:\Program Files\SSH\SecureFX\;C:\Program Files\Rational\common;C:\Program Files\SQLLIB\FUNCTION;C:\Program Files\SQLLIB\help\;C:\Program Files\SQLLIB\samples\repl\;C:\Program Files\IBM\IMNNQ\;C:\Program Files\SQLLIB\bin\;C:\PROGRA~1\IBM\SQLLIB\BIN;C:\PROGRA~1\IBM\SQLLIB\FUNCTION;C:\Program Files\Java\jre6\bin;C:\Program Files\Java\jdk1.6.0_21\bin;C:\Program Files\Java\jdk1.6.0_21\bin;C:\Program Files\Java\jre6\bin;Z:.;Y:.;X:.
java.specification.name = Java Platform API Specification
java.class.version = 50.0
sun.management.compiler = HotSpot Client Compiler
os.version = 5.1
user.home = C:\Documents and Settings\madan
user.timezone =
java.awt.printerjob = sun.awt.windows.WPrinterJob
file.encoding = Cp1252
java.specification.version = 1.6
user.name = madan
java.class.path = .
java.vm.specification.version = 1.0
sun.arch.data.model = 32
java.home = C:\Program Files\Java\jre6
java.specification.vendor = Sun Microsystems Inc.
user.language = en
awt.toolkit = sun.awt.windows.WToolkit
java.vm.info = mixed mode, sharing
java.version = 1.6.0_21
java.ext.dirs = C:\Program Files\Java\jre6\lib\ext;C:\WINXP\Sun\Java\lib\ext
sun.boot.class.path = C:\Program Files\Java\jre6\lib\resources.jar;C:\Program Files\Java\jre6\lib\rt.jar;C:\Program Files\Java\jre6\lib\sunrsasign.jar;C:\Program Files\Java\jre6\lib\jsse.jar;C:\Program Files\Java\jre6\lib\jce.jar;C:\Program Files\Java\jre6\lib\charsets.jar;C:\Program Files\Java\jre6\classes
java.vendor = Sun Microsystems Inc.
file.separator = \
java.vendor.url.bug = http://java.sun.com/cgi-bin/bugreport.cgi
sun.cpu.endian = little
sun.io.unicode.encoding = UnicodeLittle
sun.desktop = windows
sun.cpu.isalist = pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86

Thursday, August 26, 2010

Java Decompiler : Simple Java Program to decompile .class files

I was wondering is there a java program to decompile a .class file of another java program or itself. I searched on internet but I didn't found any, latter I decided to write my own. but how..... lets see.

When we compile a java file, JVM creates .class file. But imagine you have a .class and you need to create its source .java file, in such case you can use java decompiler which creates .java file of a .class file.


However many times decompiled .java file is not 100% accurate but still more or less you will get idea about what the java file consist of.

There are many java decompiler available on internet.We will use JAD Java Decompiler to decompile our .class files because it can be easily integrated with our Java program.

To know more about JAD Decompiler click here, Also you can download latest version of JAD Decompiler. In our example we are using JAD 1.5.8 version ie jad158g.win.zip. Visit  http://www.varaneckas.com/jad to know more.

Installation

Unzip jad.zip file into any appropriate directory on your hard drive.
This will create two files:

    * an executable file named 'jad.exe' (Windows 9x/NT/2000) or 'jad' (UNIX)
    * README file 'Readme.txt', which contains the short user's manual

Note : You need to add jad.exe in your CLASS PATH
Simple way just put jad.exe in your java path For Eg : C:\Program Files\Java\jdk1.6.0_21\bin\jad.exe

To test your installation just type 'jad' in your command prompt, it should produce below output.




Now Lets see the decompile process and its command.

For example, lets say we have Test.class to which we need to decompile.

C:\Jad>jad Test.class
Parsing Test.class... Generating Test.jad

This will create Test.jad file which contains java code, don't worry .jad is default extension.

C:\Jad>jad -s .java Test.class
Parsing Test.class... Generating Test.java

using -s you can provide extension of the file. This will create Test.java.

Also you can provide destination folder where you want to decomiple the .class file.

C:\Jad>jad -s .java -d C:\Dest Test.class
Parsing Test.class... Generating C:\Dest\Test.java

This will create Test.java in our desire destination folder. To know more see the 'Readme.txt' file.

 Now we can write our java program which will use above mentioned system commands and can be used as Java decompiler program.

/* JadExample.java */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class JadExample {

    public void runSystemCommand(String command) {
       
        try {
            Process p = Runtime.getRuntime().exec(command);
           
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
           
            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
           
            String s = "";
           
            System.out.println("command :: "+command);
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
           
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }           
           
        } catch (IOException e) {
           
            e.printStackTrace();
        }       
    }
   
    public void decompile(String srcClassFile,String destFolder) {
       
        runSystemCommand("jad -s .java -d "+destFolder+" "+srcClassFile);
       
    }
   
    public static void main(String[] args) {
       
        JadExample obj = new JadExample();
       
        //obj.decompile("Test.class", "."); //Current directory
        obj.decompile("Test.class", "C:\\Test");
    }

}





Run the above program and see the output. If you like it do write comments or mail me madan712@gmail.com

Monday, August 23, 2010

Java : Simple Properties Example

The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.

Properties class extends Hashtable so methods like get, hashCode, isEmpty, keys, keySet, put, putAll, rehash, remove, size can be applied to Properties class.

Lets see a simple Java Properties counter example, here we will read count values ie load value from a  data.properties file and just increment the value and again store in data.properties file. Each time we run this example it increment the count value.

 /* PropertiesExample.java */

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesExample {

        public static void main(String[] args) {
      
            Properties prop = new Properties();
           
            //load Properties prop from a file
            try {
                prop.load(new FileInputStream("data.properties"));
               
            } catch (IOException e) {
                System.out.println("IOException :: "+e);
            }
           
            //get values of count
            String count = prop.getProperty("count");
           
            System.out.println("count = "+count);
           
            //just incrementing value of count
            int newCount = Integer.parseInt(count);
            newCount++;
           
            //set the new value of count
            prop.setProperty("count",""+newCount);
           
            //save the file
            try {
                prop.store(new FileOutputStream("data.properties"),"This is a simple example");
               
            } catch (IOException e) {
                System.out.println("IOException :: "+e);
            }
           
    }

}


data.properties

#This is a simple example
#Mon Aug 23 13:05:22 IST 2010
count=12

Output










  














However you can also store / load the data in XML (.xml) file rather than .properties file using storeToXML(OutputStream os, String comment)and loadFromXML(InputStream in) method.

Also you can iterate through all parameters in Properties using propertyNames()and stringPropertyNames().

Lets look at API for more details

For eg. Data.xml
 
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>This is a simple example</comment>
<entry key="count">10</entry>
</properties>



properties file example

# this is a comment
! this is also a comment
a = a string
b = a string with escape sequences \t \n \r \\ \" \' \ (space) \u0123
c = a string with a continuation line
   \ continuation line
d.e.f = another string 


Friday, August 20, 2010

Java : Simple program to Run System Commands

Many times we require to execute system command using java program. Java do support to this using Process class, we can execute command on Runtime object using exec("command") method.

Eg : Process p = Runtime.getRuntime().exec(command);

Lets see a simple java program to run system command. directly you can this program and see the output


/* RunSystemCommand.java */

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class RunSystemCommand {

    public void runCommand(String command) {
       
        try {
            Process p = Runtime.getRuntime().exec(command);
           
            BufferedReader inputStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
           
            BufferedReader errorStream = new BufferedReader(new InputStreamReader(p.getErrorStream()));
           
            String s = "";

            System.out.println("Output stream :: \n");
            // reading output stream of the command
            while ((s = inputStream.readLine()) != null) {
                System.out.println(s);
            }
           
            // reading any errors of the command
            System.out.println("Error stream (if any) :: \n");
            while ((s = errorStream.readLine()) != null) {
                System.out.println(s);
            }
           
        } catch (Exception e) {
           
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
       
        RunSystemCommand obj = new RunSystemCommand();
       
        //Example system commands
        //obj.runCommand("cmd /c copy c:\\java\\Test.java d:\\data");
        //obj.runCommand("javac");   
       
        obj.runCommand("cmd /c dir");

    }

}


Output


Friday, August 13, 2010

Add google map to your Website/Blog in 2 steps

Many time you need to embed google map in your website or blogs, you can do simple way in just two steps.

1. Go to google map, choose your desire location. Click on Link and get the HTML code.





























2. Add the given code in your page.


Here is the output, as show below


View Larger Map