Monday, November 24, 2008

EJB Design Patterns eBook

EJB Design Patterns
By Floyd Marinescu

EJB Design Patterns goes beyond high-level design pattern descriptions into critical EJB-specific implementation issues, illustrated with source code implementations. The book contains a catalog of twenty advanced EJB patterns and provides strategies for mapping application requirements to patterns-driven design, J2EE development best practices, and a collection of EJB tips and strategies, and other topics such as Build-System best practices using Ant, JUnit testing strategies, using Java Data Objects (JDO) as an alternative to entity beans, and more.

Floyd Marinescu draws on his work building TheServerside.com J2EE community site and offers best practices for three different strategies used in creating primary keys for entity beans: sequence blocks, UUID for EJB, and stored procedures for autogenerated keys.

Read more...

Java Data Objects eBook

Java Data Objects
By David Jordan, Craig Russell

Description: Java Data Objects was written by the JDO Specification Lead and one of the key contributors to the JDO Specification, is the definitive work on the JDO API. This gives you a thorough introduction to JDO, starting with a simple application that demonstrates many of JDO's capabilities. Java Data Objects shows you how to make classes persistent, how JDO maps persistent classes to the database, how to configure JDO at runtime, how to perform transactions, and how to make queries. More advanced chapters cover optional features such as nontransactional access and optimistic transactions. The book concludes by discussing the use of JDO in web applications and J2EE environments.

Read more...

Saturday, November 22, 2008

StringBuilder StringBuffer

StringBuilder vs StringBuffer

StringBuffer is used to store character strings that will be changed (String objects cannot be changed). It automatically expands (buffer size) as needed. Related classes: String, CharSequence.

StringBuilder was added in Java 5.0. It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster. No imports are necessary because these are both in the java.lang package.

StringBuffer and StringBuilder methods and constuctors

Assume the following code:

StringBuffer sb = new StringBuffer();
StringBuffer sb2;
int i, offset, len;
char c;
String s;
char chararr[];
Constructors
sb = new StringBuffer(); // Creates new, empty, StringBuffer
sb = new StringBuffer(n); // Creates new StringBuffer of size n
sb = new StringBuffer(s); // Creates new StringBuffer with initial value s
Using StringBuffer
sb2 = sb.append(x) //appends x (any primitive or object type) to end of sb.
sb2 = sb.append(chararr, offset, len) //appends len chars from chararr starting at index offset.
sb2 = sb.insert(offset, x) // inserts x (char, int, String, ...) at position offset.
sb.setCharAt(index, c) // replaces char at index with c
Deleting from StringBuffer
sb2 = sb.delete(beg, end) //deletes chars at index beg thru end.
sb.setLength(n) // Sets the length of the content to n by either truncating current content or extending it with the null character ('\u0000').
Use sb.setLength(0); to clear a string buffer.
Extracting Values from StringBuffer
c = sb.charAt(i) // char at position i.
s = sb.substring(start) // substring from position start to end of string.
s = sb.substring(start, end) // substring from position start to the char before end.
s = sb.toString() // Returns String.
Searching in StringBuffer
i = sb.indexOf(s) //Returns position of first (leftmost) occurrence of s in sb.
i = sb.lastIndexOf(s) // Returns position of last (rightmost) occurrence of s in sb.
Misc
i = sb.length() // length of the string s.
sb2 = sb.reverse()
Converting values in StringBuffer

An interesting aspect of the append() and insert() methods is that the parameter may be of any type. These methods are overloaded and will perform the default conversion for all primitive types and will call the toString() method for all objects.

Chaining calls in StringBuffer

Some StringBuffer methods return a StringBuffer value (eg, append(), insert(), ...). In fact, they return the same StringBuffer that was used in the call. This allows chaining of calls. Eg,
sb.append("x = ").append(x).append(", y = ").append(y);
Efficiency of StringBuffer compared to String

Because a StringBuffer object is mutable (it can be changed), there is no need to allocate a new object when modifications are desired. For example, consider a method which duplicates strings the requested number of times.

// Inefficient version using String.
public static String dupl(String s, int times) {
String result = s;
for (int i=1; i<times; i++) {
result = result + s;
}
return result;
}
If called to duplicate a string 100 times, it would build 99 new String objects, 98 of which it would immediately throw away! Creating new objects is not efficient. A better solution is to use StringBuffer.

// More efficient version using StringBuffer.
public static String dupl(String s, int times) {
StringBuffer result = new StringBuffer(s);
for (int i=1; i<times; i++) {
result.append(s);
}
return result.toString();
}
This creates only two new objects, the StringBuffer and the final String that is returned. StringBuffer will automatically expand as needed. These expansions are costly however, so it would be better to create the StringBuffer the correct size from the start.

// Much more efficient version using StringBuffer.
public static String dupl(String s, int times) {
StringBuffer result = new StringBuffer(s.length() * times);
for (int i=0; i<times; i++) {
result.append(s);
}
return result.toString();
}
Because StringBuffer is created with the correct capacity, it will never have to expand. There is no constructor which allows both an initial capacity to be specifed and an initial string value. Therefore the loop has one extra iteration in it to give the correct number of repetitions.

Read more...

Friday, November 21, 2008

String Class & StringBuffer

Difference between StringBuffer and String Class :

A String object is immutable. A StringBuffer object is mutable. StringBuffer object is like a String object but can be modified. A string buffer is a sequence of characters but the length and content of the sequence can be changed through certain method calls. The principal operations on a StringBuffer are append() and insert() methods. The append() method adds characters at the end of the buffer and the insert() method adds the characters at a specified location.

The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Every string buffer has a capacity. As long as the length of the character sequence does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If there is an overflow, the string buffer is automatically made larger.

Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.
String str = new String ("Item"); str += "Found!!";
If you were to use StringBuffer to perform the same concatenation, you would need code that looks like this:
StringBuffer str = new StringBuffer ("Item");
str.append("Found!!");
Normally we assume that the first part of the code is more efficient because they think that the second part, which uses the append method for concatenation, is more costly than the first example, which uses the + operator to concatenate two String objects.
The + operator appears innocent, but the code generated produces some surprises. Using a StringBuffer for concatenation can in fact produce code that is significantly faster than using a String.

To trace that,we must see the generated bytecode from our two examples. The bytecode for the example using String looks like this:
0 new #7
3 dup
4 ldc #2
6 invokespecial #12
9 astore_1
10 new #8
13 dup14 aload_1
15 invokestatic #23
18 invokespecial #13
21 ldc #1
23 invokevirtual #15
26 invokevirtual #22
29 astore_1
The bytecode at locations 0 through 9 is executed for the first line of code, namely:
String str = new String("Stanford ");
Then, the bytecode at location 10 through 29 is executed for the concatenation:
str += "Lost!!";
The bytecode generated for the concatenation creates a StringBuffer object, then invokes its append method: the temporary StringBuffer object is created at location 10, and its append method is called at location 23. Because the String class is immutable, a StringBuffer must be used for concatenation.

After the concatenation is performed on the StringBuffer object, it must be converted back into a String. This is done withthe call to the toString method at location 26. This method creates a new String object from the temporary StringBuffer
object. The creation of this temporary StringBuffer object and its subsequent conversion back into a String object are veryexpensive.

In summary, the two lines of code above result in the creation of three objects:
A String object at location 0 A StringBuffer object at location 10 A String object at location 26

Now, let's look at the bytecode generated for the example using StringBuffer:
0 new #8
3 dup4 ldc #2
6 invokespecial #13
9 astore_110 aload_1
11 ldc #1
13 invokevirtual #
15 16 pop
The bytecode at locations 0 to 9 is executed for the first line of code:
StringBuffer str = new StringBuffer("Stanford ");
The bytecode at location 10 to 16 is then executed for the concatenation:
str.append("Lost!!");
Notice that, as is the case in the first example, this code invokes the append method of a StringBuffer object. Unlike the first example, however, there is no need to create a temporary StringBuffer and then convert it into a String object. This code creates only one object, the StringBuffer, at location 0.

In conclusion, StringBuffer concatenation is significantly faster than String concatenation. Obviously, StringBuffers should be used in this type of operation when possible. If the functionality of the String class is desired, consider using a StringBuffer for concatenation and then performing one conversion to String.

Read more...

Thursday, November 20, 2008

Servlet LifeCycle / Life Cycle of a Servlet

Servlet: Servlets are server side java components which provide a powerful mechanism for developing server side java programs. Servlets are mainly used to develop Web-based applications.

Servlet lifecycle

Servlet lifecycle is handled by the servlet container. Servlets are managed components and are managed by web(servlet) container. Servlet life cycle management is the most important responsibility of web container. A servlet is managed through a well defined life cycle that defines how it is loaded, instantiated ad initialized, handles requests from clients and how it is taken out of service.

Syntax:

public void init(ServletConfig config) throws ServletException
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()

The servlet life cycle consists of four steps:

  1. Instantiation
  2. Initialization(init())
  3. request handling (service())
  4. end of service (destroy())

Instantiation (Loading the Servlet)



During this step, web(servlet) container loads the servlet class and creates a new instance of the servlet. The container can create a servlet instance at container startup or it can delay it until the servlet is needed to service a request.



Initialization



During initialization stage of the Servlet life cycle, the web(servlet) container initializes the servlet instance by calling the init() method. The container passes an object implementing the ServletConfig interface via the init() method. This configuration object allows the servlet to access name-value initialization parameters from the web application’s deployment descriptor web.xml file. The container guarantees that the init() method will be called before the service() method is called.



The init() method is typically used to perform servlet initialization, creating or loading objects that are used by the servlet in the handling of its requests. The init() method is commonly used to perform one time activity that is it will be called only once in the life time of the servlet. One of the most common use of init() method is to setup the database connection or connection pool.

Request handling



After a servlet is properly initialized, it is ready to handle the client requests. If the container has a request for the servlet, it calls the servlet instance’s service() method. The request and response information is wrapped in ServletRequest and ServletResponse objects respectively, which are then passed to the servlet's service() method. In the case of an HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse.



Service() method is responsible for processing the incoming requests and generating the response. The service phase of the Servlet life cycle represents all interactions with requests until the Servlet is destroyed. The Servlet interface matches the service phase of the Servlet life cycle to the service() method. The service() method of a Servlet is invoked once per a request and is responsible for generating the response to that request.



The Servlet specification defines the service() method to take two parameters: a javax.servlet.ServletRequest and a javax.servlet.ServletResponse object. These two objects represent a client's request for the dynamic resource and the Servlet's response to the client.

By default a Servlet is multi-threaded, meaning that typically only one instance of a Servlet1 is loaded by a JSP container at any given time. Initialization is done once, and each request after that is handled concurrently2 by threads executing the Servlet's service() method.


End of service() method



When the servlet container determines that a servlet should be removed from service, it calls the destroy () method of the Servlet instance to allow the servlet to release any resources it is using. The servlet container can destroy a servlet because it wants to conserve some memory or server itself is shutting down.



Before the servlet container calls the destroy() method, it allows 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 has completed, the container will release the servlet instance for garbage collection. If it needs another instance of the servlet to process requests it creates the new instance of the servlet and life cycle starts again.


Destroy() method is used to release any resources it is using. The most common use of destroy() method is to close the database connections. The destruction phase of the Servlet life cycle represents when a Servlet is being removed from use by a container. The Servlet interface defines the destroy() method to correspond to the destruction life cycle phase. Each time a Servlet is about to be removed from use, a container calls the destroy() method.

Read more...

Wednesday, November 19, 2008

Jsp Objects / Implicit Objects in Jsp

Jsp Implicit Objects:

Implicit objects in JSP are Java objects that JSP Container makes available to developers in each page. These implicit Objects are automatically available in JSP. JSP Container provides developer to access these implicit objects in their program using JavaBeans and Servlets. These objects need not be declared or instantiated by the JSP author.

They are available only within the _jspService method and not in any declaration. These objects are called implicit objects since they are automatically instantiated by the container and are accessed using standard variables. The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration.

Many implicit objects available in JSP. Some of them are mentioned below:

request object in jsp

The request object has a request scope. It is an instance of the classes that implement javax.servlet.ServletRequest interface. It encapsulates the request coming from a client and uses the getParameter() method to access request parameters. It is passed to the JSP by the container as a parameter to the _jspService() method. This denotes the data included with the HTTP Request. The client first makes a request that is then passed to the server. The requested object is used to take the value from client’s web browser and pass it to the server. This is performed using HTTP request like headers, cookies and arguments.

response object in jsp

The response object has a page scope. It is an instance of the classes that implement javax.servlet.ServletResponse class. It encapsulates the response generated by the JSP to be sent to the client in response to the request. It is generated by the container and passed to the JSP as a parameter to the _jspService() method. This denotes the HTTP Response data. The result or the information from a request is denoted by this object. This is in contrast to the request object. The class or the interface name of the object response is http.HttpServletResponse. The object response is of type Javax.servlet.http. ttpservletresponse. Generally, the object response is used with cookies. The response object is also used with HTTP Headers.

Session object in jsp

The session object has a scope of an entire HttpSession. It is an instance of the javax.servlet.http.HttpSession class. It represents the session created for the requesting client, and stores objects between client's requests. The session object views and manipulates session information, such as the session identifier, creation time, and last accessed time. It also binds objects to a session, so that the user information may persist across multiple user connections.

The session object is valid only for HTTP requests.This denotes the data associated with a specific session of user. The class or the interface name of the object Session is http.HttpSession. The object Session is of type Javax.servlet.http.httpsession. The previous two objects, request and response, are used to pass information from web browser to server and from server to web browser respectively. The Session Object provides the connection or association between the client and the server. The main use of Session Objects is for maintaining states when there are multiple page requests.

jsp Out object

This denotes the Output stream in the context of page. The class or the interface name of the Out object is jsp.JspWriter. The Out object is written: Javax.servlet.jsp.JspWriter. The out object has a page scope. It is an instance of the javax.servlet.jsp.JspWriter class. The JspWriter class is the buffered version of the Printwriter class. It represents the output stream opened back to the client and provides the access to handle servlet's output stream.

jsp PageContext object

This is used to access page attributes and also to access all the namespaces associated with a JSP page. The lass or the interface name of the object PageContext is jsp.pageContext. The object PageContext is written: Javax.servlet.jsp.pagecontext The PageContext object has a page scope. It is an instance of the javax.servlet.jsp.PageContext class. It encapsulates the page-context for the particular JSP page. A pageContext instance provides access to all the namespaces associated with a JSP page. It also provides access to several page attributes such as to include some static or dynamic resource. Implicit objects are added to the PageContext automatically.

jsp Page object

The Page object denotes the JSP page, used for calling any instance of a Page's servlet. The class or the interface name of the Page object is jsp.HttpJspPage. The Page object is written: Java.lang.Object.

jsp Application object

The application object has an application scope. It is an instance of the javax.servlet.ServletContext class. It represents the context within which the JSP is executing. It defines a set of methods that a servlet uses to communicate with its servlet container. These functions include getting the MIME type, request dispatching, and writing contents to a log file. It allows the Web components in the JSP page in the application to share information. This is used to share the data with all application pages. The class or the interface name of the Application object is ServletContext. The Application object is written: Javax.servlet.http.ServletContext.

jsp config object

The config object has a page scope. It is an instance of the javax.servlet.ServletConfig class. The ServletConfig parameter can be set up in the web.xml inside the element. It uses the getInitParameter(String param) to obtain initialization parameters and the getServletContext() method to obtain the ServletContext object. This is used to get information regarding the Servlet configuration, stored in the Config object. The class or the interface name of the Config object is ServletConfig. The object Config is written Javax.servlet.http.ServletConfig.

jsp implicit object exception

The exception object has a page scope. It is an instance of the java.lang.Throwable class. It refers to the runtime exception that resulted in the error-page being invoked. This is available only in an error page, i.e., a page that has isErrorPage=true in the page directive.

Read more...

Head First Servlets and JSP eBook

Head First Servlets and JSP

This book let you know the latest J2EE 1.4 versions of Servlets and JSPs. You can got for Sun Certified Web Component Developer (SCWCD) 1.4 exam with this one. Head First Servlets & JSP will show you how to write servlets and JSPs, what makes the Container tick, how to use the new JSP Expression Language (EL), and more.

Head First Servlets and JSP eBook

Read more...

Thursday, November 13, 2008

Hashtable Hashmap in Java

Difference between Java Hashtable and Java Hashmap

Hashmap can contains null values as the keys and as well as values.But Hashtable dose not allow null values as keys and values.

Hashtable is syncronized. Hashmap is not syncronized.

Hashtable is one of the original collections of Java but HashMap is added with Java 2, v1.2

HashMap does not guarantee that the order of the map will
remain constant over time.

Class HashMap implements Map interface. Hashtable is a concreate implementation of Dictionary class, is Legacy class, all legacy classes are synchronized.

Only one "null" key is allowed in HashMap but multiple "null" values are allowed in HashMap.

HashMap provides Collection views instead of direct support for iteration via Enumeration objects(as in Hashtable). Collection views greatly enhance the expressiveness of the interface.

HashMap allows you to iterate over keys, values, or key-value pairs whereas a Hashtable does not provide the option.

HashMap provides a safe way to remove entries in the midst of iteration, the older Hashtable
does not.

HashMap retrieval is not in order (random). HashTable provide ordered retrieval.

A hashmap is faster than hashtable.

HashMap has a more complex hashing algorithm then Hashtable. It takes the hash value from the key and then hashes it again (double hashing). This can improve the distribution of the keys and hence the performance of the Map. It does take more time to compute though. This is a useful feature as many hashCode implementations are not very good.

Read more...

Difference between Interface and Abstract Class

Abstract Class and Interfaces

A class implementing an interface must implement all of the methods defined in the interface, while a class extending an abstract class need not implement any of the methods defined in the abstract class.

Abstract class does not support Multiple Inheritance . Interface supports Multiple Inheriatance.

Abstract class can implemented some methods also. Interfaces cannot implement methods.

In Interface all member functions are public by default but in abstract class we can have private and protected members.

With abstract classes, you are grabbing away each class’s individuality. With Interfaces, you are merely extending each class’s functionality.

Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast compared to interfaces.

Interfaces can be best the choice when your program need some global variables.

Abstract class definition begins with the keyword "abstract" keyword followed by Class definition. An Interface definition begins with the keyword "interface".

Abstract classes are useful in a situation when some general methods should be implemented and specialization behavior should be implemented by subclasses. Interfaces are useful in a situation when all its properties need to be implemented by subclasses

The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass

There is no difference between a fully abstract class (all methods declared as abstract and all fields are public static final) and an interface.

Neither Abstract classes nor Interface can be instantiated.

Read more...

Java Remote Method Invocation Program

Remote Method Invocation Sample Program

Remote interface:
1. The interface must be public.
2. The interface must extend the interface java.rmi.Remote.
3. Every method in the interface must declare that it throws java.rmi.RemoteException.
Other exceptions may also thrown.

HelloInterface.java

import java.rmi.*;
/** * Remote Interface for the "Hello, world!" example.*/
public interface HelloInterface extends Remote {
/** * Remotely invocable method. * @return the message of the remote object, such as "Hello, world!". * @exception RemoteException if the remote invocation
fails. */
public String say() throws RemoteException;
}


Remote class:

1. It must implement a Remote interface.
2. It should extend the java.rmi.server.UnicastRemoteObject class.Objects of such a class exist in the address space of the server and can be invoked remotely. While there are other ways to define a Remote class, this is the simplest way to ensure that objects of a class can be used as remote objects. See the documentation of the java.rmi.server for more information.
3. It can have methods that are not in its Remote interface. These can only be invoked locally.

Hello.java:
import java.rmi.*;import java.rmi.server.*;
/** * Remote Class for the "Hello, world!" example. */
public class Hello extends UnicastRemoteObject implements HelloInterface {
private String message;
/** * Construct a remote object * @param msg the message of the remote object, such as "Hello, world!". * @exception RemoteException if the object handle cannot be constructed. */
public Hello (String msg) throws RemoteException {
message = msg;
}
/** * Implementation of the remotely invocable method. * @return the message of the remote object, such as "Hello, world!". * @exception RemoteException if the remote invocation fails. */
public String say() throws RemoteException
{
return message;
}
}


All of the Remote interfaces and classes should be compiled using javac. Once this has been completed, the stubs and skeletons for the Remote interfaces should be compiled by using the rmic stub compiler. The stub and skeleton of the example Remote interface are compiled with the command:

rmic Hello

The only problem one might encounter with this command is that rmic might not be able to find the files Hello.class and HelloInterface.class even though they are in the same directory where rmic is being executed. If this happens to you, then try setting the CLASSPATH environment variable to the current directory, as in the following command:

setenv CLASSPATH .

If your CLASSPATH variable already has some directories in it, then you might want to add the current directory to the others.

Remote class and its corresponding Remote interface. We call these Hello and HelloInterface, respectively. The Server requires the definition of both the Remote class and the Remote interface, but the Client only uses the Remote interface. Remote interface represents the type of an object handle, while the Remote class represents the type of an object. If a remote object is being used remotely, its type must be declared to be the type of the Remote interface, not the type of the Remote class.

Note: All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objectsavailable for remote machines.

RMI Client program:

Client itself is just a Java program. It need not be part of a Remote or Serializable class, although it will use Remote and Serializable classes. A remote method invocation can return a remote object as its return value, but one must have a remote object in order to perform a remote method invocation. So to obtain a remote object one must already have one. Accordingly, there must be a separate mechanism for obtaining the first remote object. The Object Registry fulfills this requirement. It allows one to obtain a remote object using only the name of the remote object.

The name of a remote object includes the following information:

1. The Internet name (or address) of the machine that is running the Object Registry with which the remote object is being registered. If the Object Registry is running on the same machine as the one that is making the request, then the name of the machine can be omitted.
2. The port to which the Object Registry is listening. If the Object Registry is listening to
the default port, 1099, this does not have to be included in the name.
3. The local name of the remote object within the Object Registry.


/** * Client program for the "Hello, world!" example. * @param argv The command
line arguments which are ignored. */
public static void main (String[] argv)
{
try
{
HelloInterface hello = (HelloInterface) Naming.lookup ("//RmiRegistryPath/Hello");
System.out.println (hello.say());
}
catch (Exception e)
{ System.out.println ("HelloClient exception: " + e);
}
}

The Naming.lookup method obtains an object handle from the Object Registry running on ortles.ccs.neu.edu and listening to the default port. Note that the result of Naming.lookup must be cast to the type of the Remote interface. The remote method invocation in the example Client is hello.say(). It returns a String which is then printed. A remote method invocation can return a String object because String is a Serializable class.

The code for the Client can be placed in any convenient class. In the example Client, it was placed in a class HelloClient that contains only the program above.

RMI Server:

Server itself is just a Java program. It need not be a Remote or Serializable class, although it will use them. The Server some responsibilities:

1. If class definitions for Serializable classes need to be downloaded from another machine,
then the security policy of your program must be modified. Java provides a security manager class called RMISecurityManager for this purpose. The RMISecurityManager defines a security policy that allows the downloading of Serializable classes from another machine. The "Hello, World!" example does not need such downloads, since the only Serializable class it uses String. As a result it isn't necessary to modify the security policy for the example program. If your program defines Serializable classes that need to be downloaded to another machine, then insert the System.setSecurityManager (new RMISecurityManager ()); as the first statement in the main program below. If this does not work for your program, then you should consult the Security section below.

2. At least one remote object must be registered with the Object Registry. The statement for this is: Naming.rebind (objectName, object); where object is the remote object being registered, and objectName is the String that names the remote object.


/** * Server program for the "Hello, world!" example. * @param argv The command line arguments which are ignored. */
public static void main (String[] argv)
{
try{
Naming.rebind ("Hello", new Hello ("Hello,world!"));
System.out.println ("Hello Server is ready.");
}
catch (Exception e)
{
System.out.println ("Hello Server failed: " + e);
} }


The rmiregistry Object Registry only accepts requests to bind and unbind objects running on the same machine, so it is never necessary to specify the name of the machine when one is egistering an object. The code for the Server can be placed in any convenient class. In the example Server, it was placed in a class HelloServer that contains only the program above.

Running the client and server:

Start the rmiregistry
To start the registry, Windows users should do the following (assuming that your java\bin directory is in the current path):-
start rmiregistry

To start the registry, Unix users should do the following:-
rmiregistry &

Compile the server
Compile the server, and use the rmic tool to create stub files.

Start the server
From the directory in which the classes are located, type the following:-
java ServerProgram

Start the client
You can run the client locally, or from a different machine. In either case, you'll need to specify the hostname of the machine where you are running the server. If you're running it locally, use localhost as the hostname.
java ClientProgram

Read more...

Remote Method Invocation (RMI)

Java Remote Method Invocation is a mechanism for communicating between two machines running Java Virtual Machines. RMI allows one object to invoke a method on an another object existing in other location. The other location could be on the same machine or a different one. The RMI mechanism is basically an object-oriented RPC mechanism. Remote Method Invocation (RMI) facilitates object function calls between Java Virtual Machines (JVMs). JVMs can be located on different computers - even one JVM can invoke methods belonging to an object stored in another JVM.
How RMI differs from CORBA?

CORBA is another object-oriented RPC mechanism. CORBA differs from Java RMI in a number of ways:

1. CORBA is a language-independent standard.
2. CORBA includes many other mechanisms in its standard (standard for TP monitors)
none of which are part of Java RMI.
3. There is also no notion of an "object request broker" in Java RMI.

Java RMI has recently been evolving toward becoming more compatible with CORBA. In particular, there is now a form of RMI called RMI/IIOP ("RMI over IIOP") that uses the Internet Inter-ORB Protocol (IIOP) of CORBA as the underlying protocol for RMI communication.
How RMI Works ?

Consider Java code on machine A needs a service or a method, respectively, of objB (remote Java object) on machine B it starts a remote method invocation. It does this the same way as invoking a local Java object's method.The whole communication behind the remote invocation is done by the RMI mechanism.

When referencing a remote object residing on machine B from code being on machine A there are always two intermediate objects actually handling the communication: a stub object and a skeleton object. When a remote method invocation comes up the following tasks are handled by these two objects:
The stub object (on machine A) has to
* build an information block thats consists of
o an identifier of the remote object to be used,
o an operation number describing the method to be called and
o Marshalled parameters (method parameters have to be encoded
into a format suitable for
transporting them across the net)
* send this information to the server
The skeleton object (on machine B) will

* to unmarshal the parameters,
* to call the desired method on the real object lying on the
server,
* to capture the return value or exception of the call on the
server,
* to marshal this value,
* to send a package consisting of the value in the marshalled
form back to the stub on the
client, machine A.

The stub object unmarshals the return value or exception from the server. This value becomes the return value of the remote method invocation. Or, if the remote method threw an exception, the stub (object) rethrows it in the process space of the caller.
There are three components that participate in supporting remote method invocation.

1. The Client is the process that is invoking a method on a remote object.

2. The Server is the process that owns the remote object. The remote object is an ordinary
object in the address space of the server.

3. The Object Registry is a name server that relates objects with names. Objects are registered
with the Object Registry. Once an object has been registered, one can use the Object
Registry to obtain access to a remote object using the name of the object.

The object registry process has to be started at first. It observes a specific port for bindings between logical names and real objects. Afterwards the server process is started on the same machine. It gives the binding information to the registry process by sending them to the corresponding port. Then everything has be done on server side. Now any client process can be started. It will send lookups to the port of the registry process. Now a connection via a stub object and a skeleton object becomes established.

There are two kinds of classes that can be used in Java RMI.

Remote class is one whose instances can be used remotely. An object of such a class can be referenced in two different ways:

a. Within the address space where the object was constructed, the object is an ordinary object
which can be used like any other object.

b. Within other address spaces, the object can be referenced using an object handle. While there
are limitations on how one can use an object handle compared to an object, for the most part
one can use object handles in the way as an ordinary object.
For simplicity, an instance of a Remote class will be called a remote object.

Serializable class is one whose instances can be copied from one address space to another. An instance of a Serializable class will be called a serializable object. In other words, a serializable object is one that can be marshaled. This concept has no connection to the concept of serializability in database management systems.

If a serializable object is passed as a parameter (or return value) of a remote method invocation, then the value of the object will be copied from one address space to the other. By contrast if a remote object is passed as a parameter (or return value), then the object handle will be copied from one address space to the other.
RMI OverView:

• RMI is an object-oriented implementation of the Remote Procedure Call model; it is an API for
Java programs only
• Using RMI, an object server exports a remote object and registers it with a directory service.
The object provides remote methods, which can be invoked in client programs
• A remote object is declared with a remote interface
• The remote interface is implemented by the remote object
• An object client accesses the object by invoking the remote methods associated with the objects

Read more...

Saturday, November 8, 2008

Hibernate Interview Questions

Java Hibernate FAQ's & Interview Questions

1. What is Hibernate?

Hibernate is a powerful, high performance object/relational persistence and query service. This lets the users to develop persistent classes following object-oriented principles such as association, inheritance, polymorphism, composition, and collections.

2. What is ORM?

ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another.

3. What does an ORM solution comprises of?

• It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes

• Should have a language or an API for specifying queries that refer to the classesand the properties of classes

• An ability for specifying mapping metadata

• It should have a technique for ORM implementation to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions.

4. What are the different levels of ORM quality?

There are four levels defined for ORM quality.

i. Pure relational
ii. Light object mapping
iii. Medium object mapping
iv. Full object mapping

5. What is a pure relational ORM?

The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

6. What is a meant by light object mapping?

The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.

7. What is a meant by medium object mapping?

The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time.

8. What is meant by full object mapping?

Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application.

9. What are the benefits of ORM and Hibernate?

There are many benefits from these. Out of which the following are the most important one.

i. Productivity – Hibernate reduces the burden of developer by providing much ofthe functionality and let the developer to concentrate on business logic.

ii. Maintainability – As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC.

iii. Performance – Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing the performance. If it is automated persistence then it still increases the performance.

iv. Vendor independence – Irrespective of the different types of databases that arethere, hibernate provides a much easier way to develop a cross platform application.

10. How does hibernate code looks like?
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
MyPersistanceClass mpc = new MyPersistanceClass ("Sample App");
session.save(mpc);
tx.commit();
session.close();
The Session and Transaction are the interfaces provided by hibernate. There are many other interfaces besides this.

11. What is a hibernate xml mapping document and how does it look like?

In order to make most of the things work in hibernate, usually the information is provided in an xml document. This document is called as xml mapping document. The document defines, among other things, how properties of the user defined persistence classes’ map to the columns of the relative tables in database.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="sample.MyPersistanceClass" table="MyPersitaceTable">
<id name="id" column="MyPerId">
<generator class="increment"/>
</id>
<property name="text" column="Persistance_message"/>
<many-to-one name="nxtPer" cascade="all" column="NxtPerId"/>
</class>
</hibernate-mapping>
Everything should be included under <hibernate-mapping> tag. This is the main tag for an xml mapping document.

12. Show Hibernate overview?

13. What the Core interfaces are of hibernate framework?

There are many benefits from these. Out of which the following are the most important one.

i. Session Interface – This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.

ii. SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.

iii. Configuration Interface – This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.

iv. Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.

v. Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution.

14. What are Callback interfaces?

These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but they’re useful for implementing certain kinds of generic functionality.

15. What are Extension interfaces?

When the built-in functionalities provided by hibernate is not sufficient enough, it provides a way so that user can include other interfaces and implement those interfaces for user desire functionality. These interfaces are called as Extension interfaces.

16. What are the Extension interfaces that are there in hibernate?

There are many extension interfaces provided by hibernate.

ı ProxyFactory interface - used to create proxies
ı ConnectionProvider interface – used for JDBC connection management
ı TransactionFactory interface – Used for transaction management
ı Transaction interface – Used for transaction management
ı TransactionManagementLookup interface – Used in transaction management.
ı Cahce interface – provides caching techniques and strategies
ı CacheProvider interface – same as Cache interface
ı ClassPersister interface – provides ORM strategies
ı IdentifierGenerator interface – used for primary key generation
ı Dialect abstract class – provides SQL support

17. What are different environments to configure hibernate?

There are mainly two types of environments in which the configuration of hibernate application differs.

i. Managed environment – In this kind of environment everything from database connections, transaction boundaries, security levels and all are defined. An example of this kind of environment is environment provided by application servers such as JBoss, Weblogic and WebSphere.

ii. Non-managed environment – This kind of environment provides a basic configuration template. Tomcat is one of the best examples that provide this kind of environment.

18. What is the file extension you use for hibernate mapping file?

The name of the file should be like this : filename.hbm.xml The filename varies here. The extension of these files should be “.hbm.xml”. This is just a convention and it’s not mandatory. But this is the best practice to follow this extension.

19. What do you create a SessionFactory?
Configuration cfg = new Configuration();
cfg.addResource("myinstance/MyConfig.hbm.xml");
cfg.setProperties( System.getProperties() );
SessionFactory sessions = cfg.buildSessionFactory();
First, we need to create an instance of Configuration and use that instance to refer to the location of the configuration file. After configuring this instance is used to create the SessionFactory by calling the method buildSessionFactory().

20. What is meant by Method chaining?

Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to actual java code. And it is not mandatory to use this format. Look how a SessionFactory is created when we use method chaining.
SessionFactory sessions = new Configuration()
.addResource("myinstance/MyConfig.hbm.xml")
.setProperties( System.getProperties() )
.buildSessionFactory();
21. What does hibernate.properties file consist of?

This is a property file that should be placed in application class path. So when the Configuration object is created, hibernate is first initialized. At this moment the application will automatically detect and read this hibernate.properties file.
hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB
hibernate.transaction.factory_class =
net.sf.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class =
net.sf.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect
22. What should SessionFactory be placed so that it can be easily accessed?

As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various components that are hibernate aware. You can set the SessionFactory to a JNDI by configuring a property hibernate.session_factory_name in the hibernate.properties file.

23. What are POJOs?

POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. Besides they can also have some business logic related to that property. Hibernate applications works efficiently with POJOs rather then simple java classes.

24. What is object/relational mapping metadata?

ORM tools require a metadata format for the application to specify the mapping between classes and tables, properties and columns, associations and foreign keys, Java types and SQL types. This information is called the object/relational mapping metadata. It defines the transformation between the different data type systems and relationship representations.

25. What is HQL?

HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL.

26. What are the different types of property and class mappings?

• Typical and most common property mapping
<property name="description" column="DESCRIPTION" type="string"/>
Or
<property name="description" type="string">
<column name="DESCRIPTION"/>
</property>
• Derived properties
<property name="averageBidAmount" formula="( select AVG(b.AMOUNT) from BID b
where b.ITEM_ID = ITEM_ID )" type="big_decimal"/>
• Typical and most common property mapping
<property name="description" column="DESCRIPTION" type="string"/>
• Controlling inserts and updates
<property name="name" column="NAME" type="string"
insert="false" update="false"/>
27. What is Attribute Oriented Programming?

XDoclet has brought the concept of attribute-oriented programming to Java. Until JDK 1.5, the Java language had no support for annotations; now XDoclet uses the Javadoc tag format (@attribute) to specify class-, field-, or method-level metadata attributes. These attributes are used to generate hibernate mapping file automatically when the application is built. This kind of programming that works on attributes is called as Attribute Oriented Programming.

28. What are the different methods of identifying an object?

There are three methods by which an object can be identified.

i. Object identity –Objects are identical if they reside in the same memory location
in the JVM. This can be checked by using the = = operator.

ii. Object equality – Objects are equal if they have the same value, as defined by the
equals( ) method. Classes that don’t explicitly override this method inherit the
implementation defined by java.lang.Object, which compares object identity.

iii. Database identity – Objects stored in a relational database are identical if they
represent the same row or, equivalently, share the same table and primary key value.

29. What are the different approaches to represent an inheritance hierarchy?

i. Table per concrete class.

ii. Table per class hierarchy.

iii. Table per subclass.

30. What are managed associations and hibernate associations?

Associations that are related to container management persistence are called managed
associations. These are bi-directional associations. Coming to hibernate associations,
these are unidirectional.

Read more...

Friday, November 7, 2008

JAVA 6

Java Standard Edition 6 (Java SE 6) is feature complete and stable enough for mainstream evaluation. They can be classified into two categories: Desktop and Core Improvements.

The desktop improvements focus mainly on user interface (UI) performance and native OS desktop integration.

The core improvements focus mainly on improving developer productivity and Java application management. Java 6 also had significant effort towards Web services support and security improvements.

Core Improvements:

The Java core can be described as portions of Java that are fundamental to all other aspects of Java, from user interface APIs to server libraries. They are

Developer Productivity:

The new Java Compiler API allows Java source to be compiled from within a Java application. During compilation, the application has access to the library dependency information as formulated, along with any warnings, errors, and other messages that are generated. To enable Java scripting, Java SE 6 supports JSR 223, a scripting framework that provides scripting language access to Java internals. You can locate scripting engines and invoke them to run scripts at runtime. The Scripting API allows you to provide Java support for the scripting language of your choice. In addition, the Web Scripting Framework allows script code to generate Web content within any Servlet container. For debugging, the Java Platform Debugger (JPDA) has been enhanced to detect deadlocks and generate stack traces for monitor objects that are locked. In addition, Java SE 6 adds support to allow agents to attach to a running JVM for diagnostic purposes.

Application Management:

Java SE 6 enhances memory leak analysis and detection by including a full stack trace in the java.lang.OutOfMemory exception and generating a fatal error log when the heap is full. In addition, a new JVM option allows you to run a script when the heap is full.

JMX Monitoring API allow an application to send events when MBean attribute values pass specified thresholds.

Web Services:

Java SE 6 includes a few APIs to support Web services. The XML Digital Signatures API allows you to secure Java-based Web services by performing cryptographic operations on XML data.
The Java-XML Web Service (JAX-WS) 2.0 API updates the library formerly named JAX-RPC.
Improvements to Java-XML Binding (JAXB) 2.0 include XML schema support and class binding to a schema.
Lastly, the Streaming API for XML (STaX) provides a bi-directional API to read and write XML via a stream of events, including the ability to skip sections, and focus on sub-sections of documents.

Security:

Java SE 6's security offerings include GSS/Kerberos integration, Java Authentication and Authorization Service (JAAS) for LDAP authentication, and a security certificate request framework that allows Java applications to request secure certificates over a number of protocols.

Desktop Improvements:

Java has been regarded as an excellent language for server-based software, also for desktop GUI applications. The result is not only improved GUI performance in Java SE 6, but also improvements in the behavior of Java GUI applications.

Many of the new desktop features in Java SE 6 are based on the JDesktop Integration Components (JDIC) project. The JDIC project gives Java applications access to features available on the native OS desktop, such as the browser, email editor, file-type associations, the system tray, application launching, and printing. The following are some of the more prominent Java desktop improvements in Java SE 6:

* Splash screen support—Splash screens inform a user that an application is starting while he waits. Java SE 6 adds support for splash screens that can be displayed even before the JVM starts.

* Java Foundation Classes (JFC) and Swing Improvements:

o Java SE 6 leverages Windows APIs to both improve performance and ensure the Windows look-and-feel on current and future versions of Windows.
o It improves layout management to include customizable layout managers and includes other enhancements to simplify GUI component layout.
o It has vastly improved Swing drag-and-drop, making it customizable.
o True double-buffering provides quick, smooth graphic transitions.

* System Tray Support— Two new classes, SystemTray and TrayIcon, in the java.awt package allow you to add icons, tool tips, and pop-up menus to the Windows or Gnome Linux system tray. The system tray is the desktop area shared by all applications, usually located in the lower-right corner. Actions and events allow your Java application to track mouse clicks on the items you place in the tray, and respond to those clicks.

* Improved print support for JTable

* Java 2D enhancements—Improvements have been made to text display quality, especially on LCD monitors. Integration with the host desktop's font anti-aliasing settings ensures consistent text rendering.

* The new java.awt.Desktop API—The new Java SE 6 Desktop package aims to make Java UI applications. With this package, Java applications can launch the default browser and email client, and integrate with common desktop applications to open, edit, and print files of specific types. The Desktop package offers this ability through action events (Desktop.Action) that you can integrate into your applications.

* Internationalization—Java SE 6 supports "plugability" for some locale-specific features, such as date formatting, Unicode text normalization, and resource bundles.

A Java Desktop Revolution:

While Java SE 6 provides too many individual feature additions, improvements, and bug fixes to be listed here, this article provides a roadmap to this upcoming, important, Java release. The improvements span so many aspects of the standard edition of Java that all stakeholders will be affected, including those intimate with Java Enterprise Edition.

Java SE 6 has the potential to be as revolutionary to the desktop as Java 2 was to the server. It's best to be prepared for this storm now, and position yourself to cash in on the potential rewards available to the early adopters.

Read more...

Thursday, November 6, 2008

Sams teach Yourself EJB in 21 days eBook

Enterprise applications must be scalable, portable, and secure. That’s what Java 2 Platform, Enterprise Edition (J2EE) is all about: a complete architecture and framework for developing and deploying server-side Java components. Enterprise JavaBeans (EJB) is the heart of the J2EE platform. It enables simplified development of distributed Java applications. Other J2EE run-time services, such as JNDI, JDBC, and JMS, are vital in completing the full picture of server-side component architecture.
This book focuses primarily on teaching the EJB technology, but it also covers otherJ2EE technologies that are essential to understanding EJBs. You’ll be introduced to all aspects of EJB development using the most current version of the specification.

Download Sams teach Yourself EJB in 21 days

Read more...

Java 2: The Complete Reference 5th Edition eBook

Author: Herbert Schildt
This book gives nice coverage of the Java language with particular focus on the new Collections. and also coverage of threads and several chapters devoted to user interface related matters - swing, servlets, applets, etc. What is particularly refreshing with this book is the large number of complete and reasonable examples.This book is the most complete and up-to-date resource on Java from programming guru, Herb Schildt a must-have desk reference for every Java programmer.

Download Java2 The Complete Reference

Read more...

Java and SOAP eBook

Java with SOAP (Simple Object Access Protocol)

This book provides Java developers with an in-depth look at SOAP (the Simple Object Access Protocol) also covers the basics, SOAP features and capabilities, shows how to work with some of the more common Java APIs in the SOAP world Apache SOAP and GLUE also structure of a SOAP message, SOAP encoding, and building simple services using RPC and messaging.

Download Java and SOAP

Read more...

Java Programming on Linux eBook

Java Programming on Linux is a detailed how-to book on using Java on a Linux operating system. Topics include installing and enabling a Java runtime environment under Linux, Java development in Linux, running Java applications and applets under Linux, using Java with Linux-based Web servers, using Sun Components JCE and JAI in Linux, using Sun Environments Personal Java, Embedded Java, and Jini in Linux, and using JNI to Link Java and Native Capabilities.
Includes Aspects of developing and deploying Java software on computers that run the Linux operating system; the Sun Java Development Kit (JDK) as it applies to Linux and how versions 1.1 and 1.2 of the JDK differ in that environment; documentation of Linux development and runtime tools for Linux.

Download Java Programming on Linux

Read more...

Java J2EE Job Interview Questions eBook

This Book features all faq's on Java/J2EE Technolgies. Much useful for Interviews.

Download Java J2EE Job Interview Companion eBook

Read more...

Wednesday, November 5, 2008

Java Design Pattern A Tutorial eBook


Author: James Cooper
Design patterns describe how objects communicate without become entangled in each other’s data models and methods. Keeping this separation has always been an objective of good OO programming, and if you
have been trying to keep objects minding their own business, you are probably using some of the common design patterns already. Design patterns began to be recognized formally in the early 1990s by Helm (1990) and Erich Gamma (1992), who described patterns incorporated in the GUI application framework, ET++.

Read more...

Java J2EE Design Patterns eBooks Tutorials



Core J2EE Patterns Best Practices & Design Strategies EBook

Patterns not only help you build simpler systems that work, but theyalso help you build beautiful programs. In a culture of time starvation,writing beautiful software is often impossible. That’s sad, for asprofessionals, we strive to build things of quality. By applying a goodset of patterns, it is possible to bring a degree of elegance in to yoursystems that might otherwise have been lacking.

Read more...

IBM WebSphere eBooks Tutorials

WebSphere Version 6.0Web Services Handbook

Download WebSphere 6.0 Web Services Handbook

IBM Tutorial for Websphere Studio Application

Download IBM Websphere Studio Application Tutorial


WebSphere 4.0 AEs Workbook for Enterprise JavaBeans(EJB) - 3rd Edition

Description: The goal of this WebSphere AE workbook is to discuss vendor specific requirements and best practices and introduce tools such as the WebSphere Application Assembly Tool, and the WebSphere Administration Console, all in the context of building and running the example programs for O'Reilly's Enterprise JavaBeans, 3rd edition.

Download WebSphere 4.0 for EJB

Read more...

Tuesday, November 4, 2008

Enterprise Java Beans (EJB)

Enterprise Java Beans:

Enterprise JavaBeans (EJB) technology is the server-side component architecture for Java Platform, Enterprise Edition (Java EE). EJB technology enables rapid and simplified development of distributed, transactional, secure and portable applications based on Java technology.

Bean can be called as a reusable component. Enterprise Java Bean is a bean designed to run inside an EJB server. EJB is supplemented by a deployment descriptor, an XML file which provides the container with information about how the bean is to be deployed.

EJB Roles:

Enterprise Bean Provider - application domain expert who writes the Java code and the deployment descriptor. Work product is ejb jar files.

Application Assembler - assembles beans into larger units and with other components such as JSP..etc and also producing jar files.

Deployer - installs the jar files in specific environment

Server provider - provides the environment to run EJBs in different servers such as BEA, IBM, Sun. etc.

Container provider - provides the thing the server runs in.

EJB class will interact with other EJBs via interfaces.

Different Types of EJB's:

Session Beans -- represent an interaction or work process which lies on behalf on the client.

Stateless Session Beans - No information will be retained by the object between method calls

Stateful Session Beans - Data will be retained by the object

Entity Beans - represent persistence objects, typically stored in a database.
They are of two types.

Container managed persistence -- Mean the server generates the necessary SQL to insert/update/delete data.

Bean managed persistence -- Programmer writes the necessary code

Message Beans -- process Java Message Service (JMS) messages

Interfaces in EJB:

Entity and Session Beans can support two kinds of client interfaces

Home interfaces Used to create, find and destroy bean instances this will be Obtained via a name (JNDI)

Business interface Provides business logic API, Obtained from home interfaces

Interface versions:

Remote interfaces can be used anywhere and are most flexible.

Local interfaces can only be used inside the EJB server but these are more efficient

Bean class have to implement SessionBean or EntityBean interfaces.

Remote interface will extend javax.ejb.EJBObject class

Home interface will extend javax.ejb.EJBHome class

Archive files:

Java archive (jar) files are used to package data for deployment
ear - Enterprise Archive file
war - Web archive file
rar - resource adapter

Read more...

Sunday, November 2, 2008

JAVA SERVER FACES (JSF)

JSF

A server side user interface component framework for Java-based web applications

A specification and reference implementation for a web application development framework

– Components
– Events
– Validators & converters
– Navigation
– Back-end-data integration

Struts and JSF can be used together

JSF provides Drag-and-drop UI components to build a web Application.

Next generation Web application framework based on component model

We can create JSF application by writing JSP pages yourself

JSF Basic Capabilities

* Extensible user interface (UI) component model

* Flexible rendering model

* Event and listener handling model

* Per-component validation framework

* Basic page navigation support

* Internationalization and accessibility

* Extensible Component and Rendering architecture

* Support for client device independence

* Huge vendor and industry support

JSF Concepts

UIComponent

Render-independent characteristics

Base class with standard behaviors

Standard UIComponent Subclasses

UICommand, UIForm, UIGraphic, UIInput, UIOutput, UIPanel,
UISelectBoolean, UISelectMany, UISelectOne

FacesEvent

Base class for request and application events

Validator

Base class for standard and application defined validators

Converter

Plug-in for String-Object conversion

FacesContext

– Servlet request, response, session
– JSF request, response trees
– Model reference expression evaluators

Syntax similar to the expression language of the JSP Standard Tag Library (JSTL) 1.x

Primary interface between components and the data provided by (or to) the application

JSF Key Concepts

Renderer

– Converts components to and from a specific markup language
– Supports render-dependent attributes on components
– May support more than one component type

RenderKit

– Library of Renderers
– Extensible at runtime
– Basic HTML RenderKit is part of the specification

JSF is based on:
– Servlet 2.3 (JSR-53)
– JSP 1.2 (JSR-53)
JSF must be synergistic with:
– JSTL 1.0 (JSR-52)
– Portals (JSR-168)
JSF is not part of J2EE 1.4 standard yet
– Will be considered for J2EE 5.0
– It is included in J2EE 1.4 SDK, however
JSF Built in classes

UIViewRoot

● UIViewRoot is a UIComponent that represents the root of the UIComponent tree.

● Serves as the root of the component tree,and as a place to hang per-view PhaseListeners

FacesContext

● Contains all of the per-request state information related to the processing of
a single JavaServer Faces request, and the rendering of the corresponding response.

● It is passed to, and potentially modified by,each phase of the request
processing lifecycle

PhaseListener

● An interface implemented by objects that wish to be notified at the beginning
and ending of processing for each standard phase of the request processing lifecycle

● You can provide your own implementation of PhaseListener and plug it
into the application for custom request handling – Ajax request handling

● Before and after each phase handling
– “around” semantics

Application Class

● Represents a per-web-application singleton object

● Maintains application wide objects

– set of supported locales
– converters
– validators

● Serves as a factory for creating components,converters, and validators
public abstract UIComponent createComponent(String componentType) throws FacesException

Read more...

JSP 2.1 Updates

Java Server Pages (JSP) 2.1

Jsp2.1 includes webtier technologies namely Java Standard Tag Library(JSTL) and JavaServerFaces(JSF) technology. Complete alignment of JavaServer Faces technology tags and JavaServer Pages (JSP) software code.

JSP 2.1 is Part of J2EE 5.0 and Dependant on JDK 1.4, Servlet 2.5. JSP 2.1 supports annotations for dependency injection on JSP tag handlers and context listeners. New features from Faces into JSP

Support for resource injection through annotations to simplify configuring access to resources and environment data

Expression Language

The expression language provides a way to simplify expressions in JSP. It is a simple language used for accessing implicit objects and Java classes, and for manipulating collections in an elegant manner. EL provides the ability to use run-time expressions outside of JSP scripting elements.

JavaServer Faces and JavaServer Pages each has its own expression language. The expression language included in JSP provides greater flexibility to the web application developer. But those who are working with JSF have found themselves unsatisfied by the JSP expression language.

New unified EL essentially represents a union of the JSP and JSF expression languages and largely benefits JSF technology. The unified EL has the following features:

* Deferred evaluation of expressions.
* Support for expressions that can set values and expressions that can invoke methods.
* Support for using JSTL iteration tags with deferred expressions
Evaluation of EL is categorized as immediate evaluation and deferred evaluation. Immediate evaluation means a JSP page evaluates the expression when the page is rendered. With immediate evaluation, all values are always read-only. JSP EL expressions take the form of ${imExpr}. JSP expressions are evaluated immediately.

Deferred evaluation means that the technology using the unified EL takes over the responsibility of evaluating the expression from the JSP engine and evaluates the expression at the appropriate time during the page lifecycle.

Compatibility

In JSP 2.1 technology, a deferred expression does not make sense in the context of template text because evaluation of an expression is always done immediately by the JSP container. Because no entity other than the JSP container processes template text, a deferred expression would always be left unevaluated if it were included in template text. So therefore, any page authors who have included the #{ character sequence in template text probably meant to use the ${} syntax instead. Acknowledging this fact, the JSP specification authors have mandated that the inclusion of #{ in template text triggers a translation error in JSP 2.1 technology.

Maintaining compatibility with earlier versions is critical for any Java EE platform release. For JSP 2.1 technology, the only backward compatibility issue involves the EL's new support of the #{ syntax that refers to deferred expressions. The #{ character sequence can create backward compatibility problems in two situations: when the sequence is included in template text or in attribute values.

Version requires these jars:
-> ant-1.6.5.jar

-> core-3.1.1.jar

-> jsp-2.1.jar

-> jsp-api-2.1.jar

Read more...
Blog Widget by LinkWithin

JS-Kit Comments

  © Blogger template Newspaper III by Ourblogtemplates.com 2008

Back to TOP