Thursday, November 29, 2012

include vs forward



RequestDispatcher.include()
RequestDispatcher.forward()
include method leaves the output stream open.

forward method will close the output stream after it has been invoked
the output stream remains open, so you can call on as many different files to generate client side markup that you need. So you can include two or three JSP files and even a Servlet in the chain of components that generate client based markup. When you use an include, the output stream is not closed after invocation.

If you are doing processing in a server side component, and then forward to a JSP or Servlet in order to generate markup for a client, once that JSP or Servlet has finished processing, you can no longer call on any other components to generate markup that can be sent to the client. Once you have performed a forward, markup generation for the current request and response cycle is finished.

 it sounds nice to have an open stream, and be able to call includes on multiple resources, but this typically is not a good practice. Having a server side controller invoking multiple resources for markup can get messy and be difficult to manage
 it is usually best to forward to a single server-side artifact and have it generate markup for the client, and simply accept the fact that the generation of client-side markup has completed.

Monday, November 12, 2012

Tomcat Access Logging


Setting up Logging

To setup access logging, edit the Tomcat server configuration file, ${tomcat_home}/conf/server.xml and uncomment the AccessLogValve:
        <Valve className="org.apache.catalina.valves.AccessLogValve"
                 directory="logs"  prefix="localhost_access_log." suffix=".txt"
                 pattern="common" resolveHosts="false"/>
By default the log files are created in the ${tomcat_home}/logs directory and roll over to a new file at midnight.
The log messages can be written in either of two standard web access log formats by setting the pattern attribute to common or combined. These appear to be the ones used by web log analysers. Other log formats can be specified with the pattern attribute.

Modifying the Log Format

We can extend the "common" and "combined" patterns by appending the response time for each request. To use this, set the
  • commonpattern="common"
  • common plus response timepattern="%h %l %u %t &quot;%r&quot; %s %b %D"
  • combinedpattern="combined"
  • combined plus response timepattern="%h %l %u %t &quot;%r&quot; %s %b &quot;%{Referer}i&quot; &quot;%{User-Agent}i&quot; %D"

Using FastCommonAccessLogValve

The FastCommonAccessLogValve has better performance than the AccessLogValve. If you are running a production system, you might consider switching to the FastCommonAccessLogValve. The main restriction is that only the "common" and "combined" log formats can be used.
        <Valve className="org.apache.catalina.valves.FastCommonAccessLogValve"
                 directory="logs"  prefix="localhost_access_log." suffix=".txt"
                 pattern="common" resolveHosts="false"/>


The Logging Output

Here is a sample entry from the motherlode logs, using the combined plus response time pattern.
Example log entry:
82.93.133.81 - joe [01/Jul/2007:08:44:38 -0600] "GET /thredds/dodsC/fmrc/NCEP/GFS/Global_0p5deg/offset/NCEP-GFS-Global_0p5deg_Offset_0.0
hr.dds HTTP/1.1" 200 32707 "null" "IDV/NetcdfJava/HttpClient" 2999
Example ValueMeaning
82.93.133.81client IP address
-not used
joeauthenticated username
[01/Jul/2007:08:44:38 -0600]request time
"GET ..."HTTP request verb and path
200HTTP response code
32707bytes transferred
"null"Referer
"IDV/NetcdfJava/HttpClient"client name
2999response time in msecs


Values for the pattern attribute are made up of literal text strings, combined with pattern identifiers prefixed by the "%" character to cause replacement by the corresponding variable value from the current request and response. The following pattern codes are supported:
  • %a - Remote IP address
  • %A - Local IP address
  • %b - Bytes sent, excluding HTTP headers, or '-' if zero
  • %B - Bytes sent, excluding HTTP headers
  • %h - Remote host name (or IP address if resolveHosts is false)
  • %H - Request protocol
  • %l - Remote logical username from identd (always returns '-')
  • %m - Request method (GET, POST, etc.)
  • %p - Local port on which this request was received
  • %q - Query string (prepended with a '?' if it exists)
  • %r - First line of the request (method and request URI)
  • %s - HTTP status code of the response
  • %S - User session ID
  • %t - Date and time, in Common Log Format
  • %u - Remote user that was authenticated (if any), else '-'
  • %U - Requested URL path
  • %v - Local server name
  • %D - Time taken to process the request, in millis
  • %T - Time taken to process the request, in seconds
  • %I - current request thread name (can compare later with stacktraces)
There is also support to write information from the cookie, incoming header, outgoing response headers, the Session or something else in the ServletRequest. It is modeled after the apache syntax:
  • %{xxx}i for incoming request headers
  • %{xxx}o for outgoing response headers
  • %{xxx}c for a specific request cookie
  • %{xxx}r xxx is an attribute in the ServletRequest
  • %{xxx}s xxx is an attribute in the HttpSession
The shorthand pattern name common (which is also the default) corresponds to '%h %l %u %t "%r" %s %b'.
The shorthand pattern name combined appends the values of the Referer and User-Agent headers, each in double quotes, to the common pattern described in the previous paragraph.


More information on the AccessLogValve and the pattern attribute can be found on the Tomcat Valve Configuration Reference.

Monday, November 5, 2012

Abstract class extends Abstract class and Interface extends Interface


Abstract class extends Abstract class

ComicsBook.java

abstract class ComicsBook {
     public abstract void book();
     public abstract void cartoons();
}

abstract class Marvel extends ComicsBook{ //Don’t have to implement any method of ComicsBook even though they are abstract

     public abstract void action();
}

UseAbstract.java
public class UseAbstract extends Marvel {//Have to implement all method of Marvel means also methods of ComicsBook

    
     @Override
     public void action() {
          // TODO Auto-generated method stub
         
     }

     @Override
     public void book() {
          // TODO Auto-generated method stub
         
     }

     @Override
     public void cartoons() {
          // TODO Auto-generated method stub
         
     };
}


Interface extends Interface 

Comics.java
public interface Comics {
     public void book();
     public void cartoons();
}


DCComics.java

public interface DCComics extends Comics{//Don’t have to implement any method of Comics even though they are abstract
     public void action();
}



UseInterface.java

public class UseInterface implements DCComics {//Have to implement all method of DCComics means also methods of Comics

    
     @Override
     public void action() {
          // TODO Auto-generated method stub
         
     }

     @Override
     public void book() {
          // TODO Auto-generated method stub
         
     }

     @Override
     public void cartoons() {
          // TODO Auto-generated method stub
         
     };
}

Friday, November 2, 2012

Java Generic


Replace the specific type String with a type parameter such as T, and we add the type parameter to the name of the class:

class Queue<T> {
   private LinkedList<T> items = new LinkedList<T>();
   public void enqueue(T item) {
      items.addLast(item);
   }
   public T dequeue() {
      return items.removeFirst();
   }
   public boolean isEmpty() {
      return (items.size() == 0);
   }
}
the type parameter T is used just like any regular type name. It's used to declare the return type for dequeue, as the type of the formal parameter item in enqueue, and even as the actual type parameter in LinkedList<T>. Given this class definition, we can use parameterized types such as Queue<String> and Queue<Integer> and Queue<JButton>. That is, the Queue class is used in exactly the same way as built-in generic classes like LinkedList and HashSet.

Note that you don't have to use "T" as the name of the type parameter in the definition of the generic class. Type parameters are like formal parameters in subroutines. You can make up any name you like in the definition of the class. The name in the definition will be replaced by an actual type name when the class is used to declare variables or create objects. If you prefer to use a more meaningful name for the type parameter, you might define the Queue class as:

class Queue<ItemType> {
   private LinkedList<ItemType> items = new LinkedList<ItemType>();
   public void enqueue(ItemType item) {
      items.addLast(item);
   }
   public ItemType dequeue() {
      return items.removeFirst();
   }
   public boolean isEmpty() {
      return (items.size() == 0);
   }
}
Changing the name from "T" to "ItemType" has absolutely no effect on the meaning of the class definition or on the way that Queue is used.

Generic interfaces can be defined in a similar way. It's also easy to define generic classes and interfaces that have two or more type parameters, as is done with the standard interface Map<T,S>. A typical example is the definition of a "Pair" that contains two objects, possibly of different types. A simple version of such a class can be defined as:
class Pair<T,S> {
   public T first;
   public S second;
   public Pair( T a, S b ) {  // Constructor.
      first = a;
      second = b;
   }
}


This class can be used to declare variables and create objects such as:

Pair<String,Color> colorName = new Pair<String,Color>("Red", Color.RED);
Pair<Double,Double> coordinates = new Pair<Double,Double>(17.3,42.8);

Note that in the definition of the constructor in this class, the name "Pair" does not have type parameters. You might have expected "Pair<T,S>. However, the name of the class is "Pair", not "Pair<T,S>, and within the definition of the class, "T" and "S" are used as if they are the names of specific, actual types.

 Note in any case that type parameters are never added to the names of methods or constructors, only to the names of classes and interfaces.
We need to replace the specific type String in the definition of the method with the name of a type parameter, such as T. However, if that's the only change we make, the compiler will think that "T" is the name of an actual type, and it will mark it as an undeclared identifier. We need some way of telling the compiler that "T" is a type parameter. That's what the "<T>" does in the definition of the generic class "class Queue<T> { ...". For a generic method, the "<T>" goes just before the name of the return type of the method:
public static <T> int countOccurrences(T[] list, T itemToCount) {
   int count = 0;
   if (itemToCount == null) {
      for ( T listItem : list )
         if (listItem == null)
            count++;
   }
   else {
      for ( T listItem : list )
         if (itemToCount.equals(listItem))
            count++;
   }
   return count;
}  
The "<T>" marks the method as being generic and specifies the name of the type parameter that will be used in the definition. Of course, the name of the type parameter doesn't have to be "T"; it can be anything. (The "<T>" looks a little strange in that position, I know, but it had to go somewhere and that's just where the designers of Java decided to put it.)
The countOccurrences method operates on an array. We could also write a similar method to count occurrences of an object in any collection:
public static <T> int countOccurrences(Collection<T> collection, T itemToCount) {
   int count = 0;
   if (itemToCount == null) {
      for ( T item : collection )
         if (item == null)
            count++;
   }
   else {
      for ( T item : collection )
         if (itemToCount.equals(item))
            count++;
   }
   return count;
}
Since Collection<T> is itself a generic type, this method is very general. It can operate on an ArrayList of Integers, a TreeSet of Strings, a LinkedList of JButtons, ....
Type Wildcard
Let's start with a simple example in which a wildcard type is useful. Suppose that Shape is a class that defines a method public void draw(), and suppose that Shape has subclasses such asRect and Oval. Suppose that we want a method that can draw all the shapes in a collection of Shapes. We might try:
public static void drawAll(Collection<Shape> shapes) {
   for ( Shape s : shapes )
      s.draw();
}
This method works fine if we apply it to a variable of type Collection<Shape>, or ArrayList<Shape>, or any other collection class with type parameter Shape. Suppose, however, that you have a list of Rects stored in a variable named rectangles of type Collection<Rect>. Since Rects are Shapes, you might expect to be able to call drawAll(rectangles). Unfortunately, this will not work; a collection of Rects is not considered to be a collection of Shapes! The variable rectangles cannot be assigned to the formal parameter shapes. The solution is to replace the type parameter "Shape" in the declaration of shapes with the wildcard type

"? extends Shape":


public static void drawAll(Collection<? extends Shape> shapes) {
   for ( Shape s : shapes )
      s.draw();
}

The wildcard type "? extends Shape" means roughly "any type that is either equal to Shape or that is a subclass of Shape". When the parameter shapes is declared to be of typeCollection<? extends Shape>, it becomes possible to call the drawAll method with an actual parameter of type Collection<Rect> since Rect is a subclass of Shape and therefore matches the wildcard. We could also pass actual parameters to drawAll of type ArrayList<Rect> or Set<Oval> or List<Oval>. And we can still pass variables of type Collection<Shape> orArrayList<Shape>, since the class Shape itself matches "? extends Shape". We have greatly increased the usefulness of the method by using the wildcard type.

One final remark: The wildcard type "<?>" is equivalent to "<? extends Object>". That is, it matches any possible type. For example, the removeAll() method in the generic interfaceCollections<T> is declared as
public boolean removeAll( Collection<?> c ) { ...
This just means that the removeAll method can be applied to any collection of any type of object.

Thursday, November 1, 2012

Inversion of Control




IoC is one of the techniques used to wire services or components to an application program.

By definition, IoC is “A software design pattern and set of associated programming techniques in which the flow of control of a system is inverted in comparison to the traditional interaction mode.” 


In Java there are several basic techniques to implement inversion of control. These are:
1. using a factory pattern
2. using a service locator pattern
3. using a contextualized lookup
4. using a dependency injection,
 for example:
·         a constructor injection
·         a setter injection
·         an interface injection


Simply stated, in IoC, instead of an application calling the framework, it is the framework that calls the components specified by the application.This approach is similar to the one that Hollywood agents adopt with their clients. It is sometimes known as “Don’t call me, I will call you.” This is why IoC is also known as the Hollywood approach.

IoC is a broad and generic term

There are three forms or styles of Dependency Injection. 
The aspect of IoC that the Spring Framework uses is "Injection of required resources or dependency at Run-time into the dependent resource," which is also known as Dependency Injection. 

Hence, the service provided by the IoC container of Spring is Dependency Injection. 


They are:
1.  Constructor Injection [Spring Framework directly supports]
2.  Setter Injection [Spring Framework directly supports]
3.  Interface Injection [Spring Framework indirectly supports]


1.  Constructor Injection: In Constructor Injection, an IoC container uses the constructor to inject the dependency. All the dependencies, whether they are simple values or references to other objects, are declared in the constructor. One of the advantages of Constructor Injection is that all the dependencies are declared in one go. This also helps in understanding whether the class depends on too many services.

2.  Setter Injection: This form of Dependency Injection uses Setters, also known as mutators (because they change the value of the corresponding instance variables), to inject the required resources or dependencies. In other words, each of the objects that the class depends upon will have a setter and the IoC container will use the setters to provide the resource at run-time.

The main difference between Constructor Injection and Setter Injection 
Constructor Injection, the handing over of the dependencies takes place during instantiation of the dependent object
 Setter Injection, the handing over of the dependencies takes place after instantiation of the dependent object

 The Spring Framework favors Setter Injection over Constructor Injection.

3.  Interface Injection: Interface Injection provides the concrete implementations of an interface to the dependent object according to the configuration. The main difference between Interface Injection and the previous two is that in Interface Injection, any of the implementations of the interface can be injected, whereas with the other two, the object of the class specified is injected. Spring does not provide direct support for Interface Injection.


When to use Dependency Injections?
There are different scenarios where you Dependency Injections are useful.
  • You need to inject configuration data into one or more component.
  • You need to inject the same dependency into multiple components.
  • You need to inject different implementation of the same dependency.
  • You need to inject the same implementation in different configuration.
  • You need some of the services provided by container.
When you should not use Dependency Injection?
There were scenarios where you don’t need dependency injections e.g.
·         You will never need a different implementation.
·         You will never need different configurations.