Implementing Log4J

User log4j and commons-logging.jar in the class path. These jar files contain the information for logging set up.Declare the following as a class

attribute in the class where you want to implement the logging, say SomeClass.java

private static Logger logger = Logger.getLogger

(com.mattiz.SomeClass.class);

You would have a sample log4j properties configuration file which you should put in your classpath.
Suppose you wanted the line “Test Debug” to go to your log

file use logger.error or logger.debug or logger.warn.
Viz. logger.error(“Test Debug”);

For warning/ debugging messages you could use

logger.warn(“This is a warning”);

or

logger.debug(“Variable value is”+var);

In the log4j configuration file you can set the level of logging.In the sample configuration file you will find words like ERROR,WARN or DEBUG.If you
set the level to WARN, then only warnings and errors will print, while debug won’t print. If you set the level to DEBUG level then debug, warn and error
will print.These may go to the console or to a separate log output file based on the settings in the log4j configuration file. The log4j.properties contains
settings to “rollover” files. If file becomes more than 1 MB then copying to another file and creating a new file is done automatically by log4j. With the
settings in the log4j.properties file you can control

what is being logged. By setting it to ERROR level, debug statements won’t be printed in the production system.For development use DEBUG level because you
want to see debug messages.

The hierarchy is

DEBUG < INFO < WARN < ERROR < FATAL

If set to WARN level, all warn, error and fatal messages will be printed but no info and debug messages will be printed.You can set logging levels for each
package. So if you are working on a certain package you can set the package’s logging level to DEBUG, and another package’s logging level to WARN in the
log4j properties file.

For example

log4j.category.com.mattiz.security = WARN

You need not use all the debugging levels; mostly people use

DEBUG and ERROR. You can put error level messages inside the catch block.Error logs are like this logger.error(“Exception critical”+ex.toString());You can do this for production systems.

Contents of a simple log4j.properties configuration file

# Print FATAL, ERROR and WARN messages – do not print

DEBUG and INFO messages

# the sequence is FATAL > ERROR > WARN > DEBUG > INFO

# since the level is set to WARN – message levels above it will

be printed

# while levels below it will not be printed

log4j.rootCategory=WARN, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# the conversion pattern will be used to format the timestamp

see below example

# 2004-05-13 17:15:13,318 [Servlet.Engine.Transports : 1]

DEBUG

# this will pre-pend all logging messages

log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-

5p %c{1} - %m%n

Contents of a more elaborate log4j.properties file

# the general level is set to WARN

# WARN, ERROR, FATAL will be printed

# In addition to printing to System Out, also print

to "RollingFile"

log4j.rootCategory=WARN, stdout, RollingFile

# the level for the com.mattiz.web package (and subpackages)

is set to DEBUG

# DEBUG, WARN, ERROR, FATAL will be printed for the web package

log4j.category.com.mattiz.web=DEBUG

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Print the date and time for systemOut

log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c{1} - %m%n

# Save log to Rolling File Also

log4j.appender.RollingFile=org.apache.log4j.RollingFileAppender

# Location of rolling file

log4j.appender.RollingFile.File=d:/mattiz/mattiz.log

# if the file becomes greater than 500KB then create a new file

and backup the old file

log4j.appender.RollingFile.MaxFileSize=500KB

# Keep 5 back up files

log4j.appender.RollingFile.MaxBackupIndex=5

log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout

#Print the date and time for RollingFile

log4j.appender.RollingFile.layout.ConversionPattern=%d [%t]

%-5p %c{1} - %m%n

HashMap vs Hashtable

HashMap vs Hashtable

Hashtable and HashMap are both key-value based data structure. Both of them allows the access data based on key.
Both of them some differences in storing values and performance over iteration.

Some of the basic differences are following

HashMap HashTable
Synchronized Un-synchronized  Synchronized
Allow null Allowed Null for key and Value Not allowed, Null pointer would be thrown for Null
 Support in JDK since 1.2  1.0
 Subclass of Dictionary AbstractMap
 load factor  .75 .75

Hashtable

Hashtable performance is effected by its initial capacity and load factor provided at creation of object. In case of high load factor it grows it self.
At the time of creation there should not be too much initial capacity other-wise it would wastage of space. Higher the value of load factor will save to space, but lower the load factor will increase the time for searching entry.

Hashmap

Hashmap provide no guarantees to the order of the map. Hashmap is not synchronized, It means that multiple thread can access the same instance at same time, which can lead to
structal modification.

HashMap is better for non-threaded applications, as unsynchronized Objects perform better than synchronized ones.

Factory method pattern in Java

The factory method pattern is an object-oriented design pattern to implement the concept of factories. Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The creation of an object often requires complex processes not appropriate to include within a composing object. The object’s creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object’s concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.

Factory pattern comes into creational design pattern category, the main objective of the creational pattern is to instantiate an object and in Factory Pattern an interface is responsible for creating the object but the sub classes decides which class to instantiate. It is like the interface instantiate the appropriate sub-class depending upon the data passed. Here in this article we will understand how we can create an Factory Pattern in Java

The essence of the Factory method Pattern is to “Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses

Use the factory pattern when:

  • The creation of the object precludes reuse without significantly duplicating code.
  • The creation of the object requires access to information or resources not appropriate to contain within the composing object.
  • The lifetime management of created objects needs to be centralised to ensure consistent behavior.

printSomething.java

package techartifact.pattern.factory;

public abstract class PrintSomething {

public abstract void printTech();
}

Now we will have the concrete implementations of the PrintSomething class, JavaTech and J2eeTech, each providing a much simplified implementation for the printTech() method.

JavaTech.java

package techartifact.pattern.factory;

public class JavaTech extends PrintSomething {
@Override
 public void printTech()
 {
 System.out.println("this is java technology");
 }
}

We will having one more class for j2eeTech for j2ee technology.
J2eeTech.java

package techartifact.pattern.factory;

public class J2eeTech extends PrintSomething {
 public void printTech()
 {
     System.out.println("this is j2ee technology");
 }
}

Now let us come to the core implementation, the Factory class itself. The PrintFactory class has one static method called showPrint() which the clients can invoke to get the PrintSomething object. Note the return type of the method, it is neither JavaTech nor J2eeTech, but the super type of the both, i.e, PrintSomething. Whether the return type of method is JavaTech or J2eeTech is decided based on the input operating system.

PrintFactory.java

package techartifact.pattern.factory;

public class PrintFactory {

public static PrintSomething showPrint(String os){

   if (os.equals("Java"))
  {

        return new JavaTech();

  }
   else if (os.equals("J2ee"))
  {

    return new J2eeTech();

  }

return null

 }

}

In this we can makes use of the above PrintFactory class. The client is un-aware of the fact there is multiple implementations of the PrintSomething class. It accesses the printTech() operation through a single unified type PrintSomething

FactoryClient.java

package techartifact.pattern.factory;

public class FactoryClient {

  public static void main(String[] args) {

             PrintSomething psJava =PrintFactory.showPrint("Java");

             psJava.printTech();

             PrintSomething psJ2ee = PrintFactory.showPrint("J2ee");

             psJ2ee.printTech();

   }
}