Saturday, December 27, 2008

how to create user defined Objects in Javascript

I am really a fan of javascript as it is quite easy as well as complex. 
Here is the example of how to create objects in javascript i.e. User defined objects which is very usefull in handling large amount of data from the inout forms controls quite nicely.






How to retrieve System Properties in Java

Here is the example of retrieving the System Properties through Java Code. In this program I have retrieved and displayed few System Properties.

The primary method which actually retrieves the property is System.getProperty(), and it takes key info as a parameter.

For details of all the System Properties and how it can be retrieved, you can visit my earlier post about
How to retrieve System Properties through Java. You can generate the XML file of all the key-value pair of the properties and then you can use any if the key's from the XML file, in the below program to get the info in Java Code.

RetrieveSystemProperties.java
----------------------------

public class RetrieveSystemProperties
{

/*
File : RetrieveSystemProperties.java
Purpose: Retrieves and displays the System Property details
Author : Anaparthi Subrahmanyam
Published: 2008-12-27
Usage Notification: Author doesnt own responsibility of any loss of data,
responsibility for misuse or loss of any nature if this code is used. If possible,
please provide link to this webpage
*/
public static void main(String[] args)
{
try
{
/*
the below functions will retrieve the System Properties of the System
*/

// retrieving Operating System Name of the machine
System.out.println("Operating System Info: "+System.getProperty ("os.name"));

// retrieving Unicode Encoding
System.out.println("Unicode Encoding Info: "+System.getProperty ("sun.io.unicode.encoding"));

// retrieving User Language
System.out.println("Operating System Info: "+System.getProperty ("user.language"));

// retrieving Operating System Name of the machine
System.out.println("User Language Info: "+System.getProperty ("sun.management.compiler"));

// retrieving Desktop Information
System.out.println("Desktop Info: "+System.getProperty ("sun.desktop"));

// retrieving Sun Compiler name
System.out.println("Sun Compiler Info: "+System.getProperty ("sun.management.compiler"));

// retrieving Operating System patch level
System.out.println("Patch Info: "+System.getProperty ("sun.os.patch.level"));

// retrieving File encoding package
System.out.println("File encoding package Info: "+System.getProperty ("file.encoding.pkg"));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
----------------------------

Please provide your comments, i will really appreciate it.

How do I retrieve the System Properties on Windows Machine using Java

There are different ways to get the System properties of a System or Machine using Java Program. 
The following code first create a file called SystemProperties.xml and then retrieves all the System Property using Java's own function called getProperties() of Properties class and finally dumps it to the the created XML File.

SystemProperties.java
--------------------------------------------
import java.util.Properties;
import java.io.PrintStream;
import java.io.File;

/*
  File   : SystemProperties.java
  Purpose: Dumps all the System Properties and values to a XML file
  Author : Anaparthi Subrahmanyam 
  Published: 2008-12-27
  Usage Notification: Author doesnt own responsibility of any loss of data, responsibility for misuse or loss of any nature if this      code is used. If possible, please provide link to this webpage
*/

public class SystemProperties 
{
  public static void main(String[] args) 
  {
    try
    {
       File f = new File("SystemProperties.xml");
       //if creating a file called SystemProperties.xml, if returns false, exception will be thrown
       if(!f.createNewFile())
       {
          throw new Exception("Exception encoutered may be due to the file already exist.");
       }
       Properties prop = System.getProperties();
       // opening file in print stream so that later this stream will be used to write 
       PrintStream pst = new PrintStream(f.getName());
       // Passing three parameters to the storeToXML.
       //1. printstream
       //2. Comment to the XML File 
       //3. encoding format
       prop.storeToXML(pst,"System Properties details", "UTF-8");
       System.out.println("Sucessfully dumped the System Details to the file: " +f.getName());
    }
    catch (Exception e)
    {
      System.out.println("Error: "+e.getMessage());
    }
   }
}
-----------------------
Please provide your comments.

If you like this content please provide a link of this page on your page.


Friday, December 26, 2008

Details about installing java on different Operating Systems

Sun Microsystems has provided a very nice page providing all the details about steps and links for How to Install Java and also provided  links of different JDK’s for various operating systems.

 Here is the Link : http://www.java.com/en/download/manual.jsp

How do i verify whether an URL is active or not through Java

There are different ways in java through which we can verify whether any specific URL is active or not.
Here is the Java Program which displays success message if the URL is active and Failed message if URL is not active/dead.

URLVerification 
----------------
import java.net.*;
import java.io.*;

public class URLVerification {
    public static void main(String[] args) throws Exception {
        URL url_to_verify = new URL("http://www.google.com");
        try
        {
          URLConnection connObj = url_to_verify.openConnection();
          connObj .connect();
          InputStream stream_to_recieve_data = connObj .getInputStream();
          stream_to_recieve_data.close();  
          System.out.println("Successful in establishing connection.");
        }
        catch (Exception e)
        {
          System.out.println("Failed in establishing connection.");
        }
    }
}
-------------------
I also want to share the few scenarios where we can use this such as:

1. You have to write a code which will call a specific URL to get data after each interval
2. Before Sending request , you can write a filter to verify whether the url is active or not.
3. Directly you want to call a servlet/jsp through a java program to get the status 

I hope my above comments will help you to come up with new ideas as well.

Please provide comments if any...

Thursday, December 25, 2008

How do I pass numeric value as command line argument to Java

Here is the example to pass numeric value as a command line argument is Java Class.

CommandLineNumExample.java
---------------------------------
public class  CommandLineNumExample
{
  public static void main(String[] args) 
  {
    int i = Integer.parseInt(args[0]);
    double d = Double.parseDouble(args[0]);
    // multiplying the value of i i.e command line argument with 2
    System.out.println("The Argument Number Value is  "+ (i*2)); 

    // multiplying the value of i i.e command line argument with 3
    // you can see a decimal value also as the argument is converted to double
    System.out.println("The Argument Double Value is  "+ (d*3));
  }
}
---------------------------------
Please read my previous example on How to pass Command Line Arguments in Java to get details about CommandLine arguments and how to pass arguments thru command line

The output will be 
---------------------
The Argument Number Value is  44
The Argument Double Value is  66.0
---------------------

For your help, i am providing the commands in sequence:
Note: 22 in the below command is the argument
----------------------------
C:\Temp>javac CommandLineNumExample.java

C:\Temp>java CommandLineNumExample 22
The Argument Number Value is  44
The Argument Double Value is  66.0
----------------------------

If you any comments or suggestion, please provide.

How do i pass command line arguments in Java

Here is the example of how to pass command line arguments to a java file.
In the below example, one argument will be passed with the java command, and later within the the progrm it is retrieved as a String. 
Few other details, whenever we execute a java command, the main method is called, and in the below example you can see a main method defined and accepts array of String as parameters.
This means, whenever we pass any command line parameter, it is accpetd with this main method, and  "String s1 = args[0];", this line retrieves the value from the arguments passed to main method. We need to remember here one thing particularly, i.e. if we are passing one argument then we can retrieve only one otherwise if any mismatch occurs, then it will throw an exception as ArrayIndexOutOfBound exception.

CommandLineExample.java
-----------------------------

public class  CommandLineExample
{
  public static void main(String[] args) 
  {
    String s1 = args[0];
    System.out.println("Hello..  "+ s1);
  }
}
------------------------------
The above file is meant to recieve only one argument as command line argument.

How to execute and pass the command line argument, please follow the below instruction:
1. Open Command Prompt.
2. Go to the folder location where you have saved the above file as CommandLineExample.java.
3. Compile the Java file CommandLineExample.java
4. Once compilation is successfull, its turn for running the code..
5. Provide command as java CommandLineExample John and press enter
6. You can see a extra text is added other then java command and file name i.e. John, this is the string argument which i am passing to the CommandLineExample's main method.
Note: You can pass more then one number of arguments also. Whenever it is passed to the main method, all the arguments type are considered as String type. If you want to pass some numeric value then , you need to type cast it within the java code, and can use based on your requirement which is again a quite easy process.
6. You will se a message as Hello..  John

For extra help, i am providing the commandline texts here:
---------------------------------------------
--comment : below line will compile the file
C:\Temp>javac CommandLineExample.java
--comment : below line will execute the file, taking the last text i.e. John as command line argument
C:\Temp>java CommandLineExample John
Hello..  John
----------------------------------------------

Please provide you comments if any...

Wednesday, December 24, 2008

How to do I sum and print two numbers in Java Program

Here is the sample program , which will print two number sum in different ways:

public class  SumNumbers
{
  /*
    Create a java file as SumNumbers.java
    Save this code in it.
  */
  public static void main(String[] args) 
  {
    /* defining two variables.
      1. int x
      2. int y
      Variable x and y are prefixed by keyword called int.
      'int' means integer datatype can contain any integer non decimal value.
    */
    int x = 10;
    int y = 20;
    // Different ways we can print the sum value as mentioned below.
    int sum = x+ y;
    System.out.println(" Sum of two numbers : Style 1 : "+sum);
    System.out.println(" Sum of two numbers : Style 2 : "+(x+y));
    System.out.println(" Sum of two numbers "+x+" and "+y+" is : Style 3 : "+(x+y)); 
  }
}
Output will be:
-----------------------
Sum of two numbers : Style 1 : 30
Sum of two numbers : Style 2 : 30
Sum of two numbers 10 and 20 is : Style 3 : 30

Tuesday, December 23, 2008

Storing java command output to text file.

Its quite simple to store Java command output of the console window of MS Windows i.e command prompt to store in a text file. The need for this is when we have huge text as an output on executing a java program, sometimes we face problem in searching specific text.
The command is:
commandprompt>java GenerateLog >> UserFile.txt

here in the above example, java GenerateLog is the command to execute GenerateLog java file, and output will be dislayed on the console. But by providing the ">> UserFile.txt" at the end of it , the output will be directed to the file called UserFile.txt

By using the above command, a text file named UserFile will be stored in most probably c drive or in the current location
You can easily find this file.

Comment will be highly appreciated...

How do I configure User tools in editplus to compile and run java file

I would like to demonstrate how easy it is to configure java environment in editplus.

1.Open your installed editplus editor
2.Go to Menu -> Tools -> Configure User Tools
3. A Preferrences titled window will be opened on your desktop.
4.Find Add Tools button under the section Groups and tools item: section on the right side of the window.
5. Click the button Add Tools -> Program
6. It will create an item as New Program in the List.
7. Below the list you will find few input boxes such as menu, command, argument etc.
8. Fille those with following details
Menu Text: CompileJava
(Note: Here i am creating a user tool which will compile the java program written in edit plus without going to the command prompt and compiling manually)
Command: %JavaInstalledDir%\jdk1.5.0_14\bin\javac.exe
(Note: %JavaInstalledDir% means the location where you have installed Java. for example c:\jdk1..5\bin\javac.exe, so write c:\jdk1..5\bin\javac.exe in command inout box.Dont copy paste %Installed......... content. Please verify wether javac.exe file is available in the given location)
Arguments: $(FileDir)\$(FileName)
(Note: place the above content as it is)
9. Select the capture output window check box.
10.Click Apply and Ok.
11. A CompileJava item will be added under the menu of editplus i.e. Menu -> Tools -> CompileJava
12. Now its very simple to compile the Java file. Open editplus , create a simple java file having no user defined import packages, save it to whichever location you want.Keep the file opened on the editor and go to the itemCompileJava which you have created in step 11. Click it.
It will create a small partition in lower half of editplus and will show the message as
Output Completed.. .. Normal Termination.
13. A class file will be created in the same location where you have placed the file.

How to Configure User Tool for executing the Java Class file in Edit plus.
14. Follow the steps from 2 to 7.
15. The input parameters as
Menu Text: ExecuteJava
Command: %JavaInstalledDir%\jdk1.5.0_14\bin\java.exe
(Note: Follow the note in the above sections, written for Arguments input box value.)
Arguments: -classpath $(FileDir) $(FileNameNoExt)
(Copy paste as it is)
16. Follow steps 9-10.
17. Verify the new tool item as ExecuteJava in your edit plus editor
17. Use steps 12-13 to create a java class file using editplus editor , and the click ExecuteJava item in Menu -> Tools > ExecuteJava , created by you to run/execute it.
You can see the output in the lower half of the editplus editor.
I hope, i am able to help you in setting up Java environment in Edit Plus.

For your convenience, i have added the image of the user configuration tool settings of Edit Plus below:



Note: View the image by increasing the view size of your browser
Your comments will be higly appreciated..

First Java Program Example

Hello All,

The Java prorgam looks like as follows:

HelloWorld.java
-----------------
public class HelloWorld
{
public static void main(String [] args)
{
System.out.println(" Hi. to all");
}
}
--------------------
Things to note:
1. Java file name must be same as the class name (in above example its HelloWorld) which is defined as public and having main method. This is in case of a stand alone program where you are trying to execute the first program in Java.
2. The Parameter passed in main method i.e. String [] args, is actually the referring to the arguments provided while calling the main method through the console command.

How to Compile & Run.
------------

1. Create a folder such as c:\JavaWorks
2. Save the above file withing the newly create folder with the name as HelloWorld.java
3. go to your start menu, click on run
4. enter text cmd and press enter. It will open up a command prompt.
5. go to the folder location in the console i.e your command prompt should be pointing to c:\JavaWorks
6. Verify Java Development Kit is already installed in your machine. for more details please refer to my earlier article on how to install java on my machine.
7. After installation verification, enter javac HelloWorld.java command console and press enter.
8. By pressing enter , a class file with the name HelloWorld.class will be created in the same folder, where you have placed the Java file.This class file is the compiled code which will be actually executed.
9.Verify, if any error message shown on the prompt, if compiled successfully it will show the prompt again without any message.
10. Now to execute the class file which you have generated in step 8, enter java HelloWorld on your command prompt , where you have compiled you java file, and press enter key.
11. It will show you a message as "Hi. to all" .
12. For your help, i am copy pasting the commands on the console here in sequence.:

==========================
C:\JavaWork>javac HelloWorld.java

C:\JavaWork>java HelloWorld
Hi. to all

C:\JavaWork>
==========================

If you have face any issue, drop a comment here.

Thursday, December 18, 2008

Example to setup first JMX MBean in WebSphere Application Server

I struggled very hard to land on this page. I am using WAS 6.1, and on the net, its quite difficult to get documentation on 6.1, But on WAS 5.1 , good amount of documentation is available. One of the documentation from WAS 5.1 I used to setup JMX MBeanServer as well configuring MBean on WAS 6.1, and i was able to do it successfull.

Sharing with you all for your help, the link which provides details of setting up JMX with the examples.

http://www.ibm.com/developerworks/websphere/techjournal/0304_williamson/williamson.html

How to set Java Path to run Java Program

Please read my earlier post about How to install Java before setting the Java Path to compile java file.

Once you are done with Java Installation,Right click on the My Computer Icon of your desktop or if you dont have My Computer icon on your desktop then right click on the My Computer in File Explorer.

-> Select the Properties Item

-> Select the Advanced Tab

-> Click Envirnment Variables Button

-> Find path under System Variable section, select it and click edit button

-> It will open a pop up window , append %Java Installation Dir%\bin (make sure that before adding this value, you are placing a semicolon (;) and then appending the value. Semi colon is used as a separator between two different location in the Path Variable.) at the end in the Value field.

Note : %Java Installation Dir% means the folder where you have installed the java,but the path you have given upto bin folder under installed folder as it contains javac.exe (java compiler) and java.exe (executs Java )

Save your changes.

How to verify:

1.Open a command prompt

2. type java -version and press enter

if you are able to see some text on command prompt as

java version "1.5.0_14"

Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_14-b03)

Java HotSpot(TM) Client VM (build 1.5.0_14-b03, mixed mode, sharing)

Means Java is installed properly and your pc environment path is set to compile and run a java program.

If you are unable to get the above mentioned text, please verify whether you set the Environment variable properly as well as check the location you provided.

I hope it will help you to understand how to set path in computer to run java program.

How to install Java on my machine

Before running any Java program you need to have the Java installed on your machine. Normally beginners gets confused with different terminologies used in Java such as jdk,j2se,jre,jvm etc..

JDK - Java Development Kit/ J2SE( Java 2 Standard Edition)

JRE - Java Runtime Envrionment

JVM - Java Virtual Machine

All the above three are different , but if you install JDK, you will get JRE and JVM, if you install JRE , you will get JVM by defualt.

I tried to clear the concept so that before installing it may be bit less troublesome while installing Java for the first time.

About installing.. If you are installing Java on your machine for the purpose of writing code then you have to install the Java Development kit (jdk) , latest version will be good.

You can download JDK(1.5) from this location :

http://java.sun.com/javase/downloads/index_jdk5.jsp

After downloading , just double click on the exe file, which you have downloaded .

It will ask for the location where to install the software( by default it takes C:\Program Files), its upto your choice where you want to install it.I normally install in a separate folder as some times during the path setup on my machine , i was forced to modify the folder name C:\Program FIles to C:\Progra~1 as due to space in the folder name, PC unable to find the installed location.

Thats it.. wait till the installation is complete.