Saturday, May 31, 2008

Implicit VS explicit cursor

  1. PL/SQL employs an implicit cursor for each UPDATE, DELETE, or INSERT statement you execute in a program. You cannot, execute these statements within an explicit cursor, even if you want to.
  2. You have a choice between using an implicit or explicit cursor only when you execute a single-row SELECT statement (a SELECT that returns only one row).
  3. When SELECT returns more than one row you may or may not have to use explicit cursor depends on usecase.
  4. If you use an implicit cursor, Oracle performs the open, fetches, and close for you automatically; these actions are outside of your programmatic control.

SQL Faqs

find the two minimum salaries among table
This Query returns duplicate value.
select sal from (select * from order by sal asc) where rownum < 3

This Query retuns only the second minimum salary
Select min(salary) from where Salary>(Select min(salary) from )

Whereas the following Query returns the distinct first two minmum salary in a table
Select min(salary) from union
Select min(salary) from where salary>(Select min(salary) from )

Find out nth highest salary from emp table
directly we can not give the condition as rownum=2....this is the most optimal soluton for the given problem
select * from (select rownum r,salary from (select distinct(salary)from employees where salary is NOT NULL order by salary desc)) where r=2
Best way is using CORRELATED SUBQUERY : as below
Select * From TableName T1 Where (N-1) = (Select Count(Distinct(E2.ColumnName)) From TableName T2 Where T2.ColumnName > T1.ColumnName)
For Required Case We can use it as :-
Select * From EMP T1 Where (2-1) = (Select Count(Distinct(E2.sal)) From EMP T2 Where T2.sal > T1.sal)

XML vs HTML : differences

  1. XML is basically ment to represent data in portable way while HTML to show data.
  2. XML have custom tags HTML has predefined tags.
  3. XML is case sensitive and HTML is not.
  4. XML document has to wellformed HTML doc need not be.

Looking forward for your input... :)

All About JSP : TagHandler

The package javax.servlet.jsp.tagext package has interfaces
  1. Tag
  2. IterationTag
  3. BodyTag

There are classes provided in the javax.servlet.jsp.tagext package which provide default implementation for the above interfaces :
  1. TagSupport
  2. BodyTagSupport
THERE s no IterationTagSupport

Tag interface
The six methods which Tag interface provides and which we have to implement are :
  1. setPageContext(PageContext pc)
  2. setParent(Tag parent)
  3. getParent()
  4. doStartTag()
  5. doEndTag()
  6. release()
Above six methods are a must.
If there are attributes in tag then we have additional setter & getter for them.

Tag Interface Lifecycle
  1. The setPageContext() method : is the first method that is called in the life cycle of a custom tag.
  2. The setParent() and getParent() methods : are used when custom tags are nested one inside the other. The JSP container calls the setParent() method on the child tag and passes it a reference to the parent tag. The getParent() method is usually called by one of the child tags and not directly by the JSP container.
  3. the setters of attributes are called
  4. doStartTag() method : After setting up the tag with appropriate references by calling the setPageContext(), setParent(), and setter methods, the container calls the doStartTag() method on the tag. After initialization, the doStartTag() method decides whether or not to continue evaluating its body content. As a result, it returns one of the two integer constants defined in the Tag interface: EVAL_BODY_INCLUDE or SKIP_BODY. May throw a JSPException.
  5. doEndTag() method : After the body of the tag is evaluated or skipped (depending on the return value of doStartTag()), the container calls the doEndTag() method. May throw a JSPException.
  6. release() method : Finally, the container calls the release() method on the handler class when the tag handler object is no longer required. A custom tag may occur multiple times on a JSP page. A single instance of the tag handler may be used to handle all of these occurrences. The JSP container calls the release() method on the handler class when the handler object is no longer required. It is important to note that this method is not called after every call to doEndTag().

IterationTag Interface

The IterationTag interface extends the Tag interface and allows us to include the body content multiple times, in a way that is similar to the loop functionality of a programming language. The IterationTag interface declares one method and one constant

int doAfterBody() : This method is called after each evaluation of the tag body. It can return either of two values: IterationTag.EVAL_BODY_AGAIN or Tag.SKIP_BODY. The return value determines whether or not the body needs to be reevaluated.

EVAL_BODY_AGAIN : Return value for doAfterBody(). This constant instructs the JSP engine to evaluate the tag body and include it in the output.

If doStartTag() returns SKIP_BODY, then the body is skipped and the container calls doEndTag(). In this case, the doAfterBody() method is never called on the iterative tag. However, if doStartTag() returns EVAL_BODY_INCLUDE, the body of the tag is evaluated, the result is included in the output, and the container calls doAfterBody() for the very first time.

BodyTag Interface

The BodyTag interface extends IterationTag and adds a new functionality that lets the tag handler evaluate its body content in a temporary buffer. This feature allows the tag to process the generated contents at will. For example, after evaluation, the tag handler can view the body content, discard it completely, modify it, or add more data to it before sending it to the output stream. Since it is derived from IterationTag, BodyTag can also handle the evaluation and processing of the content as many times as required.

void setBodyContent(BodyContent) : Called by the JSP container to pass a reference to a
BodyContent object.

void doInitBody( ) : Called by the JSP container after calling setBodyContent(), to allow the tag handler class to perform initialization steps on BodyContent.

EVAL_BODY_BUFFERED : A constant defined as a return value for doStartTag() and doAfterBody() for tags that want to buffer the evaluation of their content

LifeCycle

The doStartTag() method of a class that implements the BodyTag interface returns any one of three values: EVAL_BODY_INCLUDE or SKIP_BODY inherited from the Tag interface, or EVAL_BODY_BUFFERED, which is defined in the BodyTag interface. The actions taken by the JSP container for the return values EVAL_BODY_INCLUDE and SKIP_BODY are the same as for the IterationTag interface.

However, if doStartTag() returns EVAL_BODY_BUFFERED, the JSP container takes a different course of action. It first creates an instance of the BodyContent class. The BodyContent class is a subclass of JspWriter and overrides all the print and write methods of JspWriter to buffer any data written into it rather than sending it to the output stream of the response. The JSP container passes the newly created BodyContent instance to the tag handler using its setBodyContent() method, calls doInitBody() on the tag, and finally evaluates the body of the tag, filling the BodyContent buffer with the result of the body tag evaluation.

The container calls doAfterBody() after evaluating the body, writing the data directly into the output or buffering it, as the case may be. If the output was buffered, we can add, modify, or delete the contents of this buffer. Finally, this method returns EVAL_BODY_AGAIN or EVAL_BODY_BUFFERED to continue evaluating the body in a loop, or returns SKIP_BODY to terminate the loop.

Finally, the container calls doEndTag(), and, as with the other interfaces, the tag handler class that is implementing the BodyTag interface can return either SKIP_PAGE or EVAL_PAGE.

Friday, May 30, 2008

All about JSP : Custom Tags

What's Custom Tag ? and Whats Use ??
Custom tags allow us to move the presentation logic outside the JSP pages into independent Java classes. One may choose to make custom tag for particular project or as an independent jar file.

There are diff kinds of custom tags
  1. Empty Tags
  2. Tags with attributes
  3. Tags with JSP code
  4. Tags with nested tags

Whats TagHandler ?
As name suggest its something that handles Tag and that something can only be java class. A tag handler is a Java class that implements one of the tag interfaces—Tag, IterationTag, or BodyTag—of the package javax.servlet.jsp.tagext.

The JSP specification defines a tag handler as a runtime, container-managed object that evaluates custom actions during the execution of a JSP page.

Whats Tag library descriptor ?
Its the way to let JSP engine know the tag handler classes for custom tags.

How to inform JSP Engine about custom tag library ?
TWO ways
(1) Use the taglib directive

< % @ taglib prefix="test" uri="testLib.tld" % >

(2) Use jsp root
< jsp="http://java.sun.com/JSP/Page" test="testLib.tld" version="1.2">
...JSP PAGE...
< / jsp:root>

Above examples shows URI. It can be of many type right ?
Three Types
(1) Absolute URI :
A URI that has a protocol, a hostname, and optionally a port number.
http://localhost:8080/mytaglibs

(2) Root Relative URI :
A URI that starts with a / "and" that does not have a protocol, a hostname, or a port number. It is interpreted as relative to the document root of the web application.
/myLib
/mytaglib/myLib

(3) Non-root Relative URI :
does not start with a / "and" that does not have a protocol, a hostname, or a port number. It is interpreted as relative to either the current JSP page "or" the WEB-INF, depending on where it is used.
myLib
mytaglib/myLib

< % @ taglib prefix="test" uri="sampleLib.tld" % >
The JSP engine searches for the file in the same directory as the JSP page.
Though keeping all the JSP pages and the TLD files in the same directory is the simplest way to use a taglib directive, it has two major drawbacks: security and flexibility.

How is the URI mapped to TLD ?
Through mapping ... standard reason ... achieve security & flexibility by maintaining a level of redirection ... If we wanted to switch to a newer version of the library, say myLib2.tld, then we would have to manually modify all the JSP pages that are affected by this change. The JSP container maintains a map between the URIs that we use in taglib directives and the actual physical location of the TLD files in the file system.
With this approach, instead of using a page-relative path, we use an absolute URI path:
< % @ taglib prefix="test" uri="http://www.myserver.com/myLib" % >
When the JSP engine reads the above URI, it refers to its internal map to find the corresponding
TLD file location.

The JSP specification mandates that, when deployed in a JAR file, a TLD file be
placed either directly under or inside a subdirectory of the META-INF directory. In
addition, the name of the TLD file must be taglib.tld. Thus, a JAR file containing
a packaged tag library is typically structured like this:
  • myPackage/myTagHandler1.class
  • myPackage/myTagHandler2.class
  • myPackage/myTagHandler3.class
  • META-INF/taglib.tld
How can the jsp container populate the taglib map
Three ways ...
• First, the container reads the user-defined mapping entries present in the deployment descriptor. This is called explicit mapping. We will learn how to add new entries to the deployment descriptor in the next section.
• Then, the container reads all the taglib.tld files present in the packaged JARs. For each jarred TLD file that contains information about its own URI, the JSP container automatically creates a mapping between the specified URI and the current location of the JAR file. This is called implicit mapping. We will learn how to add the URI information to a TLD file in the next chapter, where we will create a custom tag library.
• Finally, the JSP container adds entries for the URIs that are known to the container by default. These URIs are called well-known URIs. The element of a JSP document contains an example of a well-known URI: http://java.sun.com/JSP/Page

Algorithm ?
• If the value of the uri attribute matches any of the entries, the engine uses the value of the corresponding to locate the actual TLD file.
• If the value is a root-relative URI (that is, it starts with a /), the JSP engine assumes the location to be relative to the web application’s document root directory. Thus, the location for the URI http://www.manning.com/studyKit in listing 15.1 will resolve to
the TLD file /myLibs/studyKit.tld.
• If the value is a non-root relative URI (that is, it starts without a /), the JSP engine prepends /WEB-INF/ to the URI and assumes the location to be relative to the web application’s document root directory. Thus, the location for the URI http://www.manning.com/
sample.jar in listing 15.1 will resolve to the TLD file /WEB-INF/yourLibs/studyKit.tld.

• If the value of the uri attribute of the taglib directive does not match any of the entries, then the following three possibilities arise:
• If the specified uri attribute is an absolute URI, then it is an error and is reported at translation time.
• If the specified uri attribute is a root-relative URI, it is assumed to be relative to the web application’s document root directory.
• If the specified uri attribute is a non-root-relative URI, it is assumed to be relative to the current JSP page. Thus, if the JSP file /jsp/test.jsp contains the directive < % @ taglib prefix="test" uri="sample.tld" % >, the engine will expect to find the sample.tld file at /jsp/sample.tld.


Ques Where will it look for TLD file ?
< % @ taglib uri="www.myserver.com/myLib.tld" prefix="mylib" % >
Ans
The URI www.myserver.com/myLib.tld does not contain a protocol; therefore, it is not an absolute URI. It does not start with a /, so it is not a root-relative URI either. It is a page-relative URI. After failing to find an entry in the map, the engine will search for the file hello.tld at the location relative to the current page. Suppose the JSP page is at location
C:\tomcat\webapps\app15\test.jsp
The engine will look for the file at
C:\tomcat\webapps\app\www.myserver.com\hello.tld

Note
The value of cannot be an absolute URI. and both the and are mandatory when defining absoulte way.

google collections library

Link is more than enough :)
http://code.google.com/p/google-collections/

Wednesday, May 28, 2008

Java Tricky Question - 6

whats the difference between

< servlet-mapping >
< servlet-name >ServletOne< / servlet-name >
< url-pattern >/mywebsite/myservlet< / url-pattern >
< / servlet-mapping >

< servlet-mapping >
< servlet-name >ServletTwo< / servlet-name >
< url-pattern >/mywebsite/myservlet/< / url-pattern >
< / servlet-mapping >

< servlet-mapping >
< servlet-name >ServletThree< / servlet-name >
< url-pattern >/mywebsite/myservlet/*< / url-pattern >
< / servlet-mapping >


Dont ask me the answer ,,,, rather help me finding one ... ;o)
this one is still under discussion ... at java ranch

Java Tricky Question - 5

Q: How can you associate an array of values for an initialization parameter of a servlet?

A: You can’t; at least not directly! The deployment descriptor does not
allow you to specify multiple parameters with the same name. So you
have to do something like this:
< init-param >
< param-name > param1 < / param-name >
< param-value > val1 , val2 , val3 , val4 < / param-value >
< init-param >
You would then have to parse the param-value string in the servlet
and interpret the multiple values listed in the string.

Java Tricky Question - 4

Q : Your web application includes an applet packaged as a JAR file. Which directory would you keep the JAR file in?
A:
Because an applet is only run on the client side, the applet JAR file
should be accessible to the clients. This means that it may be kept anywhere
in the document root of the application except in the WEB-INF
directory and its subdirectories.
( As the contents inside the WEB-INF is not visible to client )

Java Tricky Question - 3

Both the interfaces ServletContext and ServletRequest have method getRequestDispatcher() .. whats the difference between them ??

Ans :
You can pass a relative path to the getRequestDispatcher() method of ServletRequest but not to the getRequestDispatcher() method of ServletContext. For example, request.getRequestDispatcher("../html/somePage.html") is valid, and the getRequestDispatcher() method of ServletRequest will evaluate the path relative to the path of the request. For the getRequestDispatcher() method of ServletContext, the path parameter cannot be relative and must start with /. This makes sense because ServletRequest has a current request path to evaluate the relative path while ServletContext does not.

Java Tricky Questions - 2

How can you create multiple servlet objects of the same servlet class if You are not allowed to implements the SingleThreadModel interface ??

Ans :
More than one element is defined in the web.xml file having the same servlet class names.
( some of you may say the ans is stupid ... I mean ques is more literal than technical ... but hey it can be a twister for many )

Practical Use :
You can do this if you want to have multiple sets of initialization parameters. For example, you may want one instance to connect to one database and a second instance to connect to another database.

Tuesday, May 27, 2008

Good Flex sites

the site http://www.flowww.com/

and This "Book tool" is simply superb... http://www.rubenswieringa.com/code/as3/flex/Book/

I wonder if Java ? ADF ? or JavaFX can make such tools .. sites
If yes how easy / tough would it be .... no idea ... !!

Java Tricky Questions - 1

Whats the difference between

int length = 5;
int breadth = 10;
int area = length * breadth;

and

final int length = 5;
final int breadth = 10;
int area = length * breadth;


dont scroll down until you have thought over the answer
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
gave it a thought ?
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
sure ?
.
.
.
.
.
.
.
.
.
.
.
Ok then heres the answer...
In the second code snippet multiplication is done at compile time.
In first multiplication is done at Runtime.
Reason
Java compiler uses something known as Constant Folding. Constant folding refers to the compiler precalculating constant expressions.
Query
I wonder what will happen if the code is

int length = 5;
final int breadth = 10;
int area = length * breadth;

The above code will not use constant folding for length but do so for breadth.
What if ?

static final int breadth = 10;
int area = 5 * breadth;

then compiler will use constant folding for breadth.

Monday, May 26, 2008

HashMap : Not thread safe structure

Nice Read
http://pveentjer.wordpress.com/2008/05/26/hashmap-is-not-a-thread-safe-structure/

Java Tricky questions

Found this link
bad part is answers are not explained

http://www.mydeveloperconnection.com/html/JavaTrap.htm

All About Java Exceptions

Common Java wisdom gives us a few general principles about how to work with exceptions:

1. Don’t use exceptions for flow control and expected business situations, but only for exceptional situations
2. Use unchecked exceptions for programming errors, bugs, situations where the application or the current operation cannot expect to recover from.
3. Use checked exceptions for situations where the caller is expected to be able to make a full or partial recovery after the failure

If we keep the function return type as


public boolean doSomeWork()
{
if(success)
return true;
else
return false;
...
}


two probs
1) Caller will have to check the return value : if he doesnt he may continue with wrong assumption
2) The caller doesn’t have enough information to see what went wrong

With this kind of solution we are back to the way C programs were written... but remember this is java

Another way is...

public class SomeException extends RuntimeException
{
...
}
public boolean doSomeWork()
{
if(success)
return true;
else
throw new SomeException();
...
}


You may have to do some documentation for the new exception class. Which is a disadvantage if you are LAZY ;).
Else the advantages are
* If the client code fails to treat the exception at least the program doesn’t continue on a wrong path.
* We can send more information about the failure context in the exception class through the exception type and the exception instance content.
Disadvantages
* The client code programmer is not automatically warned to treat the exception


One more way is ...

public class SomeException extends Exception
{
...
}
public boolean doSomeWork() throws SomeException
{
if(success)
return true;
else
throw new SomeException();
...
}

Client code will use try / catch block

How can you catch multiple exceptions in java ??

Statement stmt = null;
try {
// do stuff that uses Statement instance
} catch (SQLException e) {
// handle state
log.error("Bad database", e);
} catch (NullPointerException e) {
// handle state
log.error("Bad parameter", e);
} catch (Exception e) {
// handle state
log.error("Bad luck", e);
} finally {
try {
stmt.close();
} catch (Exception ex) {}
}


Summary
Rule of thumb: Use Checked Exceptions for recoverable conditions and Runtime Exceptions for programming errors.
Checked exceptions are great in theory, but in practice lots of developers use them poorly and then the rest of us are left to clean up their mess.
checked exceptions are domain exceptions.

Links
http://truecode.blogspot.com/2008/01/bypassing-java-checked-exception.html
http://dev2dev.bea.com/pub/a/2006/11/effective-exceptions.html
http://dev2dev.bea.com/pub/a/2007/06/exception-advice.html
http://www.csd.uoc.gr/~andreou/

Thursday, May 22, 2008

JSF FAQs

JSF is MVC2 ?
As per my knowledge There is no MVC1 and MVC2
there is JSP model 1 and model 2 as explained in the article
http://www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc.html
JSF is in the scope of model 2


Other frameworks like JSF ?
Apple's WebObjects is a similar architecture to JSF and so is ASP.net.

Difference betwwen managed beans and backing beans ??

f:facet ??


Advantages
JSF's fine-tuned event model allows your applications to be less tied to HTTP details and simplifies your development effort.


http://forum.java.sun.com/thread.jspa?threadID=674446

Tuesday, May 20, 2008

Servlets Basics

javax.servlet.http.HttpServlet Is an abstract class that extends the javax.servlet.GenericServlet class.
All the methods in it have protected identifier and the service method is overloaded

protected void service(HttpServletRequest req, HttpServletResponse resp)

Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class.

 void service(ServletRequest req, ServletResponse res)

Dispatches client requests to the protected service method.

Clicking on a hyperlink always sends a GET request and thus, the doGet() method of the servlet will be called. < href = " /servlet/TestServlet " method="POST"> Some URL < / a >
The method="POST" attribute-value pair does not make sense in the anchor tag.
Retrieve Request Parameter

String[ ] getParameterValues(String paramName)

The above method is for html element like dropbox etc
 Enumeration getParameterNames() 

This method is useful when you don’t know the names of the parameters. You can iterate through the Enumeration of Strings returned by this method and for each element you can call getParameter() or getParameterValues().

Retrieve request headers

There is one difference , though; unlike parameters, headers are specific to the HTTP protocol and so the methods that deal with the headers belong to HttpServletRequest and not to ServletRequest.

 String getHeader(String headerName) 

This method returns just one of the values associated with the given header.
 Enumeration getHeaderValues(String headerName)

This method returns all the values associated with the header as an Enumeration of String object.
 Enumeration getHeaderNames() 

This method is useful when you don’t know the names of the headers. You can iterate through the enumeration returned by this method, and for each element you can call getHeader() or getHeaderValues().

Which method would you use to retrieve the number of parameters present in a request?
Neither ServletRequest nor HttpServletRequest provides any method to retrieve the number of parameters directly. You’ll have to use ServletRequest.getParameterNames(), which returns an Enumeration, and count the number of parameters yourself.

GET vs POST



















































FEATURE

GET method

POST method

Type of data
text text & binary

Amount of data
Browser dependent gen is 255 unlimited

Visibility
data is part of URL Part of body not URL

Caching
can be cached cant be

Bookmarkable
Can bookmark Cant bookmark

Spl Case
Cant be used in case data is character set other than ASCII Can use any type of character set

Use Case
used when the form processing is "idempotent" used in all other cases

Default
Its default for HTML FORM element Its not .. need to use method attribute

Monday, May 19, 2008

HashMap : Basics


package datastructure.delme;
import java.util.*;

class SimpleClass {
private String desc;
public SimpleClass(String s) {
desc=s;
}
public String getDesc() {
return desc;
}
@Override
public String toString() {
return "description is "+desc;
}
}

public class DelMeCollection {
public static void main(String[] args) {
System.out.println("in main");
SimpleClass s1 = new SimpleClass("one");
SimpleClass s2 = new SimpleClass("two");
SimpleClass s3 = new SimpleClass("three");
SimpleClass s4 = new SimpleClass("four");

HashMap hm = new HashMap();
hm.put("1",s1);
hm.put("2",s2);
hm.put("3",s3);
hm.put("4",s4);
Iterator hmKeyItr = hm.keySet().iterator();
while(hmKeyItr.hasNext())
{
String tempKey= (String)hmKeyItr.next();
System.out.println(tempKey+" val is "+hm.get(tempKey));
}

Iterator hmValItr = hm.values().iterator();
while(hmValItr.hasNext())
{
SimpleClass tempVal = (SimpleClass)hmValItr.next();
System.out.println(" val is "+tempVal);
}

for (Map.Entry entry: hm.entrySet())
{
System.out.println(entry.getKey() + " -> " + entry.getValue());
}


}
}



also tried UPCASTING
the following gave error


HashMap < string , object > hm = new HashMap < string , simpleclass >();
HashMap < string , simpleclass > hm = new HashMap < string , object >();
HashMap < string , simpleclass > hm = new HashMap < object , sipleclass >();
HashMap < object , simpleclass > hm = new HashMap< string , simpleclass >();



Moreover java.util.HashMap

Note that this implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new HashMap(...));

Friday, May 16, 2008

Clear the Screen In Java 5

Ask your friend to write a simple command line utility in java that gives a set of options like ...

1. Press 1 to add element to LinkedList
2. Press 2 to Delete an element in LinkedList
3. Press 3 to traverse the LinkedList
4. Press 4 to exit

Enter Your Choice : _


When user choses one of the above mentioned options ,
First , the screen should be cleared off
Second , the corresponding details (if any) should be asked ( like eneter value to add / delete )
Third , perform the action
Fourth , ReDisplay the above menu

To complete the above program you need to write a method like...


public void clearTheScreen( ) {
....
}


or may be


public boolean clearTheScreen( ) {
....
// return true if screen deleted else false
}


How to complete this method ??

hhhmmmm lets "BRAIN STORM"

"first" reply may be...
Runtime.getRuntime.exec("cls");

No you say ...
System-specific tasks such as these may be performed via Runtime.exec( )
it allows you to perform certain system-specific tasks BUT with very little control.

Actually, this won't work. Yes, the 'cls' command is invoked, *but* it is
invoked in a new process ['command.com' or 'cmd.exe' is exected creating a
new process], and *does not* clear the Java application's console.

If your friend is intelligent may argue ...
But if they can implement "beep", and they do, they should be able to implement "cls" too.
But you are MORE intelligent , you say
That's because BELL is a standard ASCII character (code 7) and it's
pretty much standard that any terminal/console would render it by beeping.


The "second" reply may be
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n");

and you say ... its obviously incorrect ( BTW your friend is stupid if he mentions this option ) ,
as it scrolls the menu above so that its not visible to user NOT clean the screen.


"third" reply may be
I heard about this method:
System.out.print((char)27 + "[2J");

Dont get scared probably your friend probably was good DOS progarmmr at some time as + "[2J" is the ANSI escape sequence for clearing the screen.
However, it doen't work unless "ansi.sys" is loaded and very few WinXP user's have this.

If your friend is a Windows geek he may say

Yes, we can add the following command in the c:\windows\system32\config.nt.
device=c:\windows\system32\ansi.sys
This will load the ansi.sys

But that wont work buddy ... you may try it yourself .. and besides
Thats Platform dependent !! and Java is platform independent right ?
so take a "Chill Pill dude"

"fourth" may be ( if your friends guesses this .. he is really good with java / linux )
Printing out the form-feed character will clear the screen
System.out.print("\f");
It works but only on linux , not on windows ... But java code should be platform independent

Your friend : " So WHAT SHOULD I DO ??? "
You ( with a smile ) : Write Java Native Interface [JNI] routines which tap into the relevant operating system functionality
Your Friend : " ?? WHY ?? "
You : Unfortunately these tasks are inherently operating system-specific, and cannot be implemented in any standard way across platforms. Some platforms, in fact, don't even understand the concepts of 'screen', or 'cursor', so wouldn't even have any use for classes that implemented these abstractions. Even the 'standard' C and C++ languages which, like Java, aim for platform independance, do not implement such functionality.

Most intelligent of your friend may say ...
( you know the Phd types )

Maybe a nested class could be added to 'System', containing all the
system-specific console-management routines, something like:

class System
{
...
public class Console
{
...
public static native void cls();
public static native void setCurPos(int row, int col);
public static native String inputString();
public static native double inputNumeric();
...
}
...
}

You could then do something like:

System.Console.cls();


and YOU calmly reply ...
Amego !! It would defeat the purpose of platform-independance, since not all
platforms have the concept of a "console".


Real solution ??
Write JNI ( platform dependent way ) OR
Look at jcurses on sourceforge. ( but using this is an overkill )
http://sourceforge.net/projects/javacurses/

NeXt ... ask your friend .. to write a code to Accept input [say a single keystroke] without pressing ENTER and let me know how it goes ;o)

Contradiction
Contradicting my self ... Recently discovered that with Java 6 , Its very much possible ...
In Java 6 a better way of interacting with the command prompt was introduced, the java.io.Console class.
Together with the utility class java.util.Scanner introduced in Java 5 this new API can be used to develop more advanced Java console applications.

For more detaisl checkout
http://java.dzone.com/news/console-applications-java-6
http://java.sun.com/javase/6/docs/api/java/io/Console.html

Java Sort

http://mindprod.com/jgloss/sort.html

Thursday, May 15, 2008

Java Hashing

lets start with hashing in general and how does java implement same and what are the drawbacks ( if any )

hashing is a process of generating an index or address ( which is of smaller length) basing on ur data . A good hash function is the one which generates distinct addresses for distinct file names.

As a simple example of the using of hashing in databases, a group of people could be arranged in a database like this:
Abernathy, Sara Epperdingle, Roscoe Moore, Wilfred Smith, David (and many more sorted into alphabetical order)
Each of these names would be the key in the database for that person's data. A database search mechanism would first have to start looking character-by-character across the name for matches until it found the match (or ruled the other entries out). But if each of the names were hashed, it might be possible (depending on the number of names in the database) to generate a unique four-digit key for each name. For example:
7864 Abernathy, Sara 9802 Epperdingle, Roscoe 1990 Moore, Wilfred 8822 Smith, David (and so forth)
A search for any name would first consist of computing the hash value (using the same hash function used to store the item) and then comparing for a match using that value. It would, in general, be much faster to find a match across four digits, each having only 10 possibilities, than across an unpredictable value length where each character had 26 possibilities.

The hashing algorithm is also called hash function


Uses of hashing
(i) Hashes play a role in security systems where they're used to ensure that transmitted messages have not been tampered with. The sender generates a hash of the message, encrypts it, and sends it with the message itself. The recipient then decrypts both the message and the hash, produces another hash from the received message, and compares the two hashes. If they're the same, there is a very high probability that the message was transmitted intact.

(ii) Hashing is also a common method of accessing data records.

Java and hashing
Every Java object has a hashCode() and an equals() method. While the Java language does not provide direct support for associative arrays -- arrays that can take any object as an index -- the presence of the hashCode() method in the root Object class clearly anticipates the ubiquitous use of HashMap (and its predecessor, Hashtable). Under ideal conditions, hash-based containers offer both efficient insertion and efficient retrieval; supporting hashing directly in the object model facilitates the development and use of hash-based containers.

if two objects are equal according to the equals() method, they must have the same hashCode() value (although the reverse is not generally true).

Why override equals() and hashCode()?

What would happen if a class did not override equals() and hashCode()? Nothing, if we never used an that class as a key in a HashMap or other hash-based collection. However, if we were to use such a classes object for a key in a HashMap, we would not be able to reliably retrieve the associated value, unless we used the exact same classes instance in the get() call as we did in the put() call. This would require ensuring that we only use a single instance of the Integer object corresponding to a particular integer value throughout our program. Needless to say, this approach would be inconvenient and error prone.

There are some restrictions placed on the behavior of equals() and hashCode(), which are enumerated in the documentation for Object. In particular, the equals() method must exhibit the following properties:
· Symmetry: For two references, a and b, a.equals(b) if and only if b.equals(a)
· Reflexivity: For all non-null references, a.equals(a)
· Transitivity: If a.equals(b) and b.equals(c), then a.equals(c)
· Consistency with hashCode(): Two equal objects must have the same hashCode() value
· For any non-null reference value x, x.equals(null) must return false.

public boolean equals(Object o) {
if (o == null)
return false;
...
}

public boolean equals(Object o) {
if (!(o instanceof MyType))
return false; // also return null if o is null .. no spl check required
...
}

Building hashing into the root object class of the Java class library was a very sensible design compromise -- it makes using hash-based containers so much easier and more efficient. However, several criticisms have been made of the approach to and implementation of hashing and equality in the Java class library. The hash-based containers in java.util are very convenient and easy to use, but may not be suitable for applications that require very high performance. While most of these will never be changed, it is worthwhile to keep in mind when you're designing applications that rely heavily on the efficiency of hash-based containers. These criticisms include:

Too small a hash range. Using int, instead of long, for the return type of hashCode() increases the possibility of hash collisions.


Bad distribution of hash values. The hash values for short strings and small integers are themselves small integers, and are close to the hash values of other "nearby" objects. A more well-behaved hash function would distribute the hash values more evenly across the hash range.


No defined hashing operations. While some classes, such as String and List, define a hash algorithm to be used in combining the hash values of its constituent elements into a single hash value, the language specification does not define any approved means of combining the hash values of multiple objects into a new hash value.

Difficulty writing equals() when extending an instantiable class that already overrides equals(). The "obvious" ways to define equals() when extending an instantiable class that already overrides equals() all fail to meet the symmetry or transitivity requirements of the equals() method. This means that you must understand the structure and implementation details of classes you are extending when overriding equals(), and may even need to expose private fields in the base class as protected to do so, which violates principles of good object-oriented design.

Basically what happens is when hashCode returns a number then its searched for in collection and gets a list, and then it uses equals( ) to search in bucket that it got.

Equals( ) defines logical equality

Recipie for a equals( ) method

1. Use the == operator to check if the argument is a reference to this object.
If so, return true. This is just a performance optimization, but one that is worth
doing if the comparison is potentially expensive.
2. Use the instanceof operator to check if the argument is of the correct
type. If not, return false. Typically, the correct type is the class in which the
method occurs. Occasionally, it is some interface implemented by this class.
Use an interface if the class implements an interface that refines the equals
contract to permit comparisons across classes that implement the interface. The
collection interfaces Set, List, Map, and Map.Entry have this property.
3. Cast the argument to the correct type. Because this cast was preceded by an
instanceof test, it is guaranteed to succeed.
4. For each “significant” field in the class, check to see if that field of the argument
matches the corresponding field of this object. If all these tests succeed,
return true; otherwise, return false.
5. When you are finished writing your equals method, ask yourself three
questions: Is it symmetric, is it transitive, and is it consistent?

Here is the contract, copied from the java.lang.Object specification:
n Whenever it is invoked on the same object more than once during an execution
of an application, the hashCode method must consistently return the
same integer, provided no information used in equals comparisons on the
object is modified. This integer need not remain consistent from one execution
of an application to another execution of the same application.
n If two objects are equal according to the equals(Object) method, then calling
the hashCode method on each of the two objects must produce the same
integer result.
n It is not required that if two objects are unequal according to the equals(Object)
method, then calling the hashCode method on each of the two objects
must produce distinct integer results. However, the programmer should be
aware that producing distinct integer results for unequal objects may improve
the performance of hash tables.

References
http://java.sun.com/docs/books/effective/chapters.html
http://www.owasp.org/index.php/Hashing_Java

Java Iterator

Iterator also has a method remove( ) , when its called it will remove from source the last item retrieved from next( )

If remove is called twice in succesion without a call to next in between IllegalStateException is thrown can get Concurrent MOdification exceptiion if someone else is modifying the collection

according to http://java.sun.com/j2se/1.4.2/docs/api/java/util/Iterator.html#remove()
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.


import java.util.*;
public class DelMeCollection {
public static List l = new ArrayList(25);
static class ListIterateThread extends Thread {
public void run( ){
System.out.println("thread started ");
Iterator listItr = l.iterator();
System.out.println("got the iterator ");
try {
while(listItr.hasNext())
System.out.println("val is "+listItr.next());
} catch(Exception e ) {
System.out.println("some exception "+e);
// wonder why no concurrent modification exception
}
}
}

public static void main(String[] args) {
System.out.println("inside main THREAD");
ListIterateThread lt= new ListIterateThread();
List l = new ArrayList(25);
lt.start();
l.add("1"); System.out.println("added 1");
l.add("2"); System.out.println("added 2");
l.add("3"); System.out.println("added 3");
l.add("4"); System.out.println("added 4");
l.add("5"); System.out.println("added 5");


l.add("11"); System.out.println("added 11");
l.add("12"); System.out.println("added 12");
l.add("13"); System.out.println("added 13");
l.add("14"); System.out.println("added 14");
l.add("15"); System.out.println("added 15");

try {
Thread.currentThread().sleep(5);
} catch (InterruptedException e) {
System.out.println("exception "+e);
}

l.add("21"); System.out.println("added 21");
l.add("22"); System.out.println("added 22");
l.add("23"); System.out.println("added 23");
l.add("24"); System.out.println("added 24");
l.add("25"); System.out.println("added 25");

l.add("31"); System.out.println("added 31");
l.add("32"); System.out.println("added 32");
l.add("33"); System.out.println("added 33");
l.add("34"); System.out.println("added 34");
l.add("35"); System.out.println("added 35");

}
}


Got Output


inside main THREAD
added 1
added 2
added 3
added 4
thread started
added 5
got the iterator
added 11
added 12
added 13
added 14
added 15
added 21
added 22
added 23
added 24
added 25
added 31
added 32
added 33
added 34
added 35


If you want to iterate through "Filtered Collection" try this

Java Collections

Framework consisits of three parts
  1. interfaces -
  2. implementation - of above interfaces
  3. algorithms - general applicable to either interfaces / implementation
Interfaces
  1. Collection - A collection represents a group of objects, known as its elements. may or may not have duplicate elements .. defines no order. JDK has no direct implementation of this interface.
  2. List - defines order , may have dup
  3. Set - no dup
  4. SortedSet - set with order
  5. Map - not part of hierarchy , just store key value pairs

Implementations
Keeping the two concepts ( interface & implementation) seperate can help you write code like
List l = new ....{ }

You can change implementation when your business condition require you to do so

<>

LinkedList is gr8 if u want to add/remove data from middle , if you want indexed access then ArrayList is better

  • All implementations are unsynchronised
  • All implementations offer fail fast iterators
  • All implementations are serializable and cloneable
  • All implementations support having null elements

Algorithm
the Collections class has methods that allow you to perform action on these data
This class consists exclusively of static methods that operate on or return collections.
Has static variables like EMPTY_LIST , EMPTY_MAP , EMPTY_SET
methods like binarySearch , min , max , reverse

java.util.Collection
All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument.

Adding Elements Framework consisits of three parts
(i) interfaces -
(ii) implementation - of above interfaces
(iii) algorithms - general applicable to either interfaces / implementation

Interfaces
  • Collection - A collection represents a group of objects, known as its elements. may or may not have duplicate elements .. defines no order. JDK has no direct implementation of this interface.
  • List - defines order , may have dup
  • Set - no dup
  • SortedSet - set with order
  • Map - not part of hierarchy , just store key value pairs

Implementations
Keeping the two concepts ( interface & implementation) seperate can help you write code like
List l = new ....{ }
You can change implementation when your business condition require you to do so



















































INTERFACE

HASH TABLE

RESIZABLE ARRAY

BALANCED TREE

LINKED LIST

HISTORICAL

SET
Hah Set
TreeSet


SORTEDSET


TreeSet


LIST

ArrayList
LinkedList

MAP


HashMap



WeakHashMap



TreeMap


Vector



Stack



HashTable



Properties



SORTEDMAP


TreeMap



LinkedList is gr8 if u want to add/remove data from middle , if you want indexed access then ArrayList is better

  • All implementations are unsynchronised
  • All implementations offer fail fast iterators
  • All implementations are serializable and cloneable
  • All implementations support having null elements

Algorithm
the Collections class has methods that allow you to perform action on these data
This class consists exclusively of static methods that operate on or return collections.
Has static variables like EMPTY_LIST , EMPTY_MAP , EMPTY_SET
methods like binarySearch , min , max , reverse

java.util.Collection
All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument.

Adding Elements
public boolean add(Object a) -- can only throw UnsupportedOperation exception , not nullpointerExcep
public boolean addAll(Collection c)

Removing Elements
public void clear()
public boolean remove(Object elem)
public boolean removeAll(Collection c)
if original was {1,5,3,8,1,8,2,4,1,3,7,6}
and passed list is {1,7}
every instance of 1 nad 7 will be removed
you get {5,3,8,8,2,4,3,6}

public boolean retainAll(Collection c)
opposite of remove

public Iterator iterator()

finding elements
public boolean contains(Object elem)
public boolean containsAll(Collection c)

checking size
public int size()
public boolean isEmpty()

copy and cloning collection
public Object[] toArray( )
public Object[] toArray(Object[] a)
consults the passed collection in terms of return type and size
if collections.siz() <= a.size() ... elements are returned in array and returned

Collection c = ....
String array[] = new String[c.size()];
array = (String[])c.toArray(array);


check for equality
public boolean equals(Object o)
Note besides Object.equals() interface also has this method to imphasize the fact that need to override Its not necessary to override the Object.equals( ) The general contract for the Object.equals method states that equals must be symmetric (in other words, a.equals(b) if and only if b.equals(a)). The contracts for List.equals and Set.equals state that lists are only equal to other lists, and sets to other sets. Thus, a custom equals method for a collection class that implements neither the List nor Set interface must return false when this collection is compared to any list or set. -- dont try to add colection to itself

List l = new ArrayList(6);
l.add("1");
System.out.println("added 1");
l.add("2");
System.out.println("added 2");
l.add(l);
System.out.println("KABOOM !!");
Iterator listItr = l.iterator();
while(listItr.hasNext())
System.out.println("val is "+listItr.next());

I got the output

added 1
added 2
KABOOM !!
val is 1
val is 2
val is [1, 2, (this Collection)]


collection VS Collection VS Collections

Java Garbage Collection

A garbage collector is responsible for
  • allocating memory
  • ensuring that any referenced objects remain in memory, and
  • recovering memory used by objects that are no longer reachable from references in executing code.

Space is allocated by a large space called heap. The JVM's heap stores all objects created by an executing Java program. Objects are created by Java's "new" operator, and memory for new objects is allocated on the heap at run time.

In addition to freeing unreferenced objects, a garbage collector may also combat heap fragmentation. Heap fragmentation occurs through the course of normal program execution. New objects are allocated, and unreferenced objects are freed such that free blocks of heap memory are left in between blocks occupied by live objects

Code for System.gc is as follows

public static void gc() {
Runtime.getRuntime().gc();
}


System.gc() is just more convinient to call/use

freeMem = Runtime.getRuntime().freeMemory();
System.gc();
System.out.println("free memory after running gc(): " + freeMem);


Interesting links
http://chaoticjava.com/posts/garbage-collection-the-comic-panel/
http://chaoticjava.com/posts/how-does-garbage-collection-work/
http://chaoticjava.com/posts/parallel-and-concurrent-garbage-collectors/
http://chaoticjava.com/posts/gc-tips-and-memory-leaks/

Wednesday, May 14, 2008

Java and MS-Office

Just in case ever need to
  1. Read a Microsoft word document in Java
  2. Import Excel in JTable
In Conference Java One 2008 , Oracle also gave demo on how to integrate MS-Excel with ADF

Java Strings Immutable

Many modern languages (like java) employ “the immutable object” paradigm, which solves a lot of problems including the
  1. Memory conservation
  2. Addressing concurrency concerns
  3. Cache localization
Memory Conservation - A pool of string objects ( constant ) is maintained with references pointing to the constant objects. Instead of each variable having new String object. Re usability leads to lesser memory usage.

Concurrency Concerns - if you change any string need to consider that more than one references may be pointing to same string , so if you will change that string all references must also be updated ( thats tough ) so a new object for changed string will be created and only that particular reference will be point to that new object hence actual object will never change.

I am not sure about cache localization ??

Linux : how to list directory only

To see a listing of all directories in current directory

  • ls -l | grep ^d ( this will show names with details )
  • ls -d */ ( will how names only )

If you want to see hidden directory also
  • ls -d .*"/" *"/"
  • find . -type d -exec ls -d {} \;
  • find . -type d

Tuesday, May 13, 2008

JavaScript : String Performance

Just wanted to book mark these two "excellent" blog entries ...
  1. http://ajaxian.com/archives/everything-you-wanted-to-know-about-string-performance
  2. http://www.sitepen.com/blog/2008/05/09/string-performance-an-analysis/

Servlets and Garbage Collection

Basic Cycle
  1. The destroy() method is called by the servlet container when the container decides to unload the servlet instance itself.
  2. After the destroy() method completes, the servlet engine unloads the servlet,.
  3. Then, the JVM eventually performs garbage collection on the memory resources associated with that servlet object.
Effecient Servlet : Goals

When can you say that a Servlet is efficient , well of course when it does your work in most effecient manner or in other words the algorithm/logic that you have in it is effecient... but there's more to its efficiency .. Read On !!

Secondly even for High volume Web applications, one needs to carefully control the amount of garbage created during page generation. More the garbage created, fewer the pages generated, and the slower is the response time for a particular request. ( This bottleneck occurs because the Java VM has to steal cycles to run garbage collection when it should be generating pages. ) On the flip side , if too much garbage is created, request processing could halt entirely. Which is unacceptable.


Third is to keep the browser active: not too much of "waiting for response" messages. To put it in programatic terms the time a bean spends querying backend is the time a user spends waiting for page to display. This can -- and should -- be avoided using servlet response streaming techniques.

All About Servlets : Run The Servlet


import java.io.IOException;
import java.io.PrintWriter;

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

public class AllAboutServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

public AllAboutServlet() {
System.out.println("CTOR : Servlet constructor can be overriden .. " +
"should not be private , protected , nor default");
System.out.println("CTOR : The ctor will be called by the container ... ");
System.out.println("CTOR : At present its a normal java object .. " +
"doesnt understand ServletContext and ServletConfig ");
System.out.println("CTOR : Servlets are usually instantiated by the servlet " +
"container using the Class.newInstance() method, with no arguments");
}

private AllAboutServlet(int i){
System.out.println("Parameterized ctor value "+i);
System.out.println("It is possible to have a custom constructor for a servlet, " +
"so long as you also add a default constructor with no arguments ?? WHY ??");
System.out.println("the servlet gets instantiated by the container dynamically");
System.out.println("java does not allow to call parametrized constuctor for dynamically " +
"loaded clases");
}

public static void static_method(){
System.out.println("Can have Static method in servlet .. who can call it ??");
System.out.println("Probably no one is stopping other classes to use servlet to" +
"instantiate amnd use it as a normal object ");
System.out.println("Other classes may even call init() service() and then destroy() " +
"that wont make it servlet.. unless container call");
System.out.println("Only container can use servlet class as a servlet ");
}

public void init(ServletConfig config) throws ServletException {
System.out.println("INIT : Servlet init called .. now java object turns servlet .. " +
"understands ServletContext and ServletConfig");
System.out.println("INIT : perform one-time expensive operations, such as acquiring " +
"thread-safe resource acquisition mechanisms ");
// One effective use of the Servlet init method is the creation and caching of
// thread-safe resource acquisition mechanisms, such as JDBC DataSources, EJB Homes,
// and Web Services SOAP Mapping Registry. use this for caching data ...
super.init(config);
// COMPULSORY the abstract superclass implementation of the method in GenericServlet
// stores the servlet configuration object.

// If an exception is thrown in your init(ServletConfig) method, it may be appropriate
// to use the destroy() method to help handle the case. If so, you should still throw
// a ServletException to ensure the servlet is not put into service in this state.
}

public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>AllAboutServlet</title></head>");
out.println("<body>");
out.println("<p>The servlet has received a GET. This is the reply.</p>");
out.println("</body></html>");
out.close();

System.out.println("DOGET : doGet called ");
System.out.println("DOGET : one may call delete() from inside service() ... It will do whatever logic you have in destroy() (cleanup, remove attributes, etc.) but it won't \"unload\" the servlet instance itself");
System.out.println("");
}

public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>AllAboutServlet</title></head>");
out.println("<body>");
out.println("<p>The servlet has received a POST. This is the reply.</p>");
out.println("</body></html>");
out.close();
}

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

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

public void destroy(){
System.out.println("DESTROY : destroy called by contianer .. when is it called ??" +
"When your application is stopped or Servlet Container shuts down ");
System.out.println("DESTROY : Not when embedded oc4j stopped ");
System.out.println("DESTROY : destroy() does not imply garbage collection");
System.out.println("DESTROY : write the destroy() method and destroy your servlet" +
"because if many servlets running on the same webserver are not destroyed explicitly," +
"then the performance of the web server falls down");
System.out.println("DESTROY : destroy() is not guaranteed to be called... but if it is, " +
"you should make sure it works right");
}

public void destroy(int i){
System.out.println("may overload .. its syntactically ok ... container wont call this...");
}

public void point1() {
System.out.println("Is it possible that the servlet container will call destroy()" +
"while the servlet is still processing a request inside service() on a different thread ?");
System.out.println("yes, but it's a degenerate case. The servlet container is required" +
"to wait a reasonable amount of time for current requests to finish processing. So if your" +
"request is not totally lagging, it should work out fine. If you're spending more than" +
"a few seconds processing a request, that's a UI problem that you should try to work out first.");
}
public void point2() {
// GenericServlet has methods ... init() destroy() log() getInitParameter() getInitParameterNames()
// getServletContext() getServletConfig() getServletInfo() getServletName()
}
public void point3() {
// HttpServlet is declared abstract because the default implementations of the main service methods
// do nothing and must be overridden
}
public void point4() {
// The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it
// easy for developers to create custom implementations of the servlet request and response types.
// The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances
// respectively and their default behaviour is to pass all method calls directly to the underlying
// objects.
}

}

All About Servlets : Introduction

The Servlet Philosophy
To write a server side program , need two things
  1. Program at socket level .. handle all the incoming requests
  2. Program at logical level .. write the correct response to each request
The Servlet API is based on simple philosophy , letting the programmers concentrate on the second option and taking care of first option by themselves.

Load On Startup
The element load-on-startup indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the Web application. The element content of this element must be an integer indicating the order in which the servlet should be loaded.
  1. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses.
  2. If the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-startup value.
When is destroy( ) called ?
I could think of following cases...
  1. When your application is stopped
  2. Servlet Container shuts down
  3. In init( ) method if an exception is thrown
What if i call the destroy( ) explicitly
N
othing , it will just execute like a normal java method call it wont unload the servlet. The unloading happens only if the Container calls the destroy( ).

From the Spec


The servlet container is not required to keep a servlet loaded for any particular period of time. A servlet instance may be kept active in a servlet container for a period of milliseconds, for the lifetime of the servlet container (which could be a number of days, months, or years), or any amount of time in between.

When the servlet container determines that a servlet should be removed from service, it calls the destroy method of the Servlet interface to allow the servlet to release any resources it is using and save any persistent state. For example, the container may do this when it wants to conserve memory resources, or when it is being shut down.

Before the servlet container calls the destroy method, it must allow any threads that are currently running in the service method of the servlet to complete execution, or exceed a server-defined time limit.

Once the destroy method is called on a servlet instance, the container may not route other requests to that instance of the servlet. If the container needs to enable the servlet again, it must do so with a new instance of the servlet’s class.

After the destroy method completes, the servlet container must release the servlet instance so that it is eligible for garbage collection.


Can I use a constructor instead of init(ServletConfig) ?
Servlet constructor can be overriden .. not be private , protected , nor default The constructor will be called by the container. In the constructor it doesn't understand classes like ServletContext and ServletConfig.

It is possible to have a custom constructor for a servlet, so long as you also add a default constructor with no arguments the servlet gets instantiated by the container dynamically java does not allow to call parametrized constuctor for dynamically loaded clases

It is possible to have a custom constructor for a servlet, so long as you also add a default constructor with no arguments, but constructors are not called in the standard servlet lifecycle. Servlets are usually instantiated by the servlet container using the Class.newInstance() method, with no arguments. At this point, the servlet has no reference to its configuration or the general servlet context, so it cannot do any useful start-up activity. These configuration references are only available through the init(ServletConfig) method.

Why is it necessary to call super.init(config)?

Programmers are expected to call the super.init(ServletConfig) in the init(ServletConfig) method so that the abstract superclass implementation of the method in GenericServlet stores the servlet configuration object. When the configuration object is stored in this way, the servlet methods getInitParameter(String) and getInitParameterNames() can be called instead of calling the equivalent methods on the configuration object.

Should I get my database connection in the init() method?

The init(ServletConfig) method is only called once when a servlet is brought into service by the servlet container, not for each new servlet thread. If you create a single database connection in the init(ServletConfig) method and use it to all handle servlet requests, you must ensure all operations are synchronized or you will get unpredictable results. You must also ensure the connection is closed when the servlet is taken out of service by overriding the servlet's destroy() method.

Generally it is better to use the init(ServletConfig) method to register the database driver and get a reference to the DriverManager, a DataSource or database connection pool. Then use the connection provider to get a connection for each request within a try/catch block. This way you can handle the case where the connection fails, and ensure that all connections are closed in any case. The close() method of a pooled Connection instance just returns it to the pool.

What's the difference between ServletConfig and ServletContext?

The ServletContext object - represents the context for the whole Web application in which a servlet is deployed, and contains initialisation parameters that are shared amongst all servlets in the application.
The ServletConfig object - represents the configuration for a single specific servlet.

How can I load a Properties file for my servlet?

There are standard methods for identifying and loading this type of static property set into servlets via the ServletContext object. The primary method is getResourceAsStream(String path), which opens an InputStream to the path given in the argument. The path must begin with a forward slash, /, and is relative to the context root, so for instance you might use the path:
/WEB-INF/servlet.properties

Is it possible to overload the destroy() method?

Any Java method may be overloaded, but the overloaded version will not be called directly by a servlet container's lifecycle methods. The servlet container expects all servlets to have a standard no argument destroy() method, so your servlet is safe to use destroy methods with other signatures.
    public void destroy(final String arg) {
// Overloaded method body
}

Can I call destroy() from the service() method ?

The destroy() method has a special significance in the servlet lifecycle when it is called by the servlet container, but is a normal method in all other respects. If you have a typical destroy() method that does servlet clean-up work before the servlet is taken out of service, it is difficult to imagine why you would want to call it from the service() method, though it is possible. Normally, you should handle service requests by overriding the relevant doGet() or doPost() method.

What happens if I call destroy() from init() ?

If the destroy() method is called from the init(ServletConfig) method, whatever statements are contained in the method will be executed and the method will return, it will not affect the lifecycle status of the servlet from the container's point of view. If the init(ServletConfig) method returns without exception, the servlet container will put the servlet into service regardless.

If an exception is thrown in your init(ServletConfig) method, it may be appropriate to use the destroy() method to help handle the case. If so, you should still throw a ServletException to ensure the servlet is not put into service in this state.

Can have Static method in Servlet .. If yes , who can call it ??
Probably no one is stopping other classes to use servlet to instantiate and use it as a normal object Other classes may even call init() service() and then destroy() that wont make a java object a servlet.. unless container calls the same methods Only container can use java class as a servlet.

Summary
To sum up basically a Servlet first becomes a Java object and then a Servlet. I mean a container will first make a Java Object then convert it to Servlet Instance.

You can very well use this as a java object ( in case you call destroy( ) from init( ) etc) but it wont effect the lifeCycle of a servlet. Life cycle of servlet is decided and executed by container servlets cant manage / change their own life cycle by calling there methods.