Saturday, October 8, 2011

Servlet

URI And URL Difference

Before going into URL and URI,
you need to know some background. Do you ever thought about, who decides what is URL? and what is URI? or who is the authority for URL, URI and such naming conventions?

W3C and IETF

There are two separate bodies W3C and IETF. The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web. The specifications for URI and URL are defined by W3C.
It was founded and headed by Sir Tim Berners-Lee. He is one of the greatest scientist living now. He created this www model of server and client architecture, a web server serving web pages through network and client browsers reading it. He did it first when he was with CERN. He created the world’s first web page http://info.cern.ch/ . He was also in HTML 2.0 working group of IETF. So it is very appropriate for W3C to define URI and URL.
Internet Engineering Task Force (IETF) is an open international community working on Internet related standards. In general it addresses issues of Internet protocols.
In particular W3C defines the web, html specifications and related information. IETF defines IP, TCP, or DNS, for security at any of these levels; with SMTP or NNTP protocols.
So the stake for definition for URI and URL is with W3C. But as there is only a thin line between these organisation’s work they tend to cross each other. In some place IETF gives dissimilar definition for URL and URI.
If you read through the huge volume of journals available in web for this topic, you can sense that experts :-( are using URI and URL synonymously. Which is causing all these confusion among the web community about URI, URL and URN.

URI

An URI identifies a resource. It is a locator. It includes a URI scheme, authority, path, query and fragment by syntax. For example, http: is a URI scheme.
Syntax of URI based on RFC 3986
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
| _____________________|__
/ \ / \
urn:example:animal:ferret:nose

URL

The term “Uniform Resource Locator” (URL) refers to the subset of URIs that, in addition to identifying a resource, provide a means of locating the resource by describing its primary access mechanism (e.g., its network “location”).

URN

The term “Uniform Resource Name” (URN) is used to identify a resource independent of its location. Example urn:ISBN:1-23-432536-5

Summary of differences between URI and URL

  • A URI was either a URL or a URN.
  • URL is a subset of URI. It identifies a resource using one of the URI schemes.
  • URN is a subset of URI. It identifies a resource independent of its location.
Whenever you have a doubt that, whether something is a URL or URI then use URI as a term to identify it. Since URI is a super set of URL.

Session Life Cycle

When I say life cycle, I can hear you murmur “Oh no not again, how many life cycles I have to deal with”! In real world everything has life cycle, then why not in programming, after all, software is all about mimicking real life.  In a previous article I discussed about methods used for session tracking.
Frog Life Cycle
Frog Life Cycle
It has fundamental information about what a session is and how to manage it. At the end of that article I have given a preview about “5. Session tracking API”. Now we are going to dive deep into it.
Just to recap, session is a conversion between a server and a client. An elite way to manage the session in servlets is to use API. Any web server supporting servlets will eventually have to implement the servlet API. It may or may not provide with more features of luxury but the minimum is guaranteed. Servlet specification ensures that, the minimum features provided make the session management job easier. Servlet API will use one of the underlying traditional mechanisms like cookies, URL rewriting, but that will happen behind the scenes and you need not worry about it!

How to access HttpSession object?

Every request is associated with an HttpSession object. It can be retrieved using getSession(boolean create) available in HttpServletRequest. It returns the current HttpSession associated with this request or, if there is no current session and create is true, and then returns a new session. A session can be uniquely identified using a unique identifier assigned to this session, which is called session id. getId() gives you the session id as String.
isNew() will be handy in quite a lot of situations. It returns true if the client does not know about the session or if the client chooses not to join the session. getCreationTime() returns the time when this session was created. getLastAccessedTime() returns the last time the client sent a request associated with this session.

How to store data in session?

Once you have got access to a session object, it can be used as a HashTable to store and retrieve values. It can be used to transport data between requests for the same user and session. setAttribute(String name, Object value) adds an object to the session, using the name specified. Primitive data types cannot be bound to the session.
An important note to you, session is not a bullock cart. It should be used sparingly for light weight objects. If you are in a situation where you have to store heavy weight objects in session, then you are in for a toss. Now it’s time to consult a software doctor. Your software design is having a big hole in it. HttpSession should be used for session management and not as a database.
Follow a proper naming convention to store data in session. Because it will overwrite the existing object if the name is same. One more thing to note is your object needs to implement Serializable interface if you are going to store it in session and carry it over across different web servers.

How to retrieve data from session?

getAttribute(String name) returns the object bound with the specified name in this session. Be careful while using this, most programmers fell into a deeply dug pit NullPointerException. Because it returns null if no object is bound under the name. Always ensure to handle null. Then, removeAttribute(String name) removes the object bound with the specified name from the session. Note a point; be cautious not to expose the session id to the user explicitly. It can be used to breach into another client’s session unethically.

How to invalidate a session object?

By default every web server will have a configuration set for expiry of session objects. Generally it will be some X seconds of inactivity. That is when the user has not sent any request to the server for the past X seconds then the session will expire. What do I mean by expire here. Will the browser blowup into colorful pieces? When a session expires, the HttpSession object and all the data it contains will be removed from the system. When the user sends a request after the session has expired, server will treat it as a new user and create a new session.
Apart from that automatic expiry, it can also be invalidated by the user explicitly. HttpSession provides a method invalidate() this unbinds the object that is bound to it. Mostly this is used at logout. Or the application can have an absurd logic like after the user logins he can use the application for only 30 minutes. Then he will be forced out. In such scenario you can use getCreationTime().
Generally session object is not immortal because of the default configuration by the web server. Mostly these features are left to the imagination of web server implementers. If you take Apache Tomcat 5.5, there is an attribute maxInactiveInterval. A negative value for this will result in sessions never timing out and will be handy in many situations.
Long live the sessions!

An example servlet program to demonstrate the session API

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
public class SessionExample extends HttpServlet {
 
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
 
// getting current HttpSession associated with this request or, if there
// is no current session and create is true, returns a new session.
HttpSession session = request.getSession(true);
 
// Calculating Hit Count
Integer count = (Integer) session
.getAttribute("SessionExample.HitCount");
if (count == null)
count = new Integer(1);
else
count = new Integer(count.intValue() + 1);
session.setAttribute("SessionExample.HitCount", count);
 
out.println("<HTML><HEAD><TITLE>SessionExample</TITLE></HEAD>");
out.println("<BODY><H1>Example session servlet to "
+ "demostrate session tracking and life cycle</H1>");
 
// Displaying the hit count
out.println("Hit count for your current session is " + count);
 
out.println("<H2>Some basic session information:</H2>");
out.println("Session ID: " + session.getId() + "</BR>");
out.println("Is it a new session: " + session.isNew() + "</BR>");
out.println("Session Creation time: " + session.getCreationTime());
out.println("(" + new Date(session.getCreationTime()) + ")</BR>");
out.println("Last accessed time: " + session.getLastAccessedTime());
out.println("(" + new Date(session.getLastAccessedTime()) + ")</BR>");
out.println("Max in active time interval: "
+ session.getMaxInactiveInterval() + "</BR>");
// Checks whether the requested session ID came in as a cookie
out.println("Session ID came in as a cookie: "
+ request.isRequestedSessionIdFromCookie() + "</BR>");
 
out.println("<H2>Iteratively printing all the values "
+ "associated with the session:</H2>");
Enumeration names = session.getAttributeNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = session.getAttribute(name).toString();
out.println(name + " = " + value + "</BR>");
}
 
out.println("</BODY></HTML>");
}
}
Output of the example session servlet
Output of the example session servlet

Servlet JSP Communication

getServletConfig().getServletContext().getRequestDispatcher(“jspfilepathtoforward”).forward(request, response);
The above line is essence of the answer for “How does a servlet communicate with a JSP page?”
When a servlet jsp communication is happening, it is not just about forwarding the request to a JSP from a servlet. There might be a need to transfer a string value or on object itself.
Following is a servlet and JSP source code example to perform Servlet JSP communication. Wherein an object will be communicated to a JSP from a Servlet.

Following are the steps in Servlet JSP Communication:

1. Servlet instantiates a bean and initializes it.
2. The bean is then placed into the request
3. The call is then forwarded to the JSP page, using request dispatcher.
Example Servlet Source Code: (ServletToJSP.java)
public class ServletToJSP extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
    //communicating a simple String message.
    String message = "Example source code of Servlet to JSP communication.";
    request.setAttribute("message", message);
 
    //communicating a Vector object
    Vector vecObj = new Vector();
    vecObj.add("Servlet to JSP communicating an object");
    request.setAttribute("vecBean",vecObj);
 
    //Servlet JSP communication
    RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("/jsp/javaPapers.jsp");
    reqDispatcher.forward(request,response);
  }
}
Example JSP Source Code: (javaPapers.jsp)
<html>
<body>
<%
  String message = (String) request.getAttribute("message");
  out.println("Servlet communicated message to JSP: "+ message);
 
  Vector vecObj = (Vector) request.getAttribute("vecBean");
  out.println("Servlet to JSP communication of an object: "+vecObj.get(0));
%>
</body>
</html>

Session Tracking Methods

Following answer is applicable irrespective of the language and platform used. Before we enter into session tracking, following things should be understood.

What is a session?

A session is a conversation between the server and a client. A conversation consists series of continuous request and response.

Why should a session be maintained?

When there is a series of continuous request and response from a same client to a server, the server cannot identify from which client it is getting requests. Because HTTP is a stateless protocol.
When there is a need to maintain the conversational state, session tracking is needed. For example, in a shopping cart application a client keeps on adding items into his cart using multiple requests. When every request is made, the server should identify in which client’s cart the item is to be added. So in this scenario, there is a certain need for session tracking.
Solution is, when a client makes a request it should introduce itself by providing unique identifier every time. There are five different methods to achieve this.

Session tracking methods:

  1. User authorization
  2. Hidden fields
  3. URL rewriting
  4. Cookies
  5. Session tracking API
The first four methods are traditionally used for session tracking in all the server-side technologies. The session tracking API method is provided by the underlying technology (java servlet or PHP or likewise). Session tracking API is built on top of the first four methods.

1. User Authorization

Users can be authorized to use the web application in different ways. Basic concept is that the user will provide username and password to login to the application. Based on that the user can be identified and the session can be maintained.

2. Hidden Fields

<INPUT TYPE=”hidden” NAME=”technology” VALUE=”servlet”>
Hidden fields like the above can be inserted in the webpages and information can be sent to the server for session tracking. These fields are not visible directly to the user, but can be viewed using view source option from the browsers. This type doesn’t need any special configuration from the browser of server and by default available to use for session tracking. This cannot be used for session tracking when the conversation included static resources lik html pages.

3. URL Rewriting

Original URL: http://server:port/servlet/ServletName
Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456
When a request is made, additional parameter is appended with the url. In general added additional parameter will be sessionid or sometimes the userid. It will suffice to track the session. This type of session tracking doesn’t need any special support from the browser. Disadvantage is, implementing this type of session tracking is tedious. We need to keep track of the parameter as a chain link until the conversation completes and also should make sure that, the parameter doesn’t clash with other application parameters.

4. Cookies

Cookies are the mostly used technology for session tracking. Cookie is a key value pair of information, sent by the server to the browser. This should be saved by the browser in its space in the client computer. Whenever the browser sends a request to that server it sends the cookie along with it. Then the server can identify the client using the cookie.
In java, following is the source code snippet to create a cookie:
Cookie cookie = new Cookie(“userID”, “7456″);
res.addCookie(cookie);
Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the users can opt to disable cookies using their browser preferences. In such case, the browser will not save the cookie at client computer and session tracking fails.

5. Session tracking API

Session tracking API is built on top of the first four methods. This is inorder to help the developer to minimize the overhead of session tracking. This type of session tracking is provided by the underlying technology. Lets take the java servlet example. Then, the servlet container manages the session tracking task and the user need not do it explicitly using the java servlets. This is the best of all methods, because all the management and errors related to session tracking will be taken care of by the container itself.
Every client of the server will be mapped with a javax.servlet.http.HttpSession object. Java servlets can use the session object to store and retrieve java objects across the session. Session tracking is at the best when it is implemented using session tracking api.

What happens if you call destroy() from init() in java servlet?

destroy() gets executed and the initialization process continues. It is a trick question in servlets interview.
In java servlet, destroy() is not supposed to be called by the programmer. But, if it is invoked, it gets executed. The implicit question is, will the servlet get destroyed? No, it will not. destroy() method is not supposed to and will not destroy a java servlet. Don’t get confused by the name. It should have been better, if it was named onDestroy().
The meaning of destroy() in java servlet is, the content gets executed just before when the container decides to destroy the servlet. But if you invoke the destroy() method yourself, the content just gets executed and then the respective process continues. With respective to this question, the destroy() gets executed and then the servlet initialization gets completed.
Have a look at this java servlet interview question: Servlet Life Cycle – Explain, it might help you to understand better.

How to avoid IllegalStateException in java servlet?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.
It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.
Example servlet source code snippet:

public void doGet(HttpServletRequest request,  HttpServletResponse response) throws ServletException, IOException {
if("success".equals(processLogin())) {
response.sendRedirect("menu.jsp");
return; // <-- this return statement ensures that no content is adedd to the response further
}

Note: This same scenario of IllegalStateException is applicable in JSP also.
/*
other servlet code that may add to the response….
*/
}

What is servlet mapping?

Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. It maps url patterns to servlets. When there is a request from a client, servlet container decides to which application it should forward to. Then context path of url is matched for mapping servlets.

How is servlet mapping defined?

Servlets should be registered with servlet container. For that, you should add entries in web deployment descriptor web.xml. It is located in WEB-INF directory of the web application.
Entries to be done in web.xml for servlet-mapping:
<servlet-mapping>
<servlet-name>milk</servlet-name>
<url-pattern>/drink/*</url-pattern>
</servlet-mapping>
servlet-mapping has two child tags, url-pattern and servlet-name. url-pattern specifies the type of urls for which, the servlet given in servlet-name should be called. Be aware that, the container will use case-sensitive for string comparisons for servlet matching.

Syntax for servlet mapping as per servlet specification SRV.11.2:

A string beginning with a ‘/’ character and ending with a ‘/*’ suffix is used for path mapping.
A string beginning with a ‘*.’ prefix is used as an extension mapping.
A string containing only the ‘/’ character indicates the “default” servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
All other strings are used for exact matches only.

Rule for URL path mapping:

It is used in the following order. First successful match is used with no further attempts.
1. The container will try to find an exact match of the path of the request to the path of the servlet. A successful match selects the servlet.
2. The container will recursively try to match the longest path-prefix. This is done by stepping down the path tree a directory at a time, using the ’/’ character as a path separator. The longest match determines the servlet selected.
3. If the last segment in the URL path contains an extension (e.g. .jsp), the servlet container will try to match a servlet that handles requests for the extension. An extension is defined as the part of the last segment after the last ’.’ character.
4. If neither of the previous three rules result in a servlet match, the container will attempt to serve content appropriate for the resource requested. If a “default” servlet is defined for the application, it will be used.

What is implicit mapping?

A servlet container can have a internal JSP container. In such case, *.jsp extension is mapped to the internal container. This mapping is called implicit mapping. This implicit mapping allows ondemand execution of JSP pages. Servlt mapping defined in web application has high precedence over the implicit mapping.

Example code for java servlet mapping:

<servlet>
<servlet-name>milk</servlet-name>
<servlet-class>com.javapapers.Milk</servlet-class>
</servlet>
<servlet>
<servlet-name>points</servlet-name>
<servlet-class>com.javapapers.Points</servlet-class>
</servlet>
<servlet>
<servlet-name>controller</servlet-name>
<servlet-class>com.javapapers.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>milk</servlet-name>
<url-pattern>/drink/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>points</servlet-name>
<url-pattern>/pointlist</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>controller</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

What is Servlet Invoker?

As defined by Apache Tomcat specification, the purpose of Invoker Servlet is to allow a web application to dynamically register new servlet definitions that correspond with a <servlet> element in the /WEB-INF/web.xml deployment descriptor.By enabling servlet invoker the servlet mapping need not be specified for servlets. Servlet ‘invoker’ is used to dispatch servlets by class name.
Enabling the servlet invoker can create a security hole in web application. Because, Any servlet in classpath even also inside a .jar could be invoked directly. The application will also become not portable. Still if you want to enable the servlet invoker consult the web server documentation, because every server has a different method to do it.
In Tomcat 3.x, by default the servlet invoker is enabled. Just place the servlets inside /servlet/ directory and access it by using a fully qualified name like http://[domain]:[port]/[context]/servlet/[servlet.
This mapping is available in web application descriptor (web.xml), located under $TOMCAT_HOME/conf.
/servlet/ is removed from Servlet 2.3 specifications.
In Tomcat 4.x, by defaul the servlet invoker id disabled. The <servlet-mapping> tag is commented inside the default web application descriptor (web.xml), located under $CATALINA_HOME/conf. To enable the invoker servlet uncomment the following two blocks.
<!– The mapping for the invoker servlet –>
<!–
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
–>


<!–
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
–>

Difference between HttpServlet and GenericServlet

javax.servlet.GenericServlet
Signature: public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable
  • GenericServlet defines a generic, protocol-independent servlet.
  • GenericServlet gives a blueprint and makes writing servlet easier.
  • GenericServlet provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface.
  • GenericServlet implements the log method, declared in the ServletContext interface.
  • To write a generic servlet, it is sufficient to override the abstract service method.
javax.servlet.http.HttpServlet
Signature: public abstract class HttpServlet extends GenericServlet implements java.io.Serializable
  • HttpServlet defines a HTTP protocol specific servlet.
  • HttpServlet gives a blueprint for Http servlet and makes writing them easier.
  • HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet.

What is preinitialization of a java servlet?

In the java servlet life cycle, the first phase is called ‘Creation and intialization’.
The java servlet container first creates the servlet instance and then executes the init() method. This initialization can be done in three ways. The default way is that, the java servlet is initialized when the servlet is called for the first time. This type of servlet initialization is called lazy loading.

The other way is through the <load-on-startup>non-zero-integer</load-on-startup> tag using the deployment descriptor web.xml. This makes the java servlet to be loaded and initialized when the server starts. This process of loading a java servlet before receiving any request is called preloading or preinitialization of a servlet.
Servlet are loaded in the order of number(non-zero-integer) specified. That is, lower(example: 1) the load-on-startup value is loaded first and then servlet with higher values are loaded.
Example usage:
<servlet>
       <servlet-name>Servlet-URL</servlet-name>
       <servlet-class>com.javapapers.Servlet-Class</servlet-class>
       <load-on-startup>2</load-on-startup>
</servlet>

oops

Association, Aggregation, Composition, Abstraction, Generalization, Realization, Dependency

These terms signify the relationships between classes. These are the building blocks of object oriented programming and very basic stuff. But still for some, these terms look like Latin and Greek. Just wanted to refresh these terms and explain in simpler terms.

Association

Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.

Example: A Student and a Faculty are having an association.

Aggregation

Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. Aggregation is also called a “Has-a” relationship.

Composition

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.

Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

Difference between aggregation and composition

Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.
Example: A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition. For easy understanding I am picking this example. Don’t go deeper into example and justify relationships!

Abstraction

Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.
Example: A wire frame model of a car.

Generalization

Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behaviour are used from the specializtion to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can relate this term very well. Generalization is also called a “Is-a” relationship.

Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.

Realization

Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class.

Example: A particular model of a car ‘GTB Fiorano’ that implements the blueprint of a car realizes the abstraction.

Dependency

Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.

Example: Relationship between shape and circle is dependency.

News

Its 1 Million now – Thank You

Its been a while I have written on the blog. I was kind of occupied with other studies! Suddenly I noticed a surge in bandwidth usage in my service provider’s report. Something is happening with javapapers. I quickly checked analytics report and found in recent months there is a surge in number of visitors to the website.

Ooh hah! We have crossed ONE MILLION Pageviews. Rarely I see blog authors sharing their site visitor statistics as it might affect the revenue plan. I am happy to share the little stats with you. Its all happening because of you. Thank you!
Its been a slow and steady growth till the last few months. Growth in number of direct visitors is significant in the last couple of months. Similarly from the last couple of months the total Pageviews growth are close to 100%. Almost I am experiencing an explosion in the last few months. This is a successful first step for a blogger and still long way to go. Thanks to Google for all the search traffic and many free tools.

There might be some silent period in between, but I will keep on coming back and annoy you! There is a lot to write about and I will keep on writing. More and more when I try to make it simpler and easier, in direct proportion I learn many new things.

















Top ten countries                

Apache (ASF) Resigns from JCP Committee

It’s one month old news as of today. Still if you are not aware, Apache software foundation one of the most respected group and it moves away from JCP citing license issues and Oracle’s strong hold on java.
Java benefited in many ways for more than 10 years from Apache. It chaired the JCP executive committee and one of the main drivers for java community process. Starting with famous Apache Tomcat, ASF has around 100 projects focusing on Java. This is really sad news for us. We the java community have happily used ASF’s products.
Five years back, can you name a decent project that was built without Apache Ant? Of course now it’s Apache Maven. Okay time to move on. But we believe in Apache’s ethics. I am sure that all those projects will flourish as always.
ASF resigning from JCP is now. In future, will there be JCP itself? Will there be same harmony?
Now we are living in a world of uncertainty pertaining Java. As a developer we may lose some freedom over Java and its path. But we hope java will live long. Losing some freedom, isn’t that everything?

JAG is Now Unemployed!

I recently noticed that James Gosling moved his blog from sun’s site to his own blog with a cool domain name. Also, I noticed in his bio that he is unemployed. Yes, you read it right, James Gosling is unemployed! Oracle bought Sun some time back. We are all eagerly watching the events aftermath. I would say this as one of the huge blows.
Though now java grows out of JSRs, he was the CTO of an important division. Of late his contributions to java as a language is debatable. But above all, he is James Gosling. He resigned on April 2nd. I am not aware of the happenings behind. He says, he is going to start ‘job hunting’.
Don’t get emotionally attached with the product, technology and anything else with you are working on. Only knowledge is yours. Beware, if it could happen to JAG, it could happen to ‘anyone’!


              


Now the SUN is Red

sun.com now redirects to oracle.com – oracle completes acquisition of sun.

Is it a happy news or sad news for sun customers? In particular java guys.
  1. Oracle is a strong supporter of Eclipse – what will happen to NetBeans now?
  2. Will oracle continue and endorse JCP (Java Community Process)?
  3. Will MySQL development continue?
  4. Will oracle continue OpenOffice?
  5. Will Glassfish live in sync with oracle owned weblogic

Oracle’s press release says it will continue to support sun customers and invest more money on SPARC and MySQL. Until now, no negative news to worry about.
This $7.4 billion deal has become notorious on the above fronts. All the controvercy is surrounding MySQL and there is not much noise about what will happen to java!
There is a high possibility for a new commercial platform as oracle java. They know how to sell it as oracle is everywhere.
Mike Milinkovich, the Eclipse Foundation’s Executive Director:
“The Oracle acquisition of Sun and Java holds some real promise for resolving one of the simmering disputes in the Java community. Namely, the technical direction of modularity in Java. OSGi has been around for a number of years and has demonstrated its utility as a well architected Java modularity solution in domains ranging from mobile to enterprise middleware. OSGi has been adopted to varying degrees by every major Java licensor, including Oracle.
During the past couple of years, it looked like Sun was on a path of basically reinventing the wheel. With Oracle at the helm there is a chance that the Java platform will be moving forward with OSGi as the standardized model for modularity.”
But its one killer blow by Larry Ellison. Now the competition with MS$ becomes even stronger, and a new direct competition with IBM and so on.







Log4J

Log4J Levels

This log4j post is a tutorial post describing different levels of logging in log4j. This is for log4j beginners only but if you wish to refresh, go ahead and enjoy!
Log4j logger contains three main components namely logger, appender and layout. Logger takes care of the logging mechanism and deals with level of logging. Log4j provides five standard levels of logging. There are two more special levels given by log4j. Above all these, log4j allows you to create custom levels.
Don’t try to make out a meaning from this image. Just for fun :)

Five standard log4j levels

DEBUG Level

This log4j level helps developer to debug application. Level of message logged will be focused on providing support to a application developer.

INFO Level

This log4j level gives the progress and chosen state information. This level will be generally useful for end user. This level is one level higher than DEBUG.

WARN Level

This log4j level gives a warning about an unexpected event to the user. The messages coming out of this level may not halt the progress of the system.

ERROR Level

This log4j level gives information about a serious error which needs to be addressed and may result in unstable state. This level is one level higher than WARN.

FATAL Level

This log4j level is straightforward and you don’t get it quite often. Once you get this level and it indicates application death.

Two special log4j levels

ALL Level

This log4j level is used to turn on all levels of logging. Once this is configured and the levels are not considered.

OFF Level

This log4j level is opposite to ALL level. It turns off all the logging.

New Trace Level added in Log4j

TRACE Level

This log4j level gives more detailed information than the DEBUG level and sits top of the hierarchy. This level is introduced from version 1.2.12 in log4j.

Custom log4j levels

Log4j’s levels are mostly sufficient for all common applications. Rarely you may need a new Level apart from the levels provided by log4j. In that case you can extend org.apache.log4j.Level class and have your own custom level implementation.

Log4j Logger Output

When a logger is created, generally you assign a level. The logger outputs all those messages equal to that level and also all greater levels than it. So the order for the standard log4j levels are:

Log4J Levels

TRACE Level DEBUG Level INFO Level WARN Level ERROR Level FATAL Level
TRACE Level Y Y Y Y Y Y
DEBUG Level N Y Y Y Y Y
INFO Level N N Y Y Y Y
WARN Level N N N Y Y Y
ERROR Level N N N N Y Y
FATAL Level N N N N N Y
ALL Level Y Y Y Y Y Y
OFF Level N N N N N N

Log4j Level Inheritance Rule

There can be instances when you don’t assign a level to the logger. In such cases log4j handles it seamlessly based on the following level inheritance rule:
The inherited level for a given logger C, is equal to the first non-null level in the logger hierarchy, starting at C and proceeding upwards in the hierarchy towards the root logger.
That means, if you have a package as com.foo.bar and you didn’t allocate a level, then it will inherit the level from com.foo package. Still in that package also if the level is not available, then it will inherit from the log4j root level. The log4j’s root logger is instantiated and available always. Log4j’s root logger by default has DEBUG level.

Jsp

How to pre-compile JSP?

Add jsp_precompile as a request parameter and send a request to the JSP file. This will make the jsp pre-compile. Why it is mentioned as pre compile instead of compilation is that, the request is not served. That is, the JSP will not be executed and the request will not be serviced. Just it will be compiled and the implementation class will be generated.
The jsp_precompile parameter may have no value, or may have values true or false. It should not have any other values like ?jsp_precompile=yes – this will result in HTTP error 500.
So the example for query strings to pre compile jsp files are
?jsp_precompile
?jsp_precompile=true
?jsp_precompile=false
?foobar=foobaz&jsp_precompile=true
?foobar=foobaz&jsp_precompile=false

How to do pre compile for a bunch of JSP files? for all JSPs in a folder or application?

There are no special features available for this in the JSP specification. But the application servers (JSP containers) provide methods to do this on their own way. At the end of this tutorial we will see how to pre compile JSP files for Apache Tomcat 6.
But if you want to pre compile in server independent manner you have to use jsp_precompile request parameter and no other option available. To do it for the whole application, you can custome write a servlet or jsp file which will raise a request for all the JSPs available with jsp_precompile added as parameter.

Following JSP will pre compile all JSPs available in a folder and its subfolder:

<%@ page import="javax.servlet.*,javax.servlet.http.*,javax.servlet.jsp.* "%>
<%@ page import="java.util.Set,java.util.Iterator,java.io.IOException"%>
<%!
  private void preCompileJsp(PageContext pageContext, JspWriter out,
   HttpServletRequest request, HttpServletResponse response, String uripath)
   throws IOException, ServletException {
 
     // getting jsp files list for pre compilation
     Set jspFilesSet = pageContext.getServletContext().getResourcePaths(uripath);
     for (Iterator jspFilesSetItr = jspFilesSet.iterator(); jspFilesSetItr.hasNext();) {
         String uri = (String) jspFilesSetItr.next();
         if (uri.endsWith(".jsp")) {
             RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);
             if (rd == null) throw new Error(uri +" - not found");
             rd.include(request, response);
         }
         else if (uri.endsWith("/")) {
             preCompileJsp(pageContext, out, request, response, uri);
         }
     }
   }
%>
<html><head><title>Pre Compile JSP Files</title></head>
<body>
<%
  HttpServletRequest req = new HttpServletRequestWrapper(request) {
      public String getQueryString() {
          // setting the pre compile parameter
          return "jsp_precompile";
      };
  };
  preCompileJsp(pageContext, out, req, response, "/");
%>
JSP files Pre Compile Completed.
</body></html>

How to pre compile JSP from command line?

Yes you can compile JSP files from command line. There are no specific tool promoted or authored by JSP specification or SUN. The right choice is to depend on application server for which we are compiling application or JSP the JSP files. Logic is to fork the JSP compiler mostly JSPC from command prompt using a utility like ANT.
I will give an example for the popular Apache Tomcat using ANT tool to pre compile JSP files. Important step is to write the ANT build script which will take through the compilation process. Using this ant script, either you can pre compile JSP files from command prompt or you can integrate the step of pre compiling JSP files into the build process which creates the distributable (WAR) file of your application.

Apache Tomcat 6.0 uses Eclipse JDT Java compiler to perform JSP java source code compilation.

<project name="Webapp Precompilation" default="all" basedir=".">
   <import file="${tomcat.home}/bin/catalina-tasks.xml"/>
   <target name="jspc">
<jasper
             validateXml="false"
             uriroot="${webapp.path}"
             webXmlFragment="${webapp.path}/WEB-INF/generated_web.xml"
             outputDir="${webapp.path}/WEB-INF/src" />
  </target>
  <target name="compile">
    <mkdir dir="${webapp.path}/WEB-INF/classes"/>
    <mkdir dir="${webapp.path}/WEB-INF/lib"/>
    <javac destdir="${webapp.path}/WEB-INF/classes"
           optimize="off"
           debug="on" failonerror="false"
           srcdir="${webapp.path}/WEB-INF/src"
excludes="**/*.smap">
      <classpath>
        <pathelement location="${webapp.path}/WEB-INF/classes"/>
        <fileset dir="${webapp.path}/WEB-INF/lib">
          <include name="*.jar"/>
        </fileset>
        <pathelement location="${tomcat.home}/lib"/>
        <fileset dir="${tomcat.home}/common/lib">
          <include name="*.jar"/>
        </fileset>
        <fileset dir="${tomcat.home}/bin">
          <include name="*.jar"/>
        </fileset>
      </classpath>
      <include name="**" />
      <exclude name="tags/**" />
    </javac>
  </target>
  <target name="all" depends="jspc,compile">
  </target>
  <target name="cleanup">
    <delete>
        <fileset dir="${webapp.path}/WEB-INF/src"/>
        <fileset dir="${webapp.path}/WEB-INF/classes/org/apache/jsp"/>
    </delete>
  </target>
</project>
Use the above ant script and execute the following command to pre compile JSP files from command prompt:
$ANT_HOME/bin/ant -Dtomcat.home=<$TOMCAT_HOME> -Dwebapp.path=<$WEBAPP_PATH>

The benefits of pre-compiling a JSP page:

It removes the start-up lag that occurs when a container must translate a JSP page upon receipt of the first request.
Since the Java compiler is not needed, there will be a reduction of the footprint needed to run a JSP container.
In include directives, tag library references, and translation-time actions used in custom actions, compilation of a JSP page provides resolution of relative URL specifications.

Scope of JSP Objects

The availability of a JSP object for use from a particular place of the application is defined as the scope of that JSP object. Every object created in a JSP page will have a scope. Object scope in JSP is segregated into four parts and they are page, request, session and application.
  • page
    ‘page’ scope means, the JSP object can be accessed only from within the same page where it was created. The default scope for JSP objects created using <jsp:useBean> tag is page. JSP implicit objects out, exception, response, pageContext, config and page have ‘page’ scope.
  • request
    A JSP object created using the ‘request’ scope can be accessed from any pages that serves that request. More than one page can serve a single request. The JSP object will be bound to the request object. Implicit object request has the ‘request’ scope.
  • session
    ‘session’ scope means, the JSP object is accessible from pages that belong to the same session from where it was created. The JSP object that is created using the session scope is bound to the session object. Implicit object session has the ‘session’ scope.
  • application
    A JSP object created using the ‘application’ scope can be accessed from any pages across the application. The JSP object is bound to the application object. Implicit object application has the ‘application’ scope.

Difference between forward and sendRedirect

forward

Control can be forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved. This is the major difference between forward and sendRedirect. When the forward is done, the original request and response objects are transfered along with additional parameters if needed.

redirect

Control can be redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost.
For example, sendRedirect can transfer control from http://javapapers.com to http://anydomain.com but forward cannot do this.
‘session’ is not lost in both forward and redirect.
To feel the difference between forward and sendRedirect visually see the address bar of your browser,
in forward, you will not see the forwarded address (since the browser is not involved)
in redirect, you can see the redirected address.

When can we use forward and when can we use sendRedirect?

Technical scenario: redirect should be used
  1. If you need to transfer control to different domain
  2. To achieve separation of task.
For example, database update and data display can be separated by redirect. Do the PaymentProcess and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PyamenProcess will not be repeated. But if you use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.
For other than the above two scenarios, forward is efficient to use since it is faster than sendRedirect.

Example for forward and sendRedirect based on real world

Consider the real world scenario, the milk man comes and asks for monthly payment to you in your house. Here house is the container and you are a resource existing in the container. Milk man is the client or browser.
He asks for the monthly payment to you, this is the request made by the browser to resource A. If you go inside your house and ask your mother (another resource B inside the same container) for the cash and come back and deliver to milkman this is called forward.
If you ask the milkman to speak himself to your mother inside your house or you ask the milkman to speak to your father who is in his office (different domain) then this is called redirect.

JSP Comments

There is only one type of JSP comment available by JSP specification.
JSP Comment Syntax:
<%-- comment --%>
This JSP comment tag tells the JSP container to ignore the comment part from compilation. That is, the commented part of source code is not considered for the content parsed for ‘response’.
Example:
<%-- This JSP comment part will not be included in the response object --%>

Is this a JSP Comment?

<!-- comment --> is not a JSP comment. This is HTML comment. The JSP container treats this HTML comment tag as equal as any other HTML tags. When view source is done, the content given between this tag is visible. This is not anyway related to the JSP container, it is the expected behaviour of this HTML tag.

Example

<!-- This HTML comment part is included in the response object and can be seen in view source -->
// or /* comment */ used inside the <% %> scriplet tag is also not a JSP comment. This is just a java comment and JSP container doesn’t reserve any special treatment for this comments usage.
Therefore, there is nothing called as hidden comment or output comment in JSP by specification.

JSP Implicit Objects

JSP Implicit objects are created by the web container. These implicit objects are Java objects that implement interfaces in the Servlet and JSP API. Scripting elements in a JSP page can make use of these JSP implicit objects. There are nine (9) JSP implicit objects available.

JSP Implicit Objects are as follows:

  1. request implicit object

    The JSP implicit request object is an instance of a java class that implements the javax.servlet.http.HttpServletRequest interface. It represents the request made by the client. The request implicit object is generally used to get request parameters, request attributes, header information and query string values.
  2. response implicit object

    The JSP implicit response object is an instance of a java class that implements the javax.servlet.http.HttpServletResponse interface. It represents the response to be given to the client. The response implicit object is generally used to set the response content type, add cookie and redirect the response.
  3. out implicit object

    The JSP implicit out object is an instance of the javax.servlet.jsp.JspWriter class. It represents the output content to be sent to the client. The out implicit object is used to write the output content.
  4. session implicit object

    The JSP implicit session object is an instance of a java class that implements the javax.servlet.http.HttpSession interface. It represents a client specific conversation. The session implicit object is used to store session state for a single user.
  5. application implicit object

    The JSP implicit application object is an instance of a java class that implements the javax.servlet.ServletContext interface. It gives facility for a JSP page to obtain and set information about the web application in which it is running.
  6. exception implicit object

    The JSP implicit exception object is an instance of the java.lang.Throwable class. It is available in JSP error pages only. It represents the occured exception that caused the control to pass to the JSP error page.
  7. config implicit object

    The JSP implicit config object is an instance of the java class that implements javax.servlet.ServletConfig interface. It gives facility for a JSP page to obtain the initialization parameters available.
  8. page implicit object

    The JSP implicit page object is an instance of the java.lang.Object class. It represents the current JSP page. That is, it serves as a reference to the java servlet object that implements the JSP page on which it is accessed. It is not advisable to use this page implict object often as it consumes large memory.
  9. pageContext implicit object

    The JSP implicit pageContext object is an instance of the javax.servlet.jsp.PageContext abstract class. It provides useful context information. That is it provides methods to get and set attributes in different scopes and for transfering requests to other resources. Also it contains the reference to to implicit objects.

Difference between JSP include directive and JSP include action

  • <%@ include file=”filename” %> is the JSP include directive.
    At JSP page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally JSP include directive is used to include header banners and footers. The JSP compilation procedure is that, the source JSP page gets compiled only if that page has changed. If there is a change in the included JSP file, the source JSP file will not be compiled and therefore the modification will not get reflected in the output.
  • <jsp:include page=”relativeURL” /> is the JSP include action element.
    The jsp:include action element is like a function call. At runtime, the included file will be ‘executed’ and the result content will be included with the soure JSP page. When the included JSP page is called, both the request and response objects are passed as parameters. If there is a need to pass additional parameters, then jsp:param element can be used. If the resource is static, its content is inserted into the calling JSP file, since there is no processing needed.

    Difference between _jspService() and other life cycle methods.

    JSP contains three life cycle methods namely jspInit( ), _jspService() and jspDestroy(). In these, jspInit() and jspDestroy() can be overridden and we cannot override _jspService().
    The contents what we write in the JSP will go into _jspService() because we are implicitly implementing it. If we again try to override it explicitly, JSP compliler will giver error as ‘the method is already implemented and cannot override’. But in the case of other two methods we are not implementing it in the JSP. Therefore the JSP compiler will allow to override jspInit() and jspDestroy().
    To show this difference _jspService() method is prefixed with ‘_’ by the JSP container and the other two methods jspInit() and jspDestroy() has no special prefixes.

    JSP Life Cycle – explain.

    JSP’s life cycle can be grouped into following phases.

    1. JSP Page Translation:

    A java servlet file is generated from the JSP source file. This is the first step in its tedious multiple phase life cycle. In the translation phase, the container validates the syntactic correctness of the JSP pages and tag files. The container interprets the standard directives and actions, and the custom actions referencing tag libraries used in the page.

    2. JSP Page Compilation:

    The generated java servlet file is compiled into a java servlet class.
    Note: The translation of a JSP source page into its implementation class can happen at any time between initial deployment of the JSP page into the JSP container and the receipt and processing of a client request for the target JSP page.

    3. Class Loading:

    The java servlet class that was compiled from the JSP source is loaded into the container.

    4. Execution phase:

    In the execution phase the container manages one or more instances of this class in response to requests and other events.
    The interface JspPage contains jspInit() and jspDestroy(). The JSP specification has provided a special interface HttpJspPage for JSP pages serving HTTP requests and this interface contains _jspService().

    5. Initialization:

    jspInit() method is called immediately after the instance was created. It is called only once during JSP life cycle.

    6. _jspService() execution:

    This method is called for every request of this JSP during its life cycle. This is where it serves the purpose of creation. Oops! it has to pass through all the above steps to reach this phase. It passes the request and the response objects. _jspService() cannot be overridden.

    7. jspDestroy() execution:

    This method is called when this JSP is destroyed. With this call the servlet serves its purpose and submits itself to heaven (garbage collection). This is the end of jsp life cycle.
    jspInit(), _jspService() and jspDestroy() are called the life cycle methods of the JSP.

Java Gallery

Wordle – Word Clouds

From now onwards I am starting up a series, where in I will share cool java applications that I come across. I don’t want to keep my blog stiff. Even some friends have started commenting that, we get exam fever when we stumble on javapapers.com
Sometimes I couldn’t resist myself when I see a nice thing that I feel like introducing to others. So how is it going to get related with javapapers? Will I post about a nice secret joke that I came across. No! as always I will stick to java.
So how can you identify this series? Watch out for the tag (look at the url) – “java-gallery”. Now over to the first cool thing :)
I came across a website named wordle, which generates word clouds. Its awesome! Done using java platform. You should have java in your machine to run that. If you came to javapapers.com thinking that its about coffee, then this site is not for you.
I am dumbstruck by the options it gives. Its not just a toy, it has loads and loads of logic behind it. You may wonder how useful it is? There are many ways, wordle can be useful, starting with generating a nice image for you T-shirt. More than worrying about the usefulness, I wish to appreciate the innovate idea.
Couple of images generated using wordle with source as javapapers.com

just click this image to see the same in large size.
I hope these kind of applications will be an inspiration and will boost the energy of the creator inside everybody.