Tuesday, October 16, 2012

Serialization Vs Externalizable

Serializable is a marker interface and doesn't contain any methods whereas Externalizable interface contains two methods: writeExternal(ObjectOutput) and readExternal(ObjectInput). But, the main difference between the two is that Externalizable interface provides complete control to the class implementing the interface over the object serialization process whereas Serializable interface normally uses default implementation to handle the object serialization process.

While implementing
Serializable, you are not forced to define any method as it's a marker interface. However, you can use the writeObject or readObject methods to handle the serilaization process of complex objects. But, while implementing Externalizable interface, you are bound to define the two methods: writeExternal and readExternal and all the object serialization process is solely handled by these two methods only.

In case of
Serializable interface implementation, state of Superclasses are automatically taken care by the default implementation whereas in case of Externalizable interface the implementing class needs to handle everything on its own as there is no default implementation in this case.

when to use what?

If everything is automatically taken care by implementing the
Serializable interface, why would anyone like to implement the Externalizable interface and bother to define the two methods? Simply to have the complete control on the process. OKay... let's take a sample example to understand this. Suppose we have an object having hundreds of fields (non-transient) and we want only few fields to be stored on the persistent storage and not all. One solution would be to declare all other fields (except those which we want to serialize) as transient and the default Serialization process will automatically take care of that. But, what if those few fields are not fixed at design tiime instead they are conditionally decided at runtime. In such a situation, implementing Externalizable interface will probably be a better solution. Similarly, there may be scenarios where we simply don't want to maintain the state of the Superclasses (which are automatically maintained by the Serializable interface implementation).

Which has better performance - Externalizable or Serializale?

In most of the cases (or in all if implemented correctly), Externalizable would be more efficient than Serializable for the simple reason that in case of Externalizable the entire process of marshalling, un-marshalling, writing to the stream, and reading back from stream, etc. is
under your control i.e., you got to write the code and you can of course choose the best way depending upon the situaton you are in. In case of Serializable, this all (or at least most of it) is done implicitly and the internal implementation being generic to support any possible case, can ofcourse not be the most efficient. The other reason for Serializable to be less efficient is that in this case several reflective calls are made internally to get the metadata of the class. Of course, you would not need any such call is needed in case Externalizable.

However, the efficiency comes at a price. You
lose flexibility because as soon as your class definition changes, you would probably need to modify your Externaliable implementation as well. Additionally, since you got to write more code in case Externalizable, you increase the chances of adding more bugs in your application.

Another disadvantage of Externalizable is that you got to have the class to interpret the stream as the stream format is an opaque binary data. Normal Serialization adds field names and types (this why reflective calls are needed here) into the stream, so it's possible to re-construct the object even without the availability of the object's class. But, you need to write the
object reconstruction code yourself as Java Serialization doesn't provide any such API at the moment. The point is that in case of Serialzable you can at least write your code as the stream is enriched with field names and types whereas in case Externalizable the stream contains just the data and hence you can't unless you use the class definition. As you can see Serializable not only makes many reflective calls, but also puts the name/type info into the stream and this would of course take some time making Serialzable slower than the corresponding Externalizable process where you got to stuff only the data into the stream.

Struts 2 Flow

  • When a client request is given, a web container will receive request
  • Web container loads web.xml and verifies whether the url-patterns are verified or not, if matches web-container transfer the request to FilterDispatcher
  • FilterDispatcher hand overs the request to ActionProxy, it is a proxy class which is responsible to apply before and after services to original business logic
  • ActionProxy contacts ConfiguraionManager class, to know the suitable Action for the request and the needed services for the request
  • ConfigurationManager class loads structs.xml and provides the required information back to ActionProxy
  • ActionPorxy delegates the request along with its information to ActionInvocation
  • ActionInvocation executes the interceptors added to an Action from 1 – N, after that it will calls the business logic implemented from N – 1 in reverse order
  • ActionInvocation receives finally result produced by an action aclass
  • ActionProxy transfers the result back to FilterDispatcher
  • FilterDispatcher selects an appropriate view, basing on the result
  • Finally FilterDispatcher uses RequestDispatchers forwarding mechanism and forward a view as a response back to the client

Tuesday, October 9, 2012

Life cycle of Servlet

The life cycle of a servlet can be categorized into four parts:
  1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.
  2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.

    The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.
  3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.
  4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet  releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection. 
Referance: roseindia

Monday, October 8, 2012

Exception

What is Exception ?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

In java it is possible to define two categories of Exceptions and Errors.
  • JVM Exceptions: These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException...
  • Programmatic exceptions: These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalState...
What is difference between Error and Exception?  
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.
While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)

What is difference between ClassNotFoundException and NoClassDefFoundError?
A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible. 
Consider if NoClassDefFoundError occurs which is something like
java.lang.NoClassDefFoundError
src/com/TestClass 
does not mean that the TestClass class is not in the CLASSPATH. It means that the class TestClass was found by the Class Loader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the Class Loader. So to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.
 

Basic java interview Questions

Can you declare a class as ‘private’ ?
No, if we declare a class as private , then it is not available to java compiler and hence a compile time error occurs, But inner classes can be declared as private.

What is the difference between instance variables and class variables(static variables) ?
1. An Instance variable is a variable whose separate copy is availabe to each object. A class variable is a variable whose single copy in memory is shared by all objects.
2. Instance variables are created in the objects on heap memory. Class variables are stored on method area.

Why instance Variables are not available to static methods ?
After executing static methods, JVM creates the objects. So the instance variables of the objects are not available to static methods.

Is it possible to compile and run a Java program without writing main( ) method ?
Yes , it is possible by using a static block in the Java program.

What is anonymous inner class ?
It is an inner class whose name is not written in the outer class and for which only one object is created.

What is method signature ?
Method signature represents the method name along with method parameters.

JSP Life Cycle

A JSP life cycle is similar to Servlet life cycle.JSP life cycle can be defined as the entire process from its creation till the destruction.

Four things is happen when we send a request for JSP are as follows:
1) Compilation
2) Initialization
3) Execution
4) Destroy - Cleanup

-->
The three major phases of JSP life cycle are very similar to Servlet Life Cycle
1) jspInit()
2)  _jspService()
3) jspDestroy()
-->

(1) JSP Compilation:

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps:
  1. Parsing the JSP.
  2. Turning the JSP into a servlet.
  3. Compiling the servlet.

(2) JSP Initialization:

When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method:
public void jspInit(){
  // Initialization code...
}
Typically initialization is performed only once and as with the servlet init method, you generally initialize database connections, open files, and create lookup tables in the jspInit method.

(3) JSP Execution:

This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows:
void _jspService(HttpServletRequest request, HttpServletResponse response)
{
   // Service handling code...
}
The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods i.e. GET, POST, DELETE etc.

(4) JSP Cleanup:

The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files.
The jspDestroy() method has the following form:
public void jspDestroy()
{
   // Your cleanup code goes here.
}

Friday, October 5, 2012

Interface

What is an interface ?
An interface is a specification of method prototypes, All the methods of the interface are public and abstract.


Why the methods of interface are public and abstract by default ?
Interface methods are public since they should be available to third party vendors to provide implementation. They are abstract because their implementation is left for third party vendors.


Can you implement one interface from another ?
No, we can’t implementing an interface means writing body for the methods. This can not be done again in an interface, since none of the methods of the interface can have body.

Can you write a class within an interface ?
Yes, it is possible to write a class within an interface.




What do you call the interface without any members ?

An interface without any members is called marking interface or tagging interface. It marks the class objects for a special purpose. For example, Clonable(java.lang) and Serializable(java.io) are two marking interfaces. Clonable interface indicates that a particular class objects are cloneable while Serializable interface indicates that a particular class objects are serializable.

What is abstraction ?

Hiding the unnecessary data from the user and expose only needed data is of interest to the user.
A good example for abstraction is a car. Any car will have some parts like engine, radiator, mechanical and electrical equipment etc. The user of the ca r (driver) should know how to drive the car and does not require any knowledge of these parts. For example driver is never bothered about how the engine is designed and the internal parts of the engine. This is why, the car manufacturers hide these parts from the driver in a separate panel, generally at the front.

Overloading and Overriding

What is method overloading ?
Writing two or more methods in the same class in such a way that each method has same name but with different method signatures – is called method overloading.
What is method overriding ?
Writing two or more methods in super and sub classes such that the methods have same name and same signature is called method overriding.


Method Overloading
Writing two or more methods with the same name but with different signatures is called method overloading.
Method overloading is done in the same class.
In method overloading, method return type can be same or different.
JVM decides which method is called depending on the difference in the method signatures.
Method overloading is done when the programmer wants to extend the already available features.
Method overloading is code refinement. Same method is refined to perform a different task.

Method Overriding
Writing two or more methods with the same name and same signatures is called method overriding.
Method overriding is done in super and sub classes.
In method overriding method return type should also be same.
JVM decides which method is called depending on the data type (class) of the object used to call the method.
Method overriding is done when the programmer wants to provide a different implementation(body) for the same feature.
Method overriding is code replacement. The sub class method overrides(replaces) the super class method.

What is the difference between dynamic polymorphism and static polymorphism ?

Dynamic polymorphism is the polymorphism existed at run-time. Here, Java compiler does not understand which method is called at compilation time. Only JVM decides which method is called at run-time. Method overloading and method overriding using instance methods are the examples for dynamic polymorphism.

Static polymorphism is the polymorphism exhibited at compile time. Here, Java compiler knows which method is called. Method overloading and method overriding using static methods; method overriding using private or final methods are examples for static polymorphism.

Wednesday, October 3, 2012

Native Queries with Hibernate Annotations

Hibernate EntityManager implements the programming interfaces and lifecycle rules as defined by the EJB3 persistence specification. Together with Hibernate Annotations, this wrapper implements a complete (and standalone) EJB3 persistence solution on top of the mature Hibernate core. In this post I will describe how map native queries (plain SQL) using Hibernate Annotations. Hibernate Annotations supports the use of Native queries through the @NamedNativeQuery and the @SqlResultSetMapping annotations.
  • @NamedNativeQuery: Specifies a native SQL named query.
  • @SqlResultSetMapping: Used to specify the mapping of the result of a native SQL query.
You will not need any EJB container support. At a minimum, you will need Hibernate core and Hibernate Annotations. The entire list of required Jar files is provided at the end.
  1. The Hibernate Configuration File: Nothing new here. Except that there are no mappings defined. I used programmatic declaration of mapping for this example as shown in the following steps.
    <!DOCTYPE hibernate-configuration PUBLIC
     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration>
     <session-factory>
      <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
      <property name="connection.url">jdbc:oracle:thin:@localhost:1521/orcl</property>
      <property name="connection.username">scott</property>
      <property name="connection.password">tiger</property>
      <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
      <property name="hibernate.current_session_context_class">thread</property>
     </session-factory>
    </hibernate-configuration>
    hibernate.cfg.xml
  2. The Entity class:
    package data;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.EntityResult;
    import javax.persistence.FieldResult;
    import javax.persistence.Id;
    import javax.persistence.NamedNativeQuery;
    import javax.persistence.SqlResultSetMapping;
    
    @Entity
    @SqlResultSetMapping(name = "implicit",
     entities = @EntityResult(entityClass = data.Employee.class))
    @NamedNativeQuery(name = "implicitSample",
     query = "select e.empno empNumber, e.ename empName, e.job empJob,
     e.sal empSalary, salg.grade empGrade from emp e, salgrade salg 
    where e.sal between salg.losal and salg.HISAL", resultSetMapping = "implicit")
    
    //@SqlResultSetMapping(name = "explicit", 
    entities = { @EntityResult(entityClass = data.Employee.class, fields = { 
    //    @FieldResult(name = "empNumber", column = "empno"), 
    //    @FieldResult(name = "empName", column = "ename"),
    //    @FieldResult(name = "empJob", column = "job"), 
    //    @FieldResult(name = "empSalary", column = "sal"), 
    //    @FieldResult(name = "empGrade", column = "grade") }) })
    //@NamedNativeQuery(name = "implicitSample", 
    //    query = "select e.empno empno, e.ename ename, e.job job, e.sal sal, salg.grade grade
     from emp e,
     salgrade salg where e.sal between salg.losal and salg.HISAL", 
    resultSetMapping = "explicit")
    public class Employee {
    
     private String empNumber;
    
     private String empName;
    
     private String empJob;
    
     private Double empSalary;
    
     private int empGrade;
    
     @Column
     @Id
     public int getEmpGrade() {
       return empGrade;
     }
    
     public void setEmpGrade(int empGrade) {
       this.empGrade = empGrade;
     }
    
     @Column
     public String getEmpJob() {
       return empJob;
     }
    
     public void setEmpJob(String empJob) {
       this.empJob = empJob;
     }
    
     @Column
     public String getEmpName() {
       return empName;
     }
    
     public void setEmpName(String empName) {
       this.empName = empName;
     }
    
     @Column
     public String getEmpNumber() {
       return empNumber;
     }
    
     public void setEmpNumber(String empNumber) {
       this.empNumber = empNumber;
     }
    
     @Column
     public Double getEmpSalary() {
       return empSalary;
     }
    
     public void setEmpSalary(Double empSalary) {
       this.empSalary = empSalary;
     }
    
    }
    Employee.java
    • The implitic mapping (the uncommented @NamedNativeQuery and @SqlResultSetMapping declarations are used for implicitly mapping the ResultSet to the entity class. Note that the SQL column names match the field names in the class. If the names do not match then you can set the name attribute of the @Column annotation to the column name in the query.
    • The commented @NamedNativeQuery and the @SqlResultSetMapping declarations explicitly map the fields to the columns. This will come in handy when using joins and composite keys etc.
    • Note the package definitions refer to javax.persistence and not the hibernate packages. If the packages are not declared properly, you will most likely end up with some exceptions like the following
      org.hibernate.hql.ast.QuerySyntaxException: Employee is not mapped.
      While there are other causes for this exception, the package declarations did cause a little trouble for me.
  3. The Client:
    import java.util.List;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import org.hibernate.cfg.Configuration;
    
    import data.Employee;
    
    public class Client {
    
     public static void main(String[] args) {
       Configuration config = new AnnotationConfiguration()
    .addAnnotatedClass(Employee.class).configure();
    
       SessionFactory sessionFactory = config.buildSessionFactory();
       Session session = sessionFactory.getCurrentSession();
    
       List result = null;
       try {
         session.beginTransaction();
    
         result = session.getNamedQuery("implicitSample").list();
         System.out.println("Result size : " + result.size());
         session.getTransaction().commit();
       } catch (Exception e) {
         e.printStackTrace();
       }
       System.out.println(result.size());
     }
    
    }

  4. Jar Files: The following jar files need to be included in the classpath
    hibernate3.jar
    commons-collections-2.1.1.jar
    antlr-2.7.6.jar
    commons-logging-1.0.4.jar
    hibernate-annotations.jar
    ejb3-persistence.jar
    hibernate-commons-annotations.jar
    dom4j-1.6.1.jar
    ojdbc14.jar
    jta.jar
    log4j-1.2.11.jar
    xerces-2.6.2.jar
    xml-apis.jar
    cglib-2.1.3.jar
    asm.jar
     
    Reference: java-x.blogspot.in