Thursday, December 25, 2014

Log4J


Log4j – Introduction
Log4j is Fast, Flexible, Reliable and easily configurable Logging framework which is open source API distributed under Apache Software License, written in Java.
Log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages.
Log4j is highly configurable through external configuration files at runtime. It views the logging process in terms of levels of priorities and offers mechanisms to direct logging information to a great variety of destinations, such as a database, file, console, UNIX Syslog etc.
Log4j is easily configurable by external xml or property file and we can configure log4j in java class itself and log4j can produce log message in following formats.

1. File
2.      HTML
3.      Database
4.      Console

Components of Log4j
There three main components available in Log4j
1.    Logger – Responsible for capturing logging information.
2.      appenders – Responsible for publishing logging information in different formats.
3.      layouts – Responsible to format logging information in different styles.

Features of Log4j
1.      log4j is thread-safe.
2.      log4j is optimized for speed.
3.      log4j supports multiple output appenders per logger.
4.      Logging behavior can be set at runtime using a configuration file.
5.      log4j supports internationalization.
6.      log4j is not restricted to a predefined set of facilities.
7.      log4j is designed to handle Java Exceptions from the start.
8.      log4j uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL
9.      The target of the log output as well as the writing strategy can be altered by implementations of the Appender interface.
10.  log4j is fail-stop. However, altough it certainly strives to ensure delivery, log4j does not guarantee that each log statement will be delivered to its destination.

log4j Installation:
Log4j API package is distributed under the Apache Software License, a fully-fledged open source license certified by the open source initiative.
The latest log4j version, including full-source code, class files and documentation can be found at http://logging.apache.org/log4j/

log4j - Architecture
Log4j contains two types of objects.
1. Core Objects – These are mandatory required object to use log4j framework
2. Support Objects – These are optional objects which give support to core object.
1.      Core Objects: Core Objects are categorized in following three categories.

1.1  Logger : This is most important component of log4j.It is responsible for capture the logging information. Logger contains following levels.
1.1.1           Debug -  Useful for debug an application
1.1.2          Info - Provides informational messages
1.1.3           Warn - Provide the details of harmful events
1.1.4        Error – It provide the error and exception thrown in application and allow the application     continue its execution
1.1.5           Fatal - It provides the details severe error events like application may leads to abort
1.1.6          ALL - Used to turn on all logging level.
1.1.7          OFF - It is used to turn off all logging level

1.2  Appenders in log4 : The Appender is responsible to publish log messages in desired destination.Log4j provides following appenders.

1.2.1        Console Appender
1.2.2        DailyRollingFileAppender
1.2.3        FileAppender
1.2.4        RollingFileAppender
1.2.5        WriterAppender
1.2.6        SMTPAppender
1.2.7        WriterAppender
1.2.8        SocketAppender
1.2.9        SocketHubAppender
1.2.10    SyslogAppender
1.2.11    JDBCAppender
1.2.12    TelnetAppender
1.2.13    AppenderSkeleton
1.2.14    AsyncAppender
1.2.15    ExternallyRollingFileAppender
1.2.16    JMSAppender
1.2.17    LF5Appender
1.2.18    NTEventLogAppender
1.2.19    NullAppender

1.3  Layouts in log4j : Layout is responsible for how to format layout.Types of log4j layouts are given below
1.3.1        HTMLLayout – It format output in table formatted output in html file.
1.3.2        PatternLayout – It format the output in given conversion pattern with all supported appenders
1.3.3        SimpleLayout – It provide simple formatted output. It output will be log level followed by log message
1.3.4        XMLLayout – Its provide the xml formatted output

2.      Supported Objects :

2.1  Level Objects : The level objects defines the priority to logging. Here I listed the levels in their priority

2.1.1        ALL
2.1.2        TRACE
2.1.3        DEBUG
2.1.4        INFO
2.1.5        WARN
2.1.6        ERROR
2.1.7        FATAL
2.1.8        OFF

2.2  FILTER: Filter is object applied on logger and make further decision on whether information should be logged or not.

2.3  ObjectsRenderer : The object renderer objects provides the string representation of different objects passed to log4j framework. This object used by layout to prepare final logging information.

2.4  LogManager : The LogManager is responsible for reading configuration information from configuration file or class.


Sunday, May 11, 2014

Difference between Spring Singleton and JVM Singleton

The Java singleton is scoped by the Java class loader, the Spring singleton is scoped by the container context.
Which basically means that, in Java, you can be sure a singleton is a truly a singleton only within the context of the class loader which loaded it. Other class loaders should be capable of creating another instance of it (provided the class loaders are not in the same class loader hierarchy), despite of all your efforts in code to try to prevent it.
In Spring, if you could load your singleton class in two different contexts and then again we can break the singleton concept.
So, in summary, Java considers something a singleton if it cannot create more than one instance of that class within a given class loader, whereas Spring would consider something a singleton if it cannot create more than one instance of a class within a given container/context.
A Java singleton, per the design pattern where instantiation is restricted to one, usually per JVM class loader by the code.

A Spring singleton bean can be any normal class you write, but declaring it's scope as singleton means that Spring will only create one instance and provide its reference to all beans that reference the declared bean. You may have many instances of that class in your application, but only one will be created for that bean. You may even have multiple beans of the same class all declared as singleton. Each bean will create exactly one instance of the class.

Friday, May 9, 2014

Comparator and Comparable in Java

Comparator: Comparator is an interface which is defined in java.util package which means Comparator should be used as a utility to sort objects. Comparator interface in Java has method public int compare (Object o1, Object o2) which is used to compare two different objects.
Let’s see below example.
Student.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

 class Student {
           
            private int marks;
private String name;
            /**
             * @return the marks
             */
            public int getMarks() {
                        return marks;
            }

            /**
             * @return the name
             */
            public String getName() {
                        return name;
            }

            public Student(int marks, String name){
                        this.marks = marks;
                        this.name = name;
                       
            }
            /**
             * @param args
             */
            public static void main(String[] args) {
                        List<Student> studentList = new ArrayList<Student>();
                        studentList.add(new Student(50, "A"));
                        studentList.add(new Student(40, "B"));
                        studentList.add(new Student(60, "C"));
                        studentList.add(new Student(20, "D"));
                        studentList.add(new Student(30, "E"));
                       
                        StudentSortByMarks studentSortByMarks = new StudentSortByMarks();
                        Collections.sort(studentList,studentSortByMarks );
                        for(Student st : studentList) {
                        System.out.println(st.getMarks() + " :::: " + st.getName());
                        }
                        }
            }
           

Let’s create an interface StudentSortByMarks

StudentSortByMarks.java

import java.util.Comparator;
public class StudentSortByMarks implements Comparator<Student> {
            public int compare(Student st1, Student st2) {
                        return st1.getMarks() - st2.getMarks();
                        }          
}
Output:
20 :::: D
30 :::: E
40 :::: B
50 :::: A
60 :::: C
In the above example we have create a class Student. Two instance variables marks and name are declared and values are assigned through a constructor. Two getter methods are declared with which Student marks and name are retrieved later.
The Comparator is implemented by StudentSortByMarks where we are comparing marks of students with method int compare (Student st1, Student st2)
After that when we are running the main () method and After the studentList is sorted, the elements are printed with enhanced for loop and above output is getting generated.

Comparable: Comparable interface in Java is defined in java.lang package. Comparable is implemented by a class in order to be able to comparing object of itself with some other objects. Comparable interface has method public int compareTo (Object o)
Let’s see below example.
Student.java: The Student class implements Comparable interface. Here, Comparable is designed to be generics; that is, Comparable object compares only Student objects.
Two instance variables marks and name are declared and values are assigned through a constructor. Two getter methods are declared with which Student marks and name are retrieved later.
class Student implements Comparable<Student> {

       private int marks;
       private String name;
       /**
        * @return the marks
        */
       public int getMarks() {
              return marks;
       }
       /**
        * @return the name
        */
       public String getName() {
              return name;
       }
        public Student(int marks, String name) {
               this.marks = marks;
               this.name = name;
               }
        
        public int compareTo(Student st1) {
               return this.marks - st1.marks;
               }
        }

StudentSortByMarks.java
Another class StudentSortByMarks is created which creates some Student objects and adds them to ArrayList studentList. The ArrayList object studentList is passed to sort() method of Collections class. The sort() method sorts as per the Comparable interface compareTo() method as Student class implements Comparable interface.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class StudentSortByMarks {
                         public static void main(String args[]) {
                                     List<Student> studentList = new ArrayList<Student>();
                                     studentList.add(new Student(50, "A"));
                                     studentList.add(new Student(40, "B"));
                                     studentList.add(new Student(60, "C"));
                                     studentList.add(new Student(20, "D"));
                                     studentList.add(new Student(30, "E"));
                                     Collections.sort(studentList);
                                     for(Student st : studentList) {
                                                 System.out.println(st.getMarks() + " : " + st.getName());
                                                 }
                                     }
                         }
Output:
20 : D
30 : E
40 : B
50 : A
60 : C

Difference between Comparator and Comparable in Java

Parameter
Comparator
Comparable
Definition
Comparator in Java is defined in java.util package which means Comparator should be used as an utility to sort objects
java.util.Comparator
Comparable interface is defined in java.lang package, which should be provided by default
java.lang.Comparable
Sorting logic
Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id, name etc.
Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects
Sorting Strategy
if you want to sort on some other attribute of object then use Comparator
if you want to sort objects based on natural order then use Comparable
Implementation
Class whose objects to be sorted do not need to implement this interface. Some other class can implement this interface.
Ex. StudentSortByMarks class can implement Comparator interface to sort collection of students object by marks
Class whose objects to be sorted must implement this interface.
 Ex. StudentSortByMarks  class needs to implement comparable to collection of students object by marks
Sorting method
int compare(Object o1,Object o2)
This method compares o1 and o2 objects  and returns a integer. Its value has following meaning.
1.positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
int compareTo(Object o1)
This method compares this object with o1 object and returns a integer. Its value has following meaning
  1. positive – this object is greater than o1
  2. zero – this object equals to o1
  3. negative – this object is less than o1
Calling method
Collections.sort(List, Comparator)
Here objects will be sorted on the basis of Compare method in Comparator
Collections.sort(List)
Here objects will be sorted on the basis of CompareTo method