Monday, August 15, 2011

JSP page life-cycle phases


JSP page life-cycle phases
Phase Name Description
Page translation The page is parsed and a Java file containing the corresponding servlet is created.
Page compilation The Java file is compiled.
Load class The compiled class is loaded.
Create instance An instance of the servlet is created.
Call jspInit() This method is called before any other method to allow initialization.
Call _jspService() This method is called for each request.
Call jspDestroy() This method is called when the servlet container decides to take the servlet out of service.

Servlet Life Cycle




1. Loading and instantiating a servlet

When we start up a servlet container, it looks for deployment descriptors (web.xml) which includes an entry for each of the servlets it uses. An entry specifies the name of the servlet and a Java class name for the servlet. The servlet container creates an instance of the given servlet class using the method Class.forName(className).newInstance().


2. Initializing a servlet

Once the container creates the servlet instance, it calls the init(ServletConfig) method on this newly created instance. The ServletConfig object contains all the initialization parameters that we specify in the deployment
descriptor of the web application. The framework guarantees that the servlet container will call the init() method once and only once on a servlet instance.

3. Servicing client requests

After the servlet instance is properly initialized, it is ready to service client requests. When the servlet container receives requests for this servlet, it will dispatch them to the servlet instance by calling the Servlet.service(ServletRequest, ServletResponse) method.

4. Destroying a servlet

If the servlet container decides that it no longer needs a servlet instance, it calls the destroy() method on the servlet instance. Once this method is called, the servlet instance will be out of service and the container will never call the service() method on this instance. The servlet container cannot reuse this instance in any way. From this state, a servlet instance may only go to the unloaded state. Before calling the destroy() method, the servlet
container waits for the remaining threads that are executing the servlet’s service() method to finish.

A servlet container may destroy a servlet if it is running low on resources and no request has arrived for a servlet in a long time. Similarly, if the servlet container maintains a pool of servlet instances, it may create and destroy the instances from time to time as required. A servlet container may also destroy a servlet if it is shutting down.

5. Unloading a servlet

Once destroyed, the servlet instance may be garbage collected, in which case the servlet instance is said to be unloaded. If the servlet has been destroyed because the servlet container is shutting down, the servlet class will also be unloaded.


Conclusion 
Before a servlet can service the client requests, a servlet container must take certain steps in order to bring the servlet to a state in which it is ready to service the requests. The first step is loading and instantiating the servlet class; the servlet is now considered to be in the loaded state. The second step is initializing the servlet instance. Once the servlet is in the initialized state, the container can invoke its service() method whenever it receives a request from the client. There may be times when the container will call the destroy() method on the servlet instance to put it in the destroyed state. Finally, when the servlet container shuts down, it must unload the servlet instance.

Preinitializing a servlet

Usually, a servlet container does not initialize the servlets as soon as it starts up. It initializes a servlet when it receives a request for that servlet for the first time. This is called lazy loading. Although this process greatly improves the startup time of the servlet container, it has a drawback.

If the servlet performs many tasks at the time of initialization, such as caching static data from a database on initialization, the client that sends the first request will have a poor response time.

In many cases, this is unacceptable. The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor (web.xml) to make the servlet container load and initialize the servlet as soon as it starts up.

This process of loading a servlet before any request comes in is called preloading, or preinitializing, a servlet.

Download free SCJP 1.5 Kathy Sierra and SCWCD Exam study kit

SCJP
SCJP
Exam Study Guide
Author :
Kathy sierra


SCWCD
JAVA web component developer certification

Author :
Hanumant Deshmukh
Jignesh Malavia
Matthew Scarpino

Thursday, August 11, 2011

Java : Assertions

Working with the Assertion Mechanism


Suppose you assume that a number passed into a method (say, methodA()) will never be negative. While testing and debugging, you want to validate your assumption, but you don't want to have to strip out print statements, runtime exception handlers, or if/else tests when you're done with development. But leaving any of those in is, at the least, a performance hit. Assertions to the rescue!


Check out the following code:

private void methodA(int num) {
if (num >= 0) {
useNum(num + x);
} else
// num must be < 0
// This code should never be reached!
System.out.println("oops! num is a negative number! " + num);
}
}


Because you're so certain of your assumption, you don't want to take the time (or program performance hit) to write exception-handling code. And at runtime, you don't want the if/else either because if you do reach the else condition, it means your earlier logic (whatever was running prior to this method being called) is flawed. Assertions let you test your assumptions during development, but the assertion code basically evaporates when the program is deployed, leaving behind no overhead or debugging code to track down and remove. Let's rewrite methodA() to validate that the argument was not negative:



private void methodA(int num) {


assert (num>=0); // throws an AssertionError
// if this test isn't true
useNum(num + x);
}




Not only do assertions let your code stay cleaner and tighter, but because assertions are inactive unless specifically "turned on" (enabled), the code will run as though it were written like this:



private void methodA(int num) {
useNum(num + x); // we've tested this;
// we now know we're good here
}



Assertions work quite simply. You always assert that something is true. If it is, no problem. Code keeps running. But if your assertion turns out to be wrong (false), then a stop-the-world AssertionError is thrown (that you should never, ever handle!) right then and there, so you can fix whatever logic flaw led to the problem. Assertions come in two flavors: really simple and simple, as follows:


Really simple:


private void doStuff() {
assert (y > x);
// more code assuming y is greater than x
}

Simple:

private void doStuff() {
assert (y > x): "y is " + y + " x is " + x;
// more code assuming y is greater than x
}

The difference between the two is that the simple version adds a second expression, separated from the first (boolean expression) by a colon, this expression's string value is added to the stack trace. Both versions throw an immediate AssertionError, but the simple version gives you a little more debugging help while the really simple version simply tells you only that your assumption was false.


Running with Assertions

Here's where it gets cool. Once you've written your assertion-aware code (in other words, code that uses assert as a keyword, to actually perform assertions at runtime), you can choose to enable or disable your assertions at runtime! Remember, assertions are disabled by default.

Enabling Assertions at Runtime

You enable assertions at runtime with

java -ea com.TestAssertions
or
java -enableassertions com.geeksanonymous.TestClass

The preceding command-line switches tell the JVM to run with assertions enabled.




Disabling Assertions at Runtime

You must also know the command-line switches for disabling assertions,

java -da com.TestAssertions
or
java -disableassertions com.TestAssertions

Because assertions are disabled by default, using the disable switches might seem unnecessary. Indeed, using the switches the way we do in the preceding example just gives you the default behavior (in other words, you get the same result regardless of whether you use the disabling switches). But…you can also selectively enable and disable assertions in such a way that they're enabled for some classes and/or packages, and disabled for others, while a particular program is running.



Example


/* TestAssertions.java */
public class  TestAssertions
{
public static void acceptsEvenNumber(int num)
{
if(num %2 != 0)
{
System.out.println("Please enable Assertion");
}
System.out.println("It is Even number : "+num);
}


public static void main(String[] args) 
{
//int num = 10;
int num = 11;
assert(num %2 == 0);// throws an AssertionError
// if this test isn't true


acceptsEvenNumber(num);
}
}


Output



C:\Java>java TestAssertions
Please enable Assertion
It is Even number : 11


C:\Java>java -ea TestAssertions
Exception in thread "main" java.lang.AssertionError
        at TestAssertions.main(TestAssertions.java:18)


Tuesday, August 9, 2011

JBoss error : Expecting "jsp:param" standard action with "name" and "value" attributes

While migration of code from WebSphere to JBoss below mentioned error was observed.

Expecting "jsp:param" standard action with "name" and "value" attributes

Solution :

Replace old code

<jsp:include flush="true" page="file.jsp">
</jsp:include>
 OR
<jsp:forward page="file.jsp">
</jsp:forward>


With new code

<jsp:include flush="true" page="file.jsp"/>
OR
<jsp:forward page="file.jsp"/>




Monday, August 8, 2011

DB2 : the syntax of the string representation of a datetime value is incorrect

DB2 query to get data between two DATE range ie to get data between start date and end date. Basically comparism of dates in DB2.

while writing a SQL query i was getting below mentioned error.


the syntax of the string representation of a datetime value is incorrect

Correct Syntax : 
select OPRID,DATETIME_STAMP,H_SS_ID from Q.PROJECT where date(DATETIME_STAMP) between '2011-08-04' and '2011-08-06' order by DATETIME_STAMP

here it will get data from date range between  2011-08-04 and 2011-08-06. Note date syntax (YYYY-MM-DD)

Also note the date function DATE(..) it will convert complete date to a YYYY-MM-DD format.

 If you want data of one particular day

select OPRID,DATETIME_STAMP,H_SS_ID from Q.PROJECT where date(DATETIME_STAMP) = '2011-08-04'

The basics of DATE TIME in DB2

To get the current date, time, and timestamp using SQL, reference the appropriate DB2 registers:

SELECT current date FROM sysibm.sysdummy1 
SELECT current time FROM sysibm.sysdummy1 
SELECT current timestamp FROM sysibm.sysdummy1 
 
The sysibm.sysdummy1 table is a special in-memory table that can be used to discover the value of DB2 registers. 
Given a date, time, or timestamp, you can extract (where applicable) the year, month, day, hour, minutes, seconds, and microseconds portions independently using the appropriate function:

YEAR (current timestamp) 
MONTH (current timestamp) 
DAY (current timestamp) 
HOUR (current timestamp) 
MINUTE (current timestamp) 
SECOND (current timestamp) 
MICROSECOND (current timestamp) 


Extracting the date and time independently from a timestamp is also very easy:

DATE (current timestamp) 
TIME (current timestamp) 
 
 
You can also perform date and time calculations using, for lack of a better term, English: 
 
current date + 1 YEAR 
current date + 3 YEARS + 2 MONTHS + 15 DAYS 
current time + 5 HOURS - 3 MINUTES + 10 SECONDS 
 
To calculate how many days there are between two dates, you can subtract dates as in the following:
 
days (current date) - days (date('1999-10-22')) 
 

Sunday, August 7, 2011

Java : Strings Are Immutable Objects


Strings Are Immutable Objects

In Java, each character in a string is a 16-bit Unicode character.

In Java, strings are objects. Just like other objects, you can create an instance of a String with the new keyword, as follows:

String s = new String();

This line of code creates a new object of class String, and assigns it to the reference variable s. So far, String objects seem just like other objects. Now, let's give the String a value:

s = "abc";


The String class has many constructors, so you can use a more efficient shortcut. Please see String API.

String s = new String("abc");


And just because you'll use strings all the time, you can even say this:

String s = "abc";

There are some subtle differences between these options that we'll discuss later, but what they have in common is that they all create a new String object, with a value of "abc", and assign it to a reference variable s. Now let's say that you want a second reference to the String object referred to by s:


String s2 = s; // refer s2 to the same String as s



So far so good. String objects seem to be behaving just like other objects, so what's all the fuss about?…Immutability!
Once you have assigned a String a value, that value can never change - it's immutable.



The good news is that while the String object is immutable, its reference variable is not, so to continue with our previous example:

s = s.concat("def"); // the concat() method 'appends'
                            // a literal to the end






The VM took the value of String s (which was "abc"), and tacked "def" onto the end, giving us the value "abcdef". Since Strings are immutable, the VM couldn't stuff this new value into the old String referenced by s, so it created a new String object, gave it the value "abcdef", and made s refer to it. At this point in our example, we have two String objects: the first one we created, with the value "abc", and the second one with the value "abcdef". Technically there are now three String objects, because the literal argument to concat, "def", is itself a new String object. But we have references only to "abc" (referenced by s2) and "abcdef" (referenced by s).

Important Facts About Strings and Memory



To make Java more memory efficient, the JVM sets aside a special area of memory called the "String constant pool." When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created. (The existing String simply has an additional reference.) Now we can start to see why making String objects immutable is such a good idea. If several reference variables refer to the same String without even knowing it, it would be very bad if any of them could change the String's value.


You might say, "Well that's all well and good, but what if someone overrides the String class functionality; couldn't that cause problems in the pool?" That's one of the main reasons that the String class is marked final. Nobody can override the behaviors of any of the String methods, so you can rest assured that the String objects you are counting on to be immutable will, in fact, be immutable.


Now let's assume that no other String objects exist in the pool:


String s = "abc"; // creates one String object and one
                        // reference variable
In this simple case, "abc" will go in the pool and s will refer to it.


String s = new String("abc"); // creates two objects,
                                         // and one reference variable


In this case, because we used the new keyword, Java will create a new String object in normal (non-pool) memory, and s will refer to it. In addition, the literal "abc" will be placed in the pool.



The StringBuffer and StringBuilder Classes



The java.lang.StringBuffer and java.lang.StringBuilder classes should be used when you have to make a lot of modifications to strings of characters. String objects are immutable however objects of type StringBuffer and StringBuilder can be modified over and over again without leaving behind a great effluence of discarded String objects.


StringBuffer vs. StringBuilder


The StringBuilder class was added in Java 5. It has exactly the same API as the StringBuffer class, except StringBuilder is not thread safe. In other words, its methods are not synchronized hence StringBuilder is faster than  StringBuffer.