Saturday, January 31, 2009

Servlet Filters

This blog intends to answer the following questions :-
  1. What is a Filter?
  2. Why should I use filters in my web application?
  3. How do I use Filters in a web application?
Here is what I have :-
  1. An local installation of tomcat that listens on port number 8080.
  2. A web application called FilterApplicationExample placed in the tomcat-installation-directory/webapps.
  3. The directory structure of every web-application in java should have a format. If you are unaware of the format, please refer to my other posts.
  4. Now I create a java file - MyFilter.java in the WEB-INF/src/examples directory.
  5. This file would house the code that would be executed as a filter for this application.
  6. I also create a Servlet named - 'MyServlet.java' in the WEB-INF/src/examples directory.
  7. This file will house the code for the the servlet that is actually requested by the client.
  8. I also have a file - 'web.xml' in the WEB-INF directory that houses the code that will be used to associate my Filter with the Servlet.
Here is the explanation :-

First and foremost lets know something about a filter. I believe everyone of us has seen a basic water filter. What does it do? Of course, it filters water so that we get pure and clean dringking water so that we can stay healthy. Similarly, when web applications were created, the developers presumably chose to use the same concept for web applications as well.

Just as in a normal water filter, a Filter in a web application in a piece of code that is supposed to execute when a client requests for a particular web resource. For example, in this application, the client will request for a servlet file, but before the code in the servlet file is executed, the code in the Filter will execute without the client being aware of this fact.

So, why do we use filters? Well, filters are intended to do important pre-processing of client requests. What kind of pre-processing? Well, normally, when we talk about pre-processing, we mean performing certain basic tasks that are not directly related to the client request. For example logging, authentication, authorization, encryption - decryption, data compression etc.

All these tasks are supposed to run without the client requesting for them directly. We also notice an important feature about these pre-processing tasks. Most of them will be required for a large number of resources in a web-application. For example, i may have 3 servlets in my application whcih may require encryption to be done. Since this is a common task, I can use an encryption filter in my web application and assiciate these servelts with the encryption filter. The advantage that i gain by doing this is that that encryption code that is common to all these three filters does not become redundant in the three servlets. MoreOver, if i later on need to extend my application, and have more servlets require the encryption filter, all that I have to do is to associate the new servlet with the filter thereby reducing development effort and time. Over and above, if the encryption algorithm need to be changed, then io need to make changes in only a single location and it will be automatically be reflected in all the servlets associated with the encryption filter.

Filters are used in web-application declaratively. This means that I just tell the web application, through an xml file that I want to associate a particular filter with the given request-URL or a servlet. This mysterious xml file is the same old web.xml that we use all along.

Here is how I do it :-

MyFilter.java
//------Start Of Source Code------
package examples;

import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;

public class MyFilter implements Filter
{
FilterConfig fc;

public void init(FilterConfig fc) throws ServletException
{
this.fc=fc;
}

public void doFilter(ServletRequest req,ServletResponse resp,FilterChain chain) throws ServletException, IOException
{
HttpServletRequest hreq=(HttpServletRequest)req;
HttpServletResponse hresp=(HttpServletResponse)resp;

PrintWriter pw=hresp.getWriter();
hresp.setContentType("text/html");

pw.write("inside filter, before going to the servlet");

chain.doFilter(req,resp);

pw.write("inside filter, after returning from the servlet");

pw.flush();
pw.close();
}

public void destroy()
{
}
}
//------End Of Source Code------



MyServlet.java
//------Start Of Source Code------
package examples;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MyServlet extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException
{
PrintWriter pw=resp.getWriter();

pw.write("<br/>");
pw.write("inside the servlet");
pw.write("<br/>");

}
}

//------End Of Source Code------



web.xml
//------Start Of Source Code------
<web-app>
<servlet>
<servlet-name>SampleServlet</servlet-name>
<servlet-class>examples.MyServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SampleServlet</servlet-name>
<url-pattern>/go</url-pattern>
</servlet-mapping>

<filter>
<filter-name>SampleFilter</filter-name>
<filter-class>examples.MyFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>SampleFilter</filter-name>
<url-pattern>/go</url-pattern>
</filter-mapping>
</web-app>

//------End Of Source Code------


Compile the java files and copy the .class files obtained into the WEB-INF/classes/examples directory.
Now Start tomcat and type the following url in your address bar :-
http://localhost:8080/FilterExample/go
Now press the Enter/Return key.

You should get the following output :-
inside filter, before going to the servlet
inside the servlet
inside filter, after returning from the servlet

This is jsut a bare bones example do demonstrate how to use filters. Kindly ignore the malformed html. I have not followed any good programming practice just to keep the code as simple as possible and to focus on the problem at hand. Hope that you find this demonstration useful.

Happy Programming ;)

Signing Off
Ryan

Saturday, January 24, 2009

Updating JPanels

This blog post intends to answer the following questions.
  1. How to update a JPanel?
  2. How to dynamically change the contents of a JPanel based on user interaction?
Here is what I have :-
  1. A File called MainFrame.java that has a button labeled 'Click Me', and a panel called displayPanel.
  2. A file called Panel1.java that has a button labeled as 'Button1'.
  3. A file called Panel2.java that has a button labeled as 'Button2'.
Here is what I have done :-
  1. The constructor of my MainFrame class initializez the button 'Click Me' and initializes the displayPanel to Panel1.
  2. So now when i run the application i get 2 buttons on my screen - 'Click Me' and 'Button 1'.
  3. When the user clicks on the 'Click Me' Button, i intend to make the displayPanel refer to the Panel 2 and hence display the 'Button 2 on my MainFrame.
Here is how I do it :-

Panel1.java
//------Start of Source Code------
import javax.swing.*;
import java.awt.*;

public class Panel1 extends JPanel
{
JButton button1;

public Panel1()
{
this.setSize(250,250);
button1=new JButton("Button 1");
this.add(button1);
}

}
//------End Of Source Code------

Panel2.java
//------Start of Source Code------
import javax.swing.*;
import java.awt.*;

public class Panel2 extends JPanel
{
JButton button2;

public Panel2()
{
this.setSize(250,250);
button2=new JButton("Button 2");
this.add(button2);
}

}
//------End Of Source Code------

MainFrame.java
//------Start of Source Code------
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class MainFrame extends JFrame
{
JPanel displayPanel;
JButton myButton;

public MainFrame()
{
super("MainFrame");

myButton=new JButton("Click Me");
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
updateMainUI();
}
});

this.setSize(400,400);
this.addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e )
{
System.exit( 0 );
}
}
);

displayPanel=new Panel1();

Container c=getContentPane();
c.setLayout(new BorderLayout());
c.add(myButton,BorderLayout.NORTH);
c.add(displayPanel,BorderLayout.SOUTH);
this.setVisible(true);
}

public void updateMainUI()
{
this.getContentPane().remove(displayPanel);
displayPanel=new Panel2();
this.getContentPane().add(displayPanel,BorderLayout.SOUTH);
this.getContentPane().validate();
}

public static void main(String [] args)
{
MainFrame mf=new MainFrame();
}

}
//------End Of Source Code------

I wrote this piece of code after toiling for about 3 hours on the internet. At all the places where I searched, the people who had solved a similar problem, just explained the procedure of how they had done it. Nobody had posted any code for the solution(at least in the forums where i searched). For those of you who feel that I am bad at 'googling', I already know that i am bad at it (lolz).I sincerely hope that this piece of code comes in handy to anyone and everyone who stumbles upon it.

Happy Programming ;)

Signing off.
Ryan

Tuesday, January 20, 2009

A Random Integer Array

Here is a sample program that creates an array of a given size containing random values with the 'size' as the range.
The function 'createRandomArray' generates the random array.

RandomArray.java

//--------Start Of Source Code------
public class RandomArray
{
public static void main(String [] args)
{
int [] sample=createRandomArray(30);

for(int i=0;i<sample.length;i++)
{
System.out.println(sample[i]);
}

}

//This function performs all the randomization task
public static int[] createRandomArray(int size)
{
int [] randomArray=new int[size];

for(int i=0;i<size;i++)
{
randomArray[i]=i;
}

for(int i=0;i<size;i++)
{
int pos=(int)(size*Math.random());

int temp=randomArray[i];
randomArray[i]=randomArray[pos];
randomArray[pos]=temp;
}

return randomArray;
}

}
//------End Of Source Code-------

Happy Programming. ;)

Signing off.
Ryan

Saturday, January 10, 2009

Command Line Echo

The program in this blog answers the following questions:
  1. How to read input from the command line?
  2. How to echo data read from the command line?
  3. What wrapper must be used to read a line of input from the command line?

This simple program demonstrates the use of the java.io package to read command line data.

CommandLineReader.java

//--------Start of source code------

import java.io.*;

public class CommandLineReader
{
public static void main(String [] args)
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

try{
System.out.println(br.readLine());
}
catch(IOException ioex)
{
System.out.println("An IOException was thrown");
}
}
}

//--------End of source code-------

Compile this program using:
javac -cp . CommandLineReader.java

Run this program using:
java -classpath CommandLineReader

When you execute this program, you will be prompted to enter some text on the command line. Enter some text and see how it is echoed back to you on the command line itself.

Explanation:
What this program does is that it makes a new InputStreamReader that takes input from the command line(represented by System.in), because data from the command line is treated as an Input Stream. Now since my intention is to read one line at a time, i need to save each character entered by the user in a buffer. The BufferedReader class does this for me. Now when a complte line is entered(i.e. the usr presses the enter/return key), i retrieve this line from the BufferedReader and print it back on the command line.

Happy Programming ;)

Signing Off
Ryan

Tuesday, January 6, 2009

XML Friendly Pages

Now, this post was intended to solve a problem that i faced while blogging. As you see, i post code snippets in this blog. However, since my code can sometimes contain XML unfriendly characters like < and > so i had to find a way around it. Well, i tried using CDATA as well, but google just wont let me post. The savvy programmer that i am , i decided to make a simple and short program to find way around this.
What i did was that i made a program that would replace the above mentioned XML unfriendly characters from my source file into XML friendly ones.

This program takes an argument a file that needs to be converted.

The code goes as follows:

MakeXmlFriendly.java

//--------Start of source code----------------
import java.io.*;

public class MakeXmlFriendly
{
static File inputFile;
static File outputFile;
static StringBuffer inputFileBuffer;
static StringBuffer outputFileBuffer;


public static void main(String [] args) throws IOException
{
if(args!=null&& args.length>0)
{
inputFile=new File(args[0]);
outputFile= new File("XmlFriendly"+args[0]);

inputFileBuffer=new StringBuffer();
outputFileBuffer=new StringBuffer();

BufferedReader inputFileReader=new BufferedReader(new FileReader(args[0]));
BufferedWriter outputFileWriter =new BufferedWriter(new FileWriter(outputFile));

String separator=System.getProperty("line.separator");


String line=inputFileReader.readLine();
while(line!=null)
{
System.out.print(line);
outputFileBuffer.append(line);
outputFileBuffer.append(separator);
line=inputFileReader.readLine();
}


String replaceString=outputFileBuffer.toString();
System.out.print(replaceString);
replaceString=replaceString.replaceAll("<", "&lt;");
replaceString=replaceString.replaceAll(">", "&gt;");

outputFile.createNewFile();

outputFileWriter.write(replaceString);
outputFileWriter.flush();
outputFileWriter.close();
}
}
}

//--------End of source code---------------

With little more improvement, i suppose that it will come in quite handy.

Happy Programming ;)

Signing Off
Ryan

Sunday, January 4, 2009

A First AJAX Program

This post should be able to answer the following questions:
  1. How to create the simplest AJAX program?
  2. I need a simple AJAX template from where I can begin coding.
The code sample given below has been executed on Mozilla Firefox version 3.0.5 and uses Apache Tomcat 6.0 as the application server.

I make use of 2 files. Ajax1.html and data.txt. Both these files have been placed in a folder named 'myajax' in the 'webapps' directory of tomcat.

My first file is a simple html file that contains a small amount of javascript that does the magic trick for us. The second file contains the a few lines of text that is magically transferred using AJAX.


-------------------Start Of Sample Code--------------------
Ajax1.html

<html>
<head>
<script language="javascript">

var ajaxObj=false;

if(window.XMLHttpRequest)
{
ajaxObj=new XMLHttpRequest();
}

function magicByAjax()
{
var obj=document.getElementById('target1');
if(ajaxObj)
{
ajaxObj.open("GET","http://localhost:8080/myajax/data.txt",true);
ajaxObj.onreadystatechange=function()
{
if(ajaxObj.readyState==4&&ajaxObj.status==200)
{
obj.innerHTML=ajaxObj.responseText;
}
}
ajaxObj.send(null);
}
}

</script>

</head>
<body>
<input type="button" value="Click Me To See Some Ajax Magic" onclick="magicByAjax()" id="b1"/>
<br/>
<div id='target1'>
Data fetched from server goes here
</div>
</body>
</html>


data.txtWush! Bang! Here I come from server-land.

----------------------End of sample code-------------------------

Start the tomcat server.
Type the following url in Mozilla Firefox:

http://localhost:8080/myajax/Ajax1.html

Click on the button and enjoy the magic.

Happy Programming ;)

Signing Off
Ryan