Tuesday, May 13, 2008

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.

Saturday, May 10, 2008

Flex 2 : Intro

One might think why blog about Flex2 .. when Flex 3 is out ?
well even i dont know why ? all i can say is ... I like flex so thought need to start somewhere !

FLEX

Flex application take advantage of Flash player 9 runtime environment ( which inturn supports 3 ) Flex application can also interact with Javascript.

Flex 2 SDK consists of
  1. the Flex framework (class library)
  2. the Flex compilers,
  3. the debugger,
  4. the MXML
  5. ActionScript programming languages
  6. other utilities.

Flex applications consist of MXML ( set up the UI ) and ActionScript source files
  1. MXML is used for
    1. Visual components - set up UI
    2. Non visual components - acess network based components ( like webservice ) server based resorces ( flex data service ) bindings ( between UI & data )
  2. ActionScript - provides flowcontrol and object manupilation features
Flex applications do not directly connect to a database, you use other tools and services
such as PHP, ASP, JSP, Web services, Flex Data Services, ColdFusion Flash Remoting Services,
and so on.

The Flex platform supports a range of deployment models:
  1. Client-side only Applications run on the client and use no server resources.
  2. Access server data through simple RPC services - Applications interact with remote data through web services and HTTP services. The Flex HTTPService and WebService tags let you retrieve data from a remote server For security, by default Flash Player does not allow an application to access a remote data source from a domain other than the domain from which the application was served. Therefore, a remote server must either be in the same domain as the server hosting your application, or the remote server must define a crossdomain.xml file.
  3. Flex Data Services - used to provide advanced features, such as data synchronization, security, and messaging.

Flex supports two versions of Flash Player
  1. standard flash player
  2. debug flash player

Some questions i couldnt answer
doesnt Flex use Http request / response at low level ? if yes then how ?
if yes why is it so fast than JSF etc ? may be because of Flash player ??

May be when i read more will be able to do so

Interesting Link
http://coenraets.org/testdrive/flex4j/index.htm

Thursday, May 8, 2008

Object.hashcode VS System.identityHashCode

basically System.identityHashCode (Object) always returns different values for different objects
Its declared as public static int identityHashCode(Object x)

The hash code for the null reference is zero.

// FileName Test.java
class HashCodeTest
{
int number;
public HashCodeTest(int i)
{ this.number=i;}

public int hashCode() { return this.number; }
}

public class Test
{
public static void main(String[] args)
{
String s1="Namaste"; String s2 = s1;
System.out.println("s1 "+ s1 + " s2 "+ s2);
System.out.println("System.identityHashCode(s1)" + System.identityHashCode(s1));
System.out.println("System.identityHashCode(s2) "+ System.identityHashCode(s2));
s1=s1 + " World";
System.out.println(" s1 "+ s1 + " s2 " + s2);
System.out.println("System.identityHashCode(s1) " + System.identityHashCode(s1));
System.out.println("System.identityHashCode(s2) "+ System.identityHashCode(s2));

HashCodeTest o1 = new HashCodeTest(5);
HashCodeTest o2 = new HashCodeTest(5);

System.out.println("");
System.out.println("First Object : " + o1);
System.out.println("Second Object : " + o2);
System.out.println("System.identityHashCode(First_Object) : " + System.identityHashCode(o1));
System.out.println("System.identityHashCode(Second_Object) : " + System.identityHashCode(o2));
}
}


the output was something like


s1 Namaste s2 Namaste
System.identityHashCode(s1)1671711
System.identityHashCode(s2) 1671711
s1 Namaste World s2 Namaste
System.identityHashCode(s1) 11394033
System.identityHashCode(s2) 1671711

First Object : HashCodeTest@5
Second Object : HashCodeTest@5
System.identityHashCode(First_Object) : 4384790
System.identityHashCode(Second_Object) : 9634993

String.split( ) VS stringTokenizer

tring.split() was introduced in jdk 1.4'

For one thing, StringTokenizer returns one substring at a time whereas the split method returns an array of substrings.
Best to use String's split(...) method. The StringTokenizer class is a legacy class (NOT deprecated)

By default, StringTokenizer uses whitespace to delimit tokens, and if there are two or more delimiter characters
in a row, it collapses them into one delimiter. So the split() equivalent would be

String[] result = "this is a test".split("\\s+");


But if you really want to treat each character as a separate delimiter, you just remove the plus sign again.
This is, in my opinion, the best reason to choose split(); while there is a way to do single-character delimiters in StringTokenizer, it's kludgy and awkward.

And yes, StringTokenizer is inherently faster,

StringTokenizer can split strings based on single characters, split() takes regular expressions.
I imagine that might make split() a bit slower when splitting for single characters (can't be arsed to test it
though), but usually it's more handy.

Monday, May 5, 2008

Business WebService VS Normal WebService

Business WebService demands the following extra features
  • Security - Obvious
  • Context - when one webservice needs to call another can pass security context need to pass extra context parameter.
  • Transactions - Business Transaction Protocol can help us manage it
  • Process Flow - Controlling the process Flow

Thursday, May 1, 2008

SOAP

SOAP - Stands for Simple Object Access Protocol
  • Simple - transport accross HTTP using Http (mime) and SMTP headers using XML. So is XML simple ? It can be as simple or complex u want it to be. Is MIME simple? It is simple only because it uses a data formatting convention that is already in widespread use, is familiar to most IT people, and is conceptually understood by less technical people.
  • Object - has to do with ways of accessing object
  • Access - A key feature of SOAP and web services is their accessibility. Possible to create SOAP binding for almost any protocol.
  • Protocol - Its a rule.
SOAP messages are fundamentally one-way transmissions from a SOAP sender to a SOAP receiver; however, SOAP messages are often combined to implement patterns such as request/response.

whats the use and difference beween xsi and xsd namespace used in SOAP ??
for example xsi:type , and from xsd you get xsd:string or xsd:boolean

Http has a SOAPAction header.

Its easy to write a program that reads XML document and and wraps it inside SOAP message and send to URL. The class org.apache.soap.Envelope ( extends Lang.Object ) has a default constructor. Similarly org.apache.soap.Body has default constructor and method setBodyEntries(java.util.Vector).

// Build the Message.
org.apache.soap.messaging.Message msg = new org.apache.soap.messaging.Message( );
msg.send (new java.net.URL(m_hostURL), URI, envelope);
org.apache.soap.transport.SOAPTransport st = msg.getSOAPTransport ( );
BufferedReader br = st.receive ( );

JAXB

How do you access and use an XML document through the Java ? Two ways
  1. JAXP - Use Java API for XML Processing (JAXP) ( ie either SAX or DOM )
  2. JAXB - Java Architecture for XML Binding (JAXB)

we can modify the second way as two step process

  1. Bind the Schema for XML document into a set of Java classes ( and interface ) that represents the schema. All JAXB implementations provide a tool called a binding compiler to bind a schema (the way the binding compiler is invoked can be implementation-specific).
  2. Unmarshal the document into Java content objects. Unmarshalling an XML document means creating a tree of content objects that represents the content and organization of the document. The content tree is not a DOM-based tree. In fact, content trees produced through JAXB can be more efficient in terms of memory use than DOM-based trees.

The binding framework comprises three packages. The primary package, javax.xml.bind, contains classes and interfaces for performing operations such as unmarshalling, marshalling, and validation (marshalling and validation will be covered later). A second package, javax.xml.bind.util, contains a number of utility classes. The third package, javax.xml.bind.helper, is designed for JAXB implementation providers.

(1) Get Classes from XML
To unmarshal an XML document, you:

Create a JAXBContext object. This object provides the entry point to the JAXB API. When you create the object, you need to specify a context path. This is a list of one or more package names that contain interfaces generated by the binding compiler. By allowing multiple package names in the context path, JAXB allows you to unmarshal a combination of XML data elements that correspond to different schemas.

import javax.xml.bind.JAXBContext;
JAXBContext jc = JAXBContext.newInstance("test.jaxb");



Create an Unmarshaller object.

import javax.xml.bind.Unmarshaller;
Unmarshaller unmarshaller = jc.createUnmarshaller();


Call the unmarshal method

unmarshaller.setValidating(true);// validate source data against schema
Collection collection= (Collection)unmarshaller.unmarshal(new File( "books.xml"));

Here the Collection is the base xml element not java.util.Collection

Use the get methods in the schema-derived classes to access the XML data.


you can unmarshal XML data from other input sources such as an InputStream object, a URL, or a DOM node. You can even unmarshal transformed XML data.

JAXB also allows you to access XML data without having to unmarshal it. One of the classes generated from a schema, ObjectFactory, contains methods to generate objects for each of the schema-derived interfaces and classes. For example, ObjectFactory class that has methods such as createElement_Name to create a object corresponding to Node in the XML document. You can use these methods to create a tree of content objects without doing any unmarshalling. All your program needs is access to the ObjectFactory class that's in the package for the pertinent schema. Then you can use the appropriate methods in the ObjectFactory class to create the objects you need. After you create the objects, you need to provide their content. To do that, you use the set methods in the objects.

(2) Write XML from Classes
you would:

* Bind the schema for the XML document (if it isn't already bound - same as above)
* Create the content tree.

ObjectFactory objFactory = new ObjectFactory();
Collection collection=(Collection) objFactory.createCollection(); // collection is element name
Collection.BooksType booksType = objFactory.createCollectionTypeBooksType(); // books is element name ( acts as a conatiner )
BookType book = objFactory.createBookType(); // its a element name

Then use set methods in the created objects to specify data values. For example:

book.setItemId("307");
book.setName("JAXB today and beyond");


* Marshal the content tree into the XML document.

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
// step 1 - create context
JAXBContext jaxbContext = JAXBContext.newInstance("test.jaxb");
// step 2 - create marshaller
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,new Boolean(true));
// step 3 - call marshal
marshaller.marshal(collection,new FileOutputStream("jaxbOutput.xml"));


Notice that validation is not performed as part of the marshalling operation. In other words, unlike the case for unmarshalling, there is no setValidating method for marshalling. Instead, when marshalling data, you use the Validator class that is a part of the binding framework to validate a content tree against a schema. For example:


import javax.xml.bind.Validator;

Validator validator = jaxbContext.createValidator();
validator.validate(collection))


(3) Updating XML document



References
http://java.sun.com/developer/technicalArticles/WebServices/jaxb/
http://wiki.java.net/bin/view/Javawsxml/JaxbArticles