Compare two List objects contains same objects with duplicate entries, but we need to show the unique records to the user. To achieve the above the following is the small snippet.
CustomerVO.java
public class CustomerVO implements Comparable{
private Integer id;
private String name;
/**
* @return the id
*/
public Integer getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Object obj) {
// TODO Auto-generated method stub
return id.compareTo(((CustomerVO)obj).getId());
}
}
Test.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
/**
* Method generate the master records for the customer information
* @return an Instance of <tt>ArrayList</tt> object
*/
private List<CustomerVO> getFirstArrayList() {
CustomerVO customer = null;
System.out.println("Creating Customer First List");
List<CustomerVO> customerFirstList = new ArrayList<CustomerVO>();
for (int i = 0; i < 100; i++) {
customer = new CustomerVO();
customer.setId(i + 1);
customer.setName("Name " + (i + 1));
customerFirstList.add(customer);
}
/**
* Sorting resultant list
*/
if(null != customerFirstList){
Collections.sort(customerFirstList);
}
return customerFirstList;
}
/**
* Method generate the duplicate records for the customer information
* @return an Instance of <tt>ArrayList</tt> object
*/
private List<CustomerVO> getSecondArrayList() {
System.out.println("Creating Customer First List");
CustomerVO customer = null;
List<CustomerVO> customerSeconbdList = new ArrayList<CustomerVO>();
for (int i = 1; i <= 50; i++) {
customer = new CustomerVO();
customer.setId(2*i);
customer.setName("Name " + (2 * i));
customerSeconbdList.add(customer);
}
/**
* Sorting resultant list
*/
if(null != customerSeconbdList){
Collections.sort(customerSeconbdList);
}
return customerSeconbdList;
}
/**
* Method to clean the lists and get unique records as list
* @param firstList
* Master/duplicate records for customer information
* @param secondList
* Master/duplicate records for customer information
* @return uniqeList an instance of <tt>ArrayList</tt>
* contains the unique customer records
*/
private List<CustomerVO> getUniqueCustomerList(List<CustomerVO> firstList,
List<CustomerVO> secondList) {
List<CustomerVO> biggerList = null;
List<CustomerVO> smallestList = null;
List<CustomerVO> uniqeList = null;
if(firstList != null && secondList != null ){
/**
* INITIALIZE THE BIGGEST AND SMALLEST LIST
*/
if( firstList.size() < secondList.size()){
biggerList = secondList;
smallestList = firstList;
}else{
biggerList = firstList;
smallestList = secondList;
}
/**
* PROCESSING THE LIST TO ELIMINATE THE DUPLICATE RECORDS FROM THE GIVE LIST
*/
if(biggerList.size() >0 && smallestList.size() > 0){
uniqeList = new ArrayList<CustomerVO>();
for(int i = 0 ; i< biggerList.size() ; ){
for(int j=0 ;j < smallestList.size(); ){
if(smallestList.get(j).compareTo(biggerList.get(i)) <= 0){
/** BOTH OBJECTS ARE THE SAME OR VALUE AT J INDEX IS LESS THAN VALUE AT I INDEX
* ADD OBJECT TO UNIQUE LIST
* AND INCREMENT I,J INDEX VALUES BY 1**/
uniqeList.add(smallestList.get(j));
System.out.println("equal");
i++;
j++;
}else if(smallestList.get(j).compareTo(biggerList.get(i)) < 0){
/** BOTH OBJECTS ARE NOT SAME
* VALUE AT J INDEX IS LESS THAN VALUE AT I INDEX
* ADD THE SMALL VALUE TO THE UNIQUE LIST
* INCREMENT J INDEX VALUE BY 1 **/
uniqeList.add(biggerList.get(i));
System.out.println("LESSTAHN");
j++;
} else if(smallestList.get(j).compareTo(biggerList.get(i)) > 0){
/** BOTH OBJECTS ARE NOT SAME
* VALUE AT J INDEX IS GRATTER THAN VALUE AT I INDEX
* ADD THE SMALL VALUE TO THE UNIQUE LIST
* INCREMENT I INDEX VALUE BY 1 **/
uniqeList.add(biggerList.get(i));
System.out.println("GREATERTAHN");
i++;
} else{
}
}
}
}
for(CustomerVO customer : uniqeList){
System.out.println("ID :"+customer.getId());
}
}
return null;
}
public static void main(String[] args) {
System.out.println("Creating Customer Second List");
Test t = new Test();
t.getUniqueCustomerList(t.getFirstArrayList(), t.getSecondArrayList());
}
}
Friday, April 19, 2013
How to hide closed project in eclipse
hat many of us not know. You may want to Hide all those closed projects from your workspace in Project Explorer tab. Simply follow following steps and do this is few seconds!
Click on Customize view a pop will open
select the closed project and then say ok.
Three Steps hide the closed projects..
Converting audio/video files using ffmpeg
Common ffmpeg Parameters
- -i - Path\Filename of source file
- -y - Overwrite the existing output file without prompting
- -an - Disable audio
- -aspect - Set Aspect Ratio for the video (4:3, 16:9 or 1.3333, 1.7777)
- -r - Set frame rate in Hz for the video
- -s - Set video resolution size (Width x Height)
- -sameq - Use same video quality as source
- -ar - Set audio sampling rate (in Hz)
- -acodec - Force audio codec, example mp3
- -vol - Change audio volume (256=normal)
- -ab - Set audio bit rate (in bits/s)
ffmpeg Command
Video
- Converting MOV to FLV using FFMPEG:
ffmpeg -i movie.mov movie.flv
- Converting Mpeg to FLV using FFMPEG:
ffmpeg -i movie.mpeg movie.flv
- Converting AVI to FLV using FFMPEG - convert movie.avi to movie.flv and resize the video resolution to 500×500:
ffmpeg -i movie.avi -s 500×500 movie.flv
- Converting 3GP to FLV using FFMPEG - convert movie.3gp to movie.flv, keep the original file settings and disable the audio content:
ffmpeg -i movie.3gp -sameq -an movie.flv
- Converting MPEG to 3GP using FFMPEG:
ffmpeg -i movie.mpeg -ab 8.85k -acodec libamr_wb -ac 1 -ar 16000 -vcodec h263 -s qcif movie2.3gp
- Converting aac to mp3 using FFMPEG with MetaData - convert audio.aac to audio.mp3 with an audio rate of 22.05 Khz and audio BitRate of 32Khz, and will copy the metadata from .aac file to .mp3 file:
ffmpeg -i audio.aac -ar 22050 -ab 32 -map_meta_data audio.mp3:audio.aac audio.mp3
- Converting WMV to MP3 using FFMPEG
ffmpeg -i audio.wmv audio.mp3
- Converting WMV to FLV using FFMPEG - convert audio.wmv to audio.flv, generating only audio content:
ffmpeg -i audio.wmv audio.flv
- Converting AMR to MP3 using FFMPEG - convert audio.amr to audio.mp3, with an audio rate of 22.05 Khz:
ffmpeg -i audio.amr -ar 22050 audio.mp3
- Converting aac to mp3 using FFMPEG - convert audio.aac to audio.mp3, with an audio rate of 22.05 Khz and audio BitRate or 32Khz:
ffmpeg -i audio.aac -ar 22050 -ab 32 audio.mp3
http://ffmpeg.arrozcru.org/autobuilds/
convert avi to flv like in youtube
ffmpeg -i video_origine.avi -ab 56 -ar 44100 -b 200 -r 15 -s 320x240 -f flv video_finale.flv
Friday, April 12, 2013
RTMP Fallback Machanism
In Flex application some security reasons in the netowrk RTMP is blocked in the enterprise environment, so we unable to connect to the media streaming servers like wowza,flash media server and etc., RTMPT will provide solution to the above. It provides the wrapper on top of RTMP and send the data through HTTP protocol and it through proxy. RTMP will run on 1935(default) and RTMPT will run on (80). So defaultly port 80 is opened for all the proxy/N/W fire wall.But performance of RTMPT is lesser than the RTMP.
1)ProtocolUtilities.as
package com.asfusion.sample.model.utils
{
import com.asfusion.sample.model.vos.AppConfig;
import flash.events.AsyncErrorEvent;
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.net.NetConnection;
import mx.controls.Alert;
public class ProtocolUtilities
{
private var counter:Number = 0;
[Bindable]
public var isRtmp:Boolean = true;
[Bindable]
public var protocolStatus:String = "";
private static var instance:ProtocolUtilities;
private var _ncon:NetConnection;
public function ProtocolUtilities() {
}
public static function getInstance ():ProtocolUtilities {
if (!instance)
instance = new ProtocolUtilities();
return instance;
}
public function testConnection():void{
counter ++;
trace("Iniside of testConnection");
_ncon = new NetConnection();
_ncon.addEventListener(NetStatusEvent.NET_STATUS,onNetStatus);
_ncon.addEventListener(SecurityErrorEvent.SECURITY_ERROR,securityError);
_ncon.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncError);
trace("IP :"+AppConfig.getInstance().appliation_IP);
if(counter == 1){
if(AppConfig.getInstance().debug == "true")
Alert.show(counter +" : rtmp");
_ncon.connect("rtmp://127.0.0.1:1935/vod");
if(AppConfig.getInstance().debug == "true")
Alert.show("rtmp://127.0.0.1:1935/vod");
}else{
if(AppConfig.getInstance().debug == "true")
Alert.show(counter +" : rtmpt");
_ncon.connect("rtmpt://127.0.0.1:80/vod");
if(AppConfig.getInstance().debug == "true")
Alert.show("rtmpt://127.0.0.1:80/vod");
}
trace("Outside of testConnection"+counter);
}
/**
* Method tracks the connection state
**/
public function onNetStatus(e:NetStatusEvent):void {
var code:String = e.info.code;
if(AppConfig.getInstance().debug == "true")
Alert.show("NetStatus c:##"+code);
try {
if(code.indexOf("Success") != -1){
//connected successfully
trace("Successfully connected...");
/*do something here*/
} else if (code.indexOf("Closed") != -1 ){
trace("Connection closed By User");
}else if (code.indexOf("Failed") != -1 ){
trace("connection failed");
if(counter <= 1 ){
trace("isRtmp :"+isRtmp);
isRtmp = false;
testConnection();
}else{
trace("isRtmp :"+isRtmp);
protocolStatus = "Sorry!!";
trace("Falied to connect");
}
}else {
trace("Connection Failed ..");
trace("Connection closed Becuase of Server inActive state");
_ncon = null;
trace("Sorry!! Media server is Inactive please try again!!");
}
trace("Net Status :" + code + "\r");
}catch(e:Error){
if(AppConfig.getInstance().debug == "true")
Alert.show("Error occured in NetStatus :"+e.getStackTrace());
trace("Error occured in NetStatus :"+e.getStackTrace());
_ncon = null;
} finally {
//Dispose Objects
}
}
private function securityError(e:SecurityErrorEvent):void {
_ncon.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,securityError);
//What do we need to do in case of a security error?
//To be implemented
//Alert.show("Security Error: "+ e.text);
trace("Security Error ::"+e);
}
private function asyncError(e:AsyncErrorEvent):void {
//What do we need to in case if there is fault?
//To be implemented
_ncon.removeEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncError);
trace("AsyncError ::"+e);
//Alert.show("Async Error: "+ e.text);
}
}
}
Thursday, April 11, 2013
Create User Defined Exception
I hope that the following snippet will give you a better understanding how to create the User defined exception using java
1) FinanceExceptio.java
package com.sample.utility.exceptions;
/**
* The class <code>FederalBank</code> and its subclasses are a form of
* <code>Exception</code> that indicates conditions that a reasonable
* application might want to catch.
*
* @author SunilG
* @version 1.0, 11 April 2013
*/
public class FinanceException extends Exception {
/**
* The serial version id.
*/
private static final long serialVersionUID = 1878273194442401814L;
/**
* The cached root exception wrapped and sent by the subclasses.
*/
private Throwable root;
/**
* Constructs a new exception with the specified detail message.
*
* @param message
* the detail message. The detail message is saved for later
* retrieval by the {@link #getMessage()} method.
*/
public FinanceException(final String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail
* message and cause.
*
* @param message
* the detail message (which is saved for later
* retrieval by the {@link #getMessage()} method).
* @param throwable
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public FinanceException(final String message,
final Throwable throwable) {
this(message);
this.root = throwable;
}
/**
* Constructs a new exception with the specified cause.
*
* @param throwable
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public FinanceException(final Throwable throwable) {
this.root = throwable;
}
/**
* Returns the root cause of this Exception.
*
* @return the cause of this Exception or <code>null</code>
* if the cause is nonexistent or unknown.
*/
public Throwable getRootCause() {
return this.root;
}
}
2) BusinessException.java
package com.sample.utility.exceptions;
/**
* @author SunilG
*
*/
public class BusinessException extends FinanceException {
/**
* The serial version id.
*/
private static final long serialVersionUID = 6527473722381576450L;
/**
* Constructs a new exception with the specified detail message.
*
* @param message
* the detail message. The detail message is saved for later
* retrieval by the {@link #getMessage()} method.
*/
public BusinessException(final String message) {
super(message);
}
/**
* Constructs a new exception with the specified cause.
*
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public BusinessException(final Throwable cause) {
super(cause);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* @param message
* the detail message (which is saved for later retrieval by the
* {@link #getMessage()} method).
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public BusinessException(final String message,
final Throwable cause) {
super(message, cause);
}
}
3) DBException.java
package com.sample.utility.exceptions;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
/**
* The class <code>DBException</code> and its subclasses are a form of
* <code>FederalBankException</code> that indicates exception conditions that
* occur in the data access layer.
*
* <p>
* Applications should throw instances of this class to indicate other issues
* related Database operation
* @author SUNILG
* @version 1.0, 11 April 2013
*/
public class DBException extends FinanceException {
/**
* The serial version id.
*/
private static final long serialVersionUID = 2696949392657790519L;
/**
* Constructs a new exception with the specified detail message.
*
* @param message
* the detail message. The detail message is saved for later
* retrieval by the {@link #getMessage()} method.
*/
public DBException(final String message) {
super(message);
}
/**
* Constructs a new exception with the specified cause.
*
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public DBException(final SQLException cause) {
super(cause);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* @param message
* the detail message (which is saved for later retrieval by the
* {@link #getMessage()} method).
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public DBException(final String message,
final SQLException cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified cause.
*
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public DBException(final HibernateException cause) {
super(cause);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* @param message
* the detail message (which is saved for later retrieval by the
* {@link #getMessage()} method).
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public DBException(final String message,
final HibernateException cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* @param message
* the detail message (which is saved for later retrieval by the
* {@link #getMessage()} method).
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public DBException(final String message,
final Throwable cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified cause.
*
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public DBException(final DataAccessException cause) {
super(cause);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* @param message
* the detail message (which is saved for later retrieval by the
* {@link #getMessage()} method).
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public DBException(final String message,
final DataAccessException cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified cause.
*
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public DBException(final DataAccessResourceFailureException cause) {
super(cause);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* @param message
* the detail message (which is saved for later retrieval by the
* {@link #getMessage()} method).
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public DBException(final String message,
final DataAccessResourceFailureException cause) {
super(message, cause);
}
/**
* Constructs a new exception with the specified cause.
*
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public DBException(final IllegalStateException cause) {
super(cause);
}
/**
* Constructs a new exception with the specified detail message and cause.
*
* @param message
* the detail message (which is saved for later retrieval by the
* {@link #getMessage()} method).
* @param cause
* the cause (which is saved for later retrieval by the
* {@link #getCause()} method).
*/
public DBException(final String message,
final IllegalStateException cause) {
super(message, cause);
}
}
Creating custom Logger Factory
Creating custom Logger Factory
I hope that the following sample snippet will give you a better understanding how to create the custom Logger Factory
package com.sample.utility.loggers;
/**
* This is an interface for application logger.It contains methods which
* facilitate the logging.Implementing <code>Logger</code> interface will unify
* most of the logging requirements and result in consistent logging system.
*
*
* @author SUNILG
* @version 1.0, 11 April 2013
*/
public interface Logger {
/**
* Logs the given string as a debug message, provided logging at
* <tt>DEBUG</tt> level is enabled for the current logger.
* <p>
* Any <tt>appendThese</tt> arguments passed will be appended to the
* message.
*
* @param message
* the message that needs to be logged.
*
* @param appendThese
* fragments which will be appended to the message.
*/
void debug(String message, Object... appendThese);
/**
* Logs the given string as an information, provided logging at
* <tt>INFO</tt> level is enabled for the current logger.
* <p>
* Any <tt>appendThese</tt> arguments passed will be appended to the
* message.
*
* @param message
* the message that needs to be logged.
*
* @param appendThese
* fragments which will be appended to the message.
*/
void info(String message, Object... appendThese);
/**
* Logs the given string as a warning message, provided logging at
* <tt>WARN</tt> level is enabled for the current logger.
* <p>
* Any <tt>appendThese</tt> arguments passed will be appended to the
* message.
*
* @param message
* the message that needs to be logged.
*
* @param appendThese
* fragments which will be appended to the message.
*/
void warn(String message, Object... appendThese);
/**
* Logs the given string as an error message.
*
* @param message
* the message that needs to be logged.
*/
void error(String message);
/**
* Logs the given string at the error level with the exception message.
*
* @param message
* the message that needs to be logged.
*
* @param throwable
* the <code>Throwable</code> to be logged.
*/
void error(String message, Throwable throwable);
/**
* Logs the given string at the fatal level.
*
* @param message
* the message that needs to be logged.
*/
void fatal(String message);
/**
* Logs the given string at the fatal level with the exception message.
*
* @param message
* the message that needs to be logged.
* @param throwable
* the <code>Throwable</code> to be logged.
*/
void fatal(String message, Throwable throwable);
/**
* Logs a method entry with the list of its parameters at debug level.
*
* @param methodName
* the string containing method name.
*
* @param params
* an array of the parameters of the method.
*/
void entering(String methodName, Object... params);
/**
* Logs the exit from a method at debug level.
*
* @param methodName
* the string containing method name.
*/
void exiting(String methodName);
/**
* Logs the exit from a method which returns a value at debug level.
*
* @param methodName
* the string containing method name.
*
* @param retVal
* the return value of the method.
*/
void exiting(String methodName, Object retVal);
/**
* Changes the logging level of a current logger.
* With this logging levels for a logger can be controlled dynamically.
*
* @param loggerLevel
* the logging level to be set
*/
void setLoggerLevel(String loggerLevel);
/**
* Returns the <code>Level.DEBUG</code> status of the logger in context.
*
* @return boolean indicating whether debug is turned on or off
*
* @see org.apache.log4j.Level
*/
boolean isDebugEnabled();
/**
* Returns the <code>Level.WARN</code> status of the logger in context.
*
* @return boolean indicating whether warn is turned on or off
*
* @see org.apache.log4j.Level
*/
boolean isWarnEnabled();
/**
* Returns the <code>Level.INFO</code> status of the logger in context.
*
* @return boolean indicating whether info is turned on or off
*
* @see org.apache.log4j.Level
*/
boolean isInfoEnabled();
}
2) LoggerFactory.java
package com.sample.utility.loggers;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.log4j.Logger;
import com.sample.utility.utils.LogUtil;
/**
* This class <code>LoggerFactory</code> provides the entry point to the logging
* layer. On loading caches all the current loggers configured in the runtime
* environment in a <code>Map</code> for later retrieval.
*
* The typical usage in getting a <code>EngineLogger</code> instance to start
* logging is as shown below :
*
* <p>
* <blockquote>
*
* <pre>
* private static EngineLogger logger = LoggerFactory.getInstance().getLogger(
* MyClass.class);
* </pre>
*
* <p>
* It can then use all the methods defined under <code>Logger</code> interface
* appropriately.
* </blockquote>
*
* @author SUNILG
* @version 1.0, 11 April 2013
*/
public final class LoggerFactory {
/**
* Single ton instance for this class
*/
private static LoggerFactory theInstance = new LoggerFactory();
/**
* Cache of loggers.
*/
private HashMap logInstance = new HashMap();
/**
* Default Constructor- Caches all the system and root loggers.
*/
private LoggerFactory() {
try {
// Get the current loggers configured
Iterator i = LogUtil.getCurrentLoggers().iterator();
SampleLogger log = null;
Logger logger = null;
// Loop through and cache the named loggers
while (i.hasNext()) {
logger = (Logger) i.next();
log = new SampleLogger(logger);
logInstance.put(logger.getName(), log);
}
} catch (Exception exception) {
exception.printStackTrace();
throw new RuntimeException("unknown Exception: "
+ exception);
}
}
/**
* Returns the instance of this class.
*
* @return an instance of <code>LoggerFactory</code>
*/
public static LoggerFactory getInstance() {
return theInstance;
}
/**
* Gets the instance of logger which is associated with the given class.
* <p>
* This method searches its cache for the logger instance with the given
* class name.
* <p>
* If an instance of the logger is not found in the cache, then a new
* instance of logger is created and returned.
*
* @param clazz
* a <code>Class</code> object interested in using the logger.
*
* @return an implementation of <code>Logger</code>
*/
public SampleLogger getLogger(Class clazz) {
String name = clazz.getName();
SampleLogger log = (SampleLogger) logInstance.get(name);
if (log == null) {
synchronized (LoggerFactory.class) {
log = new SampleLogger(clazz);
logInstance.put(name, log);
}
}
return log;
}
/**
* Sets the logger with the <code>loggerName</code>
* to the specified level <code>loggerLevel</code>.
*
* @param loggerName
* the name of the logger.This is used to retrieve the named
* logger instance
* @param loggerLevel
* the loggerLevel to change
*/
public void setCurrentLogger(String loggerName, String loggerLevel) {
SampleLogger log = (SampleLogger) logInstance.get(loggerName);
// Set the logger level of the named logger
if (log != null) {
log.setLoggerLevel(loggerLevel);
logInstance.put(loggerName, log);
}
}
}
3) SampleLogger.java
/**
*
*/
package com.sample.utility.loggers;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
/**
* @author SUNILG
* @version 1.0, 11 April 2013
*/
public class SampleLogger implements com.sample.utility.loggers.Logger {
/**
* Enter method prefix.
*/
private static final String ENTER_PREFIX = " ENTERING METHOD : ";
/**
* Exit method prefix.
*/
private static final String EXIT_PREFIX = " EXITING METHOD : ";
/**
* Parameter prefix.
*/
private static final String PARAM_PREFIX = " PARAM";
/**
* Return value prefix.
*/
private static final String RETURN_PREFIX = " RETURN VALUE = ";
/**
* Name of this class.
*/
private static final String LOGGER_NAME = SampleLogger.class.getName();
/**
* Log4j logger for logging.
*/
private final Logger logger;
/**
* Creates a logger for the given class.
*
* @param clazz
* the <code>Class</code> object interested in logging.
*/
public SampleLogger(Class clazz) {
logger = Logger.getLogger(clazz);
}
/**
* Creates a logger with a given logger.This is used to load all the
* predefined system loggers.
*
* @param logger
* a Log4j logger instance
*/
public SampleLogger(Logger logger) {
this.logger = logger;
}
/**
* {@inheritDoc}
*/
public void debug(String message, Object... appendThese) {
if (!this.isDebugEnabled()) {
return;
}
if (appendThese != null) {
StringBuilder msg = new StringBuilder(message);
for (Object appendThis : appendThese) {
msg.append(appendThis);
}
message = msg.toString();
}
logger.log(LOGGER_NAME, Level.DEBUG, message, null);
}
/**
* {@inheritDoc}
*/
public void info(String message, Object... appendThese) {
if (!this.isInfoEnabled()) {
return;
}
if (appendThese != null) {
StringBuilder msg = new StringBuilder(message);
for (Object appendThis : appendThese) {
msg.append(appendThis);
}
message = msg.toString();
}
logger.log(LOGGER_NAME, Level.INFO, message, null);
}
/**
* {@inheritDoc}
*/
public void warn(String message, Object... appendThese) {
if (!this.isWarnEnabled()) {
return;
}
if (appendThese != null) {
StringBuilder msg = new StringBuilder(message);
for (Object appendThis : appendThese) {
msg.append(appendThis);
}
message = msg.toString();
}
logger.log(LOGGER_NAME, Level.WARN, message, null);
}
/**
* {@inheritDoc}
*/
public void error(String message) {
logger.log(LOGGER_NAME, Level.ERROR, message, null);
}
/**
* {@inheritDoc}
*/
public void error(String message, Throwable throwable) {
logger.log(LOGGER_NAME, Level.ERROR, message, throwable);
}
/**
* {@inheritDoc}
*/
public void fatal(String message) {
logger.log(LOGGER_NAME, Level.FATAL, message, null);
}
/**
* {@inheritDoc}
*/
public void fatal(String message, Throwable throwable) {
logger.log(LOGGER_NAME, Level.FATAL, message, throwable);
}
/**
* {@inheritDoc}
*/
public void entering(String methodName, Object... params) {
logger.log(LOGGER_NAME, Level.DEBUG,
this.getEnterMethodLogStr(methodName, params), null);
} // end of method enterMethod
/**
* {@inheritDoc}
*/
public void exiting(String methodName) {
StringBuffer buf = new StringBuffer();
buf.append(EXIT_PREFIX);
buf.append(methodName + "(..)");
logger.log(LOGGER_NAME, Level.DEBUG, buf.toString(), null);
}
/**
* {@inheritDoc}
*/
public void exiting(String methodName, Object retVal) {
StringBuffer buf = new StringBuffer();
buf.append(EXIT_PREFIX);
buf.append(methodName + "(..)");
buf.append(RETURN_PREFIX);
buf.append("[ ");
buf.append(retVal);
buf.append(" ]");
logger.log(LOGGER_NAME, Level.DEBUG, buf.toString(), null);
}
/**
* {@inheritDoc}
*/
public void setLoggerLevel(String loggerLevel) {
if ("DEBUG".equals(loggerLevel)) {
logger.setLevel(Level.DEBUG);
}
if ("INFO".equals(loggerLevel)) {
logger.setLevel(Level.INFO);
}
if ("WARN".equals(loggerLevel)) {
logger.setLevel(Level.WARN);
}
if ("ERROR".equals(loggerLevel)) {
logger.setLevel(Level.ERROR);
}
if ("FATAL".equals(loggerLevel)) {
logger.setLevel(Level.FATAL);
}
}
/**
* {@inheritDoc}
*/
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
/**
* {@inheritDoc}
*/
public boolean isInfoEnabled() {
return logger.isInfoEnabled();
}
/**
* {@inheritDoc}
*/
public boolean isWarnEnabled() {
return logger.isEnabledFor(Level.WARN);
}
/**
* Returns the log string for entry of a method.
*
* @param methodName
* a string containing the method name as the parameter.
*
* @param params
* an array of objects containing the parameters to the method.
*
* @return a string to be logged indicating the entry of this method.
*/
private String getEnterMethodLogStr(String methodName, Object[] params) {
StringBuffer buf = new StringBuffer(ENTER_PREFIX);
buf.append(methodName + "(..)");
if (params != null) {
for (int i = 0; i < params.length; i++) {
if (i > 0 && i != params.length) {
buf.append(",");
}
buf.append(PARAM_PREFIX);
buf.append(i + 1);
buf.append(" = [");
buf.append(params[i]);
buf.append("]");
}
}
return buf.toString();
}
}
4) LogUtil
package com.sample.utility.utils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import com.sample.utility.loggers.LoggerFactory;
/**
* The <code>LogUtil</code> class contains a collection of public
* static utility methods for logger used in the application.
*
*
* @author SUNILG
* @version 1.0, 11 April 2013
*/
public final class LogUtil {
/**
* The private constructor to prevent instantiation.
*/
private LogUtil() {
}
/**
* Sets the level of logging for the given loggerName.
* This method retrieves the named logger instance
* and modifies the Level.
*
* @param loggerName
* the name of the logger to which level has to be modified
* @param loggerLevel
* the new level that has to set to <code>Logger</code>
* identified by the <code>loggerName</code>
* @return a response containing appropriate message
*
* @see org.apache.log4j.Logger#getLogger(java.lang.String)
* @see org.apache.log4j.Category#setLevel(org.apache.log4j.Level)
*
*/
public static String setLoggerLevel(
String loggerName, String loggerLevel) {
LoggerFactory.getInstance().
setCurrentLogger(loggerName, loggerLevel);
// response to the caller
return "Logger verbosity set successfully, logger=" + loggerName
+ ", level=" + loggerLevel
+ ". The change may affect"
+ " subordinate loggers.";
}
/**
* Internal method to Retrieve all the current loggers from the logger
* repository as a <code>Collection</code> instance.
*
* @return a Collection holding the Current Loggers
*/
public static java.util.Collection getCurrentLoggers() {
// Create an empty list to hold CurrentLoggers
java.util.List loggers = new java.util.LinkedList();
// Build the list with logger
for (java.util.Enumeration e =
org.apache.log4j.Logger.getRootLogger()
.getLoggerRepository().getCurrentLoggers();
e.hasMoreElements();) {
Logger loggerImpl = (org.apache.log4j.Logger)
e.nextElement();
loggers.add(loggerImpl);
}
return loggers;
}
/**
* Returns the current logging level of the given logger.
*
* @param logger
* the logger on which current <code>LEVEL</code> will be
* returned
* @return the effective Level of the input <code>Logger</code>
*
* @see org.apache.log4j.Level
*/
public static Level getCurrentLevel(Logger logger) {
org.apache.log4j.Level level = logger.getEffectiveLevel();
if (Level.ALL.equals(level)) {
return Level.DEBUG;
}
if (Level.DEBUG.equals(level)) {
return Level.DEBUG;
}
if (Level.INFO.equals(level)) {
return Level.INFO;
}
if (Level.WARN.equals(level)) {
return Level.WARN;
}
if (Level.ERROR.equals(level)) {
return Level.ERROR;
}
if (Level.FATAL.equals(level)) {
return Level.FATAL;
}
if (Level.OFF.equals(level)) {
return Level.FATAL;
}
return null;
}
}
Subscribe to:
Posts (Atom)