• Entries (RSS)
  • Comments (RSS)

Java and HTTP Proxy Settings

Posted by | Posted in Java | Posted on 29-11-2007

Tagged Under : ,

How to connect to internet from Java program through a proxy? The answer is very simple Just add the following arguments to the virtual machine

    java -Dhttp.proxyHost=hostname -Dhttp.proxyPort=port -Dhttp.proxyUser=username  -Dhttp.proxyPassword=passowrd

or just put set these System properties using the code.

   System.getProperties().put("http.proxyHost", "hostname");
   System.getProperties().put("http.proxyPort", "port");
   System.getProperties().put("http.proxyUser", "username");
   System.getProperties().put("http.proxyPassword", "password");

If your proxy doesn’t require an authentication, you just need to set proxyHost and proxyPort properties only.

But the fist method wouldn’t work if we are running our program from within Eclipse as we don’t have command line access. So to set the proxy properties in Eclipse just go to Run menu and click on Run. A dialog box would appear and in the first tab (Main tab) enter your main class and other information and in the Arguments tab under VM arguments just add the following line.

   -Dhttp.proxyHost=hostnmae -Dhttp.proxyPort=port

Polymorphism in Java

Posted by | Posted in Java | Posted on 22-10-2007

Tagged Under : ,

Polymorphism refers to the ability of an object to behave differently to the same message.

Polymorphism is of two types. static or dynamic. In dynamic polymorphism the response to message is decided on run-time while in static polymorphism it is decided out of run-time (i.e. on compile-time).

The assignment of data types in dynamic polymorphism is known as late or dynamic binding. In dynamic binding method call occur based on the object (instance) type at Run time. Eg: method overriding

If the assignment of data types is in compile time it is known as early or static binding. In static binding method call occur based on the reference type at compile time. Eg: method overloading

Method Overloading

Method overloading means creating a new method with the same name and different signature. It uses early binding.

Method Overriding

Method overriding is the process of giving a new definition for an existing method in its child class. All object created at run time on the heap therefore actual binding is done at the runtime only

Play WAV files using Java

Posted by | Posted in Java | Posted on 20-10-2007

Tagged Under : ,

The following Java code plays a .wav file

import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
 
public class MusicPlayer {
 public static void main(String args[]) {
    try {
         AudioInputStream stream =
                  AudioSystem.getAudioInputStream(
                    new File("C:\\i386\\Blip.wav"));
 
 	AudioFormat format = stream.getFormat();
        DataLine.Info info =
                  new DataLine.Info(Clip.class,
                          stream.getFormat());
        Clip clip = (Clip) AudioSystem.getLine(info);
 
        clip.open(stream);
        clip.start();
 
      } catch (Exception e) {
           e.printStackTrace();
      }
   }
 
}

Parsing XML String using DOM

Posted by | Posted in Java | Posted on 09-10-2007

Tagged Under : , ,

The first step in parsing an XML String using DOM is to get the org.w3c.dom.Document object from our String object. Here I am going to parse the following XML which is stored in a String variable xmlString

<data>
   <address>
          <name>Tom</name>
          <city>Bangalore</city>
    </address>
   <address>
        <name>Chris</name>
        <city>New Jersey</city>
   </address>
</data>

First lets create a Document object using xmlString object.

    javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    javax.xml.parsers.DocumentBuilder db = factory.newDocumentBuilder();
    org.xml.sax.InputSource inStream = new org.xml.sax.InputSource();
 
    inStream.setCharacterStream(new java.io.StringReader(xmlString));
    org.xml.sax.Document doc = db.parse(inStream);

Once we got the Document object we need to get the NodeList from our Document object.

org.w3c.dom.NodeList nodeList = doc.getElementsByTagName("address");

This would return all the address elements available in our XML. Next we need to loop through all the nodes in our NodeList and get the nodes present.

for(int index=0; index < nodeList.getLength(); index++) {
      org.w3c.dom.Node node = nodeList.item(index);
}

Once we got the Node we need to cast it to an org.w3c.dom.Element object if the Node is of type org.w3c.dom.Element

if (node.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
      org.w3c.dom.Element element = (org.w3c.dom.Element) node;
}

Now we need to find out all the names that is coming under the current address.

 
org.w3c.dom.NodeList nameNode = element.getElementsByTagName("name");

Now we need to do all the above exercise again to get the final element from where we can get the value.

for(int iIndex=0; iIndex< nameNode.getLength(); iIndex++) {
    if (nameNode.item(iIndex).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
         org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nameNode.item(iIndex);
         System.out.println("Name = " +nameElement.getFirstChild().getNodeValue().trim());
     }
}

So the complete code is

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xmlString));
Document doc = db.parse(inStream);	
 
NodeList nodeList = doc.getElementsByTagName("address");
 
for(int index=0; index < nodeList.getLength(); index++)
{
        Node node = nodeList.item(index);
 
	if (node.getNodeType() == Node.ELEMENT_NODE)
	{
	        Element element = (Element) node;
 
		NodeList nameNode = element.getElementsByTagName("name");
 
		for(int iIndex=0; iIndex< nameNode.getLength(); iIndex++)
		{
		        if (nameNode.item(iIndex).getNodeType() ==Node.ELEMENT_NODE)
			{
				Element nameElement = (Element) nameNode.item(iIndex);
				System.out.println("Name = " +nameElement.getFirstChild().getNodeValue().trim());
			}
	        }
        }
}

StringTokenizer replacement

Posted by | Posted in Java | Posted on 07-10-2007

Tagged Under :

The StringTokenizer class in java.util package has been deprecated as of Java 1.4. Sun recommends the use of String.split method instead of java.util.StringTokenizer class.

For eg:

StringTokenizer strTokens = new StringTokenizer("Token String");
 
   while (strTokens.hasMoreTokens())  {
             System.out.println(strTokens.nextToken());
   }

Can be replaces with the following code.

    String[] splittedSting = "Token Sting".split("\\s");
   for (int x=0; x&lt;splittedSting.length; x++) {
       System.out.println(splittedSting[x]);
    }