Thursday, September 11, 2008

How to write, compile and execute JAVA servlets

Servlets are core java programs that can be executed on the webserver upon the request via the url.

Prerequests for running a java servlet:

1. install JRE (Java Runtime Environment)

1.1 Download the JRE installation pack. Click here to download
1.2 Install the pack as per instructions.
1.3 Set the Environment Variable, JRE_HOME to the installed location.

1.3.1 Steps to set the Environment Variable in Windows XP/Vista MyComputer-> Properties -> ADVANCED tab . Click the "Environment Variables" button. Add a new System Variable:
Variable name: JRE_HOME
Variable value: C:\Program Files\Java\jre1.5.0_01\
(or ur insalled location)

1.4 You have done with installing JRE

2. Install apache-tomcat.

2.1 Download a binary distribution of Tomcat from:
2.2 Unpack the binary distribution into a convenient location so that the distribution resides in its own directory (conventionally named "apache-tomcat-[version]").

3. Include the servlet-api.jar to the CLASSPATH environment varialbe.
servlet-api.jar is not contained in JDK. It comes along with the apache-tomcat server. It is located "lib" folder of Tomcat installation direcotry.

eg: set classpath=C:\apache-tomcat-6.0.14\lib\servlet-api.jar;%classpath%

4. Start the ApacheTomcat server(startup.bat inside bin folder).

5. Now your server is ready and running.

Writing a Sample Java Servlet ::

Java servlets are no different from normal java programs. The servlet file is of .java extension. It uses javax.servlet package.

A sample and simple java servlet example :

import javax.servlet.*;
import javax.servlet.http.*;

public class myExample extends HttpServlet {

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

PrintWriter out = response.getWriter();
out.println("< HTML > \n" +
"< HEAD > < TITLE > Servlet Example from </TITLE > < /HEAD >\n" +
"< BODY >\n" );

out.println( "<H1> Servlet Example < /H1 >\n" + " A simple Servlet..
<br/><br/><br/>Thought for the day: You never get a second chance to make the first impression.
</BODY></HTML >");


public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);


How to run the servlet :

step 1: Compile the file using javac compiler just like anyother java file is compiled.

Step 2: Move the .class file to $java_installation_directory\webapps\ROOT\WEB-INF\classes\
If any directory is not found in the path, create it.

Step 3: Open the web.xml file in
if it does not exist, create it. We use this file to map the servlet. It is must

Step 4: its content should look like this:

< ?xml version="1.0" encoding="ISO-8859-1"? >

<web-app xmlns=""

 <display-name >Welcome to Tomcat </display-name >
<description >
     Welcome to Tomcat
</description >

<servlet >
<servlet-name >HelloWWW </servlet-name >
<servlet-class >HelloWWW </servlet-class >
</servlet >
<servlet-mapping >
<servlet-name >HelloWWW </servlet-name >
<url-pattern >/servlet/HelloWWW </url-pattern >
</servlet-mapping >

</web-app >

Step 5: Run the servlet using the browser. Type http://localhost:8080/servlet/myExample in the adress bar.

Step 6: Enjooyyy...>!!!!

Note: You can use servlets to receive form-data as POST and GET. Do a google search on it and you will find it. Feeling too lazy to write that too here... check back late.. i might have posted it.

Sunday, September 7, 2008

Image Processing using Java Media FrameWork (JMF))

Image processing using java is very simple. With the use of Java MediaFrameWork, image processing is just a matter of calling functions to get the job done .. !!

Here i will discuss in detail how image processing can be done in a real world scenario...step wise..

1. JDK 1.4 Download
2. Java Media Framework(JMF) Download
3. A PC :P

Step1: Capture the image.

Image to be processed can be obtained from the real world using camera or a stored image can be used. But usually image processing is a Real World Application. So we need to get the images 'LIVE'. .. now that is simple...

this is the code to capture an image using cam(inbuilt or usb)..

class captureImage
public static void main()
CaptureDeviceInfo deviceInfo = CaptureDeviceManager.getDevice("vfw:Microsoft WDM Image Capture (Win32):0");
Player player = Manager.createRealizedPlayer(deviceInfo.getLocator());
// Wait a few seconds for camera to initialise (otherwise img==null)
System.out.println("Capturing Image...");
// Grab a frame from the capture device
FrameGrabbingControl frameGrabber = (FrameGrabbingControl)player.getControl("");
Buffer buf = frameGrabber.grabFrame();
// Convert frame to an buffered image so it can be processed and saved
Image img = (new BufferToImage((VideoFormat)buf.getFormat()).createImage(buf));
BufferedImage buffImg = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
g.drawImage(img, null, null);

// Save image to disk as JPG
ImageIO.write(buffImg, "jpg", new File("C:\\cam.jpg"));



Now you have the image saved on to your hard disk at the location "c:\" with name cam.jpg.


Step 2: Processing the image:

By processing, i mean. Obtain the values of each pixels. Once that is done, then you can play with the pixel values and obtain fabulous results...

class imageProcessor extends Frame
Image rawImg;
int imgCols;//Number of horizontal pixels
int imgRows;//Number of rows of pixels
Image modImg;//Reference to modified image

//Inset values for the Frame
int inTop;
int inLeft;
static String theProcessingClass = "iMAGE pROCESSOR";

Static String theImgFile = "cam.jpg";

MediaTracker tracker;
int[][][] threeDPix;
int[][][] threeDPixMod;
int[] oneDPix;

ImgIntfc02 imageProcessingObject;

public static void main()
rawImg = Toolkit.getDefaultToolkit().getImage(theImgFile);
tracker = new MediaTracker(this);

System.out.println("Load error.");
}//end if
catch(InterruptedException e)
}//end catch

if((tracker.statusAll(false) & MediaTracker.ERRORED & MediaTracker.ABORTED) != 0)
System.out.println("Load errored or aborted");
}//end if

imgCols = rawImg.getWidth(this);
imgRows = rawImg.getHeight(this);
oneDPix = new int[imgCols * imgRows];

PixelGrabber pgObj = new PixelGrabber(rawImg,0,0,imgCols,imgRows,oneDPix,0,imgCols);
if(pgObj.grabPixels() && ((pgObj.getStatus() & ImageObserver.ALLBITS)!= 0))
threeDPix = convertToThreeDim(oneDPix,imgCols,imgRows);

//end if statement on grabPixels
System.out.println("Pixel grab not successful");
catch(InterruptedException e)
}//end catch

return 1;
} //end of run.

int[][][] convertToThreeDim(int[] oneDPix,int imgCols,int imgRows)
//Create the new 3D array to be populated
// with color data.
int[][][] data = new int[imgRows][imgCols][4];

for(int row = 0;row < arow =" new" col =" 0;" element =" row" col =" 0;col">> 24) & 0xFF;
//Red data
data[row][col][1] = (aRow[col] >> 16) & 0xFF;
//Green data
data[row][col][2] = (aRow[col] >> 8) & 0xFF;
//Blue data
data[row][col][3] = (aRow[col]) & 0xFF;
}//end for loop on col

}//end for loop on row
return data;
}//end convertToThreeDim

int[] convertToOneDim(int[][][] data,int imgCols,int imgRows)
int[] oneDPix = new int[imgCols * imgRows * 4];

for(int row = 0,cnt = 0;row < col =" 0;col">

The threeDPix array contain the pixel values. Explore the array and have fun.. Do post back your success stories..

Saturday, September 6, 2008

My First Post...

Hiiiiiiiiiiiii All..... Welcome to my first BLog..!! 
Usually peaple start with blog and move towards owning website.. 
but in my case, its other way round.. :D
Check out some of my websites:
My Personal Webiste:
Others: , , .............................

Oops .. i have named this as My Tech Experiments.. .. So some techie news.. 
something which i learnt some time back.. 

TRACE ROOT (tracert) command in windows. 

Syntax: tracert hostname

It actually returns the way you reach the given host name. When you request for a webpage, the data flows through .. or hops through many servers.. meaning there are many intermediate servers while you are communicating with a server via internet. Lesser the number of hops, more reachable is your server. 

eg: C:\> tracert

Output will look something like this : 

Microsoft Windows [Version 6.0.6000]
Copyright (c) 2006 Microsoft Corporation.  All rights reserved.


Tracing route to []
over a maximum of 30 hops:

  1    14 ms    14 ms    15 ms
  2     *        *        *     Request timed out.
  3     *        *       57 ms
  4   106 ms   106 ms   107 ms
  5   166 ms   167 ms   165 ms
  6   206 ms     *        * [
  7   158 ms   158 ms   159 ms
  8   221 ms   221 ms   221 ms
  9   305 ms   303 ms   317 ms
 10   349 ms   349 ms   349 ms
 11   323 ms   322 ms   334 ms
 12   362 ms   362 ms   359 ms
 13   333 ms   337 ms   335 ms
 14   353 ms   353 ms   353 ms
 15   353 ms   369 ms   365 ms
 16   356 ms   357 ms   355 ms []

Trace complete.