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
1.3.1.1 MyComputer-> Properties -> ADVANCED tab .
1.3.1.2 Click the "Environment Variables" button.
1.3.1.3 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: http://tomcat.apache.org
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 java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class myExample extends HttpServlet {

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

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("< HTML > \n" +
"< HEAD > < TITLE > Servlet Example from My-Tech-Experiments.blogspot.com </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 servletName.java 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
$java_installation_directory\webapps\ROOT\WEB-INF\
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="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5">

 <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..

Requirements:
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)..

captureImage.java
-----------------


class captureImage
{
public static void main()
{
CaptureDeviceInfo deviceInfo = CaptureDeviceManager.getDevice("vfw:Microsoft WDM Image Capture (Win32):0");
Player player = Manager.createRealizedPlayer(deviceInfo.getLocator());
player.start();
// Wait a few seconds for camera to initialise (otherwise img==null)
System.out.println("Capturing Image...");
Thread.sleep(2500);
// Grab a frame from the capture device
FrameGrabbingControl frameGrabber = (FrameGrabbingControl)player.getControl("javax.media.control.FrameGrabbingControl");
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"));


player.close();
player.deallocate();

}
}



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...


imageProcessor.java
-------------------

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);
tracker.addImage(rawImg,1);

try
{
if(!tracker.waitForID(1,10000))
{
System.out.println("Load error.");
System.exit(1);
}//end if
}
catch(InterruptedException e)
{
e.printStackTrace();
System.exit(1);
}//end catch

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

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

try
{
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
else
System.out.println("Pixel grab not successful");
}
catch(InterruptedException e)
{
e.printStackTrace();
}//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: www.jaismathews.com
Others: www.basicneeds.co.cc , wwww.usearch.co.cc , .............................

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 google.com

Output will look something like this : 

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

C:\>tracert google.com

Tracing route to google.com [64.233.167.99]
over a maximum of 30 hops:

  1    14 ms    14 ms    15 ms  59.93.39.1
  2     *        *        *     Request timed out.
  3     *        *       57 ms  218.248.255.90
  4   106 ms   106 ms   107 ms  202.54.185.230
  5   166 ms   167 ms   165 ms  172.31.39.66
  6   206 ms     *        *     59.163.234.254.static.vsnl.net.in [59.163.234.25
4]
  7   158 ms   158 ms   159 ms  64.233.175.207
  8   221 ms   221 ms   221 ms  209.85.252.105
  9   305 ms   303 ms   317 ms  209.85.248.131
 10   349 ms   349 ms   349 ms  209.85.248.128
 11   323 ms   322 ms   334 ms  209.85.243.116
 12   362 ms   362 ms   359 ms  209.85.241.20
 13   333 ms   337 ms   335 ms  209.85.241.23
 14   353 ms   353 ms   353 ms  66.249.94.134
 15   353 ms   369 ms   365 ms  64.233.175.42
 16   356 ms   357 ms   355 ms  py-in-f99.google.com [64.233.167.99]

Trace complete.

C:\>