Monday, March 7, 2011

How To Use Apache Log4j Logging API in your Application?

Logging in the context of application development includes inserting statements into the program that provide some kind of output information that is useful to the developer in debuggging process and improve their code or test it’s functionality.
For Logging,Apache has released a project called log4j.To get started with using it in your application.
First download the
latest version here and follow the instructions below:
1. Add log4j’s jar(log4j-x.x.xx.jar where x.x.xx is the version of the release you’ve downloaded) file to your application’s classpath.


2. Create a file named “log4j.properties” and place it in the default package of your source code(the root folder where all your code resides). Copy the following lines in it:

# Log levels
# Uncomment the following line to enable full loggin for every class
#log4j.rootLogger=trace, stdout, R
log4j.logger.com.test.logging=trace, stdout, R


# Console appender configuration
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n


# Rolling File Appender
log4j.appender.R=org.apache.log4j.RollingFileAppender
# Path and file name to store the log file.
log4j.appender.R.File=./logs/applog.log
log4j.appender.R.MaxFileSize=500KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
# Rolling File Appender layout
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %c - %p - %m%n

Here is a explanation of what the above properties do:
“log4j.logger.xxx” controls the loggers, where xxx is the package for which you want to set log levels.
The line
log4j.logger.com.test.logging=trace, stdout, R
means that you want every class under the com.test.logging package to have a logging level of trace, and output the log to the standard output(the console) using a Console Appender named stdout and to a file using a Rolling File Appender named R.

After that you define the appenders mentioned earlier and set their properties.
The lines
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) – %m%n
define the ConsoleAppender named stdout, set it’s layout to PatternLayout and then assign a pattern for the output.

Thursday, March 3, 2011

What is the difference between GET and POST methods?

GET and POST methods are usually used to sent back information from browser(HTTP client) to web server.
Imagine that you have a form on a HTML page and clicking the "submit" button sends the data in the form back to the server, as "name=value" pairs.

    GET method:

1.All the name value pairs are submitted as a query string in URL.
2.It's not secured as it is visible in plain text format in the Location bar of the web browser.
3.As the data transfers through address bar (URL) there are some restrictions in using space, some characters like ampersand (&) etc in the GET method of posting data.
4.Length of the string is restricted.
5.If method is not mentioned in the Form tag, this is the default method used.
6.If get method is used and if the page is refreshed it would not prompt before the request is submitted again.
7.One can store the name value pairs as bookmark and directly be used while sharing with others - example search results.
Data is always submitted in the form of text
8.If the response of the page is always same for the posted query then use GET example database searches

    POST method:

1.All the name value pairs are submitted in the Message body of request.
2.Length of the string(data submitted) is not restricted.
3.It is secure because name value pairs not seen on the address bar
4.If post method is used and if the page is refreshed it would prompt before the request is submitted again.
5.If the request involves a form with side effects(ie.database changes) then use post method.

cheers,
@Varaprasad!!!

Tuesday, March 1, 2011

Parsing a Simple Command line containing optional and required arguments

I used Apache Commons CLI to parse the program arguments.
First,populate an Options object to configure command-line parsing.
Pass the Options class and a String[] of arguments to a CommandLineParser, which parses and returns a CommandLine object capturing the supplied options and parameters(arguments).

For the purposes of this , assume that am attempting to parse a command line with three optional arguments: -h, -v, and -f .
-h prints out a simple help message with usage information and available command-line options
-v runs the program with verbose logging
-f sends the output of the application to a file.
To parse this command line, our main( ) method would resemble the following code:


import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.CommandLine;
public class CommandLineSample {

public static void main(String[] args) throws Exception {
// Create a Parser
CommandLineParser parser = new BasicParser();
Options options = new Options( );
options.addOption("h", "help", false, "Print this usage information");
options.addOption("v", "verbose", false, "Print out VERBOSE information");
options.addOption("f", "file", true, "File to save program output to");
// Parse the program arguments
CommandLine commandLine = parser.parse( options, args );
// Set the appropriate variables based on supplied options
boolean verbose = false;
String file = "";
if( commandLine.hasOption('h') ) {
System.out.println( "Help Message");
System.exit(0);
}
if( commandLine.hasOption('v') ) {
verbose = true;
}
if( commandLine.hasOption('f') ) {
file = commandLine.getOptionValue('f');
}
}

}
The Options object tells the CommandLineParser to expect three arguments: -h, -v, and -f.
The first argument to options.addOption( ) is the short name or abbreviation of the option, and the second argument is the long name of the argument.
When the long name of an option is specified, either may be used as program arguments.
For example, a command line specifying short-name arguments, -h -v -f test.xml, is equivalent to a command line specifying long-name arguments, --help --version --file test.xml, and both short- and long-name arguments may be mixed in the same command line.
The third argument to options.addOption() specifies whether the option takes a parameter;
in the previous example, only the file option expects a parameter. The fourth parameter is a String containing a description of the option for a user.

Setting Up Apache Commons CLI for Project

To use Commons CLI 1.1 in a Maven project, add the following dependency to your project's pom.xml:

    Adding a Dependency on Commons CLI

 <dependency>
  <groupid>commons-cli</groupid>
  <artifactid>commons-cli</artifactid>
  <version>1.1</version>
 </dependency>


For more information about the Commons CLI project, see the Commons CLI project page at http://commons.apache.org/cli

Monday, February 28, 2011

Implementation of Singleton design pattern

I will explain the implementation with the following steps

Step 1: Provide a default Private constructor

public class SingletonDemo{

// Note that the constructor is private
private SingletonDemo() {
// Optional Code
}
}


Step 2: Create a Method for getting the reference to the SingletonDemo



public class SingletonDemo {

private static SingletonDemo singletonDemo;
// Note that the constructor is private
private SingletonDemo() {
// Optional Code
}
public static SingletonDemo getSingletonDemo() {
if (singletonDemo == null) {
singletonDemo = new SingletonDemo();
}
return singletonDemo;
}
}
Then write a public static getter or access method to get the instance of the SingletonDemo Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.

Step 3: Make the Access method(getter) Synchronized to prevent Thread Problems.

public static synchronized SingletonDemo getSingletonDemo()

It might happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle.
In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below

SingletonDemo clonedObject = (SingletonDemo) obj.clone();

This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}

The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.

class SingletonClass {

private static SingletonClass singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private SingletonClass() {
// Optional Code
}
public static synchronized SingletonClass getSingletonObject() {
if (singletonObject == null) {
singletonObject = new SingletonClass();
}
return singletonObject;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}

public class SingletonObjectDemo {

public static void main(String args[]) {
// SingletonClass obj = new SingletonClass(); //Compilation error not allowed
SingletonClass obj = SingletonClass.getSingletonObject();
// Your Business Logic
System.out.println("Singleton object obtained");
}
}



cheers,
Varaprasad.

Design Patterns I Used

Java has several design patterns Singleton Pattern being the most commonly used.
Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process.
What it says??

This design patterns says that at any time there can be only one instance of object created by the JVM.

How it is done??

The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes).
A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.(called factory method)

One such scenario where it might prove useful is when we develop the help Module in a project.

Singletons can be used to create a Connection Pool. If programmers create a new connection object in every class that requires it, then its clear waste of resources. In this scenario by using a singleton connection class we can maintain a single connection object which can be used throughout the application.

Brief Talk on Design Patterns

What is a design patterns??

A Design patterns describes a proven solution to the frequently recurring design problems placing particular emphasis on the context surrounding the problem, and the consequences and impact of the solution.


Reasons to Use Design Patterns :
1.They are proven ie.solutions given by the experts in the domain
2.They are resuable ie. When a problem occcurs,don't have to reinvent the solution. just follow the proven solution
3.They are expressive.

You can tell whether a design pattern is applicable for a solution only after understanding the problem and applying it on own