Tuesday, September 27, 2011

Simple Way to create a Logs in Java :

Note : log4j.jar mandatory required.

step - 1 )

create a class Log :
syntax :


/**
 *  This file is property of IMImobile pvt ltd.
 *  Copyright(c) 2008 IMImobile pvt ltd. All rigths reserved.
 */

package util;


import java.io.File;
import org.apache.log4j.Appender;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.SimpleLayout;

public class Log {

private static Logger myLogger = Logger.getLogger(Log.class.getName());
Appender myAppender;
SimpleLayout myLayout;

public Log() {
                PropertyConfigurator.configure(LogConstants.LOG_PROP_PATH);
                File file = new File(LogConstants.LOG_PROP_PATH);
                System.out.println(">>> Abs Path : "+file.getAbsolutePath());
}

// public static void initLogging() {
// PropertyConfigurator.configure(LogConstants.LOG_PROP_PATH);
// }

// public static void initLogging(String argLogPropPath) {
// PropertyConfigurator.configure(argLogPropPath);
// }

public static void debug(String argMessage, Exception ex) {
// log into {imiclient_name}_{proj_name}_debug.log
myLogger.debug(argMessage, ex);
}

public static void debug(String argMessage) {
// log into {imiclient_name}_{proj_name}_debug.log
myLogger.debug(argMessage);
}

public static void info(String argMessage, Exception ex) {
// log into {imiclient_name}_{proj_name}_info.log
myLogger.info(argMessage, ex);
}

public static void info(String argMessage) {
// log into {imiclient_name}_{proj_name}_info.log
myLogger.info(argMessage);
}

public static void error(String argMessage, Exception ex) {
// log into {imiclient_name}_{proj_name}_error.log
myLogger.error(argMessage, ex);
}

public static void error(Exception ex) {
// log into {imiclient_name}_{proj_name}_error.log
myLogger.error(ex);
}

public static void error(String argMessage) {
// log into {imiclient_name}_{proj_name}_error.log
myLogger.error(argMessage);
}





// public static void debug(String argClass, String argMessage, Exception ex) {
// debug(argClass, argMessage);
// ex.printStackTrace();
// }
//
// public static void debug(String argClass, String argMessage) {
// ConvertDate date = new ConvertDate();
// String className = date.getToday() + "[" + argClass + "] : ";
// System.out.println(className + argMessage);
// }
//
// public static void error(String argClass, String argMessage, Exception ex) {
// error(argClass, argMessage);
// ex.printStackTrace();
// }
//
// public static void error(String argClass, String argMessage) {
// argMessage = "[EXCEPTION] : " + argMessage;
// debug(argClass, argMessage);
// }
}


step -2 :

create a class LogConstants ;
Note : This class is helpful to set the custom properties file

syntax : config/log/log4j.properties ( Should in your root directory any custom name)


public class LogConstants {
public static String LOG_PROP_PATH = "config/log/log4j.properties";
}

 

Step-3 :  log4j.properties ( Important , we can change the format of logs as per our requirement in log4j.properties )
log4j.rootLogger=debug, stdout, ALL
#log4j.debugLogger=ALL, DEBUG
#log4j.infoLogger=ALL, INFO
#log4j.errorLogger=ALL, ERROR



# stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
# date log_level thread_name class_name message line_seperator
log4j.appender.stdout.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss.SSS} [%16t] [%5p] - %m%n
# log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

# ALL
log4j.appender.ALL=org.apache.log4j.RollingFileAppender
log4j.appender.ALL.File=D:/log.txt ( Here log info will be appended ) 
log4j.appender.ALL.MaxFileSize=20120KB
# Keep one backup file
log4j.appender.ALL.MaxBackupIndex=50
log4j.appender.ALL.layout=org.apache.log4j.PatternLayout
# timeinterval date log_level thread_name class_name message line_seperator
log4j.appender.ALL.layout.ConversionPattern=%-3r %d{dd/MM/yyyy HH:mm:ss.SSS} [%5p] [%t] [%c] - %m%n


# DEBUG
log4j.appender.DEBUG=org.apache.log4j.RollingFileAppender
log4j.appender.DEBUG.File=D:/VideoconBillingHandler/log.txt
log4j.appender.DEBUG.MaxFileSize=20120KB
# Keep one backup file
log4j.appender.DEBUG.MaxBackupIndex=50
log4j.appender.DEBUG.layout=org.apache.log4j.PatternLayout
# timeinterval date log_level thread_name class_name message line_seperator
log4j.appender.DEBUG.layout.ConversionPattern=%-3r %d{dd/MM/yyyy HH:mm:ss.SSS} [%5p] [%t] [%c] - %m%n


# INFO
log4j.appender.INFO=org.apache.log4j.RollingFileAppender
log4j.appender.INFO.File=D:/VideoconBillingHandler/log.txt
log4j.appender.INFO.MaxFileSize=20120KB
# Keep one backup file
log4j.appender.INFO.MaxBackupIndex=50
log4j.appender.INFO.layout=org.apache.log4j.PatternLayout
# timeinterval date log_level thread_name class_name message line_seperator
log4j.appender.INFO.layout.ConversionPattern=%-3r %d{dd/MM/yyyy HH:mm:ss.SSS} [%5p] [%t] [%c] - %m%n


# ERROR
log4j.appender.ERROR=org.apache.log4j.RollingFileAppender
log4j.appender.ERROR.File=D:/VideoconBillingHandler/log.txt
log4j.appender.ERROR.MaxFileSize=20120KB
# Keep one backup file
log4j.appender.ERROR.MaxBackupIndex=50
log4j.appender.ERROR.layout=org.apache.log4j.PatternLayout
# timeinterval date log_level thread_name class_name message line_seperator
log4j.appender.ERROR.layout.ConversionPattern=%-3r %d{dd/MM/yyyy HH:mm:ss.SSS} [%5p] [%t] [%c] - %m%n


Main Class :

example :

public class Main {
    
    public static void main(String[] args) {
   
     //  Note : we can able to trace the logs in our console as well as in the log.txt file which we have been defined in log4j.properties configuration file.
        Log log= new Log();
        Log.debug("welcome");
      
    }

}





Easy way to parse and read XML Data


Note : Required dom4j.jar

This Class file should be mandatory :


XMLHandler.java


import java.io.IOException;
import java.io.StringReader;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathFactory;


import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;




public class XMLHandler {


    private Document doc;


    public XMLHandler(final String message) throws IOException, SAXException, ParserConfigurationException {
        final StringReader response = new StringReader(message);
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(new InputSource(response));
    }




    public final String getStringValue(final String xPath) throws XPathException {
        // Get the matching elements
        XPathFactory factory = XPathFactory.newInstance();
        XPath path = factory.newXPath();
        final Node node = (Node)path.evaluate(xPath, doc, XPathConstants.NODE);


        return node.getFirstChild().getNodeValue().trim();
    }






}




Eg :




public class Testing


{



 public String simple(String xml) throws IOException, SAXException, ParserConfigurationException, XPathException
    {
        String xmlresp=null;




        XMLHandler xmh=new XMLHandler(xml);
        System.out.println("res"+xmh);


        xmlresp=xmh.getStringValue("/xml/datacom-api-output/response/code");


        System.out.println("cuming here..result : "+xmlresp);




        return xmlresp.toString();


    }







public static void main(String[]a)
{


  Testing t=new Testing();



  String xmlfile="<xml><datacom-api-output><response><code>0</code></response></datacom-api-output></xml>";




String result=  t.sample(xmlfile);
sop("----------"+result);




}


}



















Wednesday, September 21, 2011

how to generate a file with last update time in a day.


String temporaypath = m_strLogFilePath + "uniqueDateId.csv";
                        File out = new File(temporaypath);
                        if (!out.exists()) {
                            out.createNewFile();
                        }
                        FileInputStream fin = new FileInputStream(out);
                        BufferedReader buffreader = new BufferedReader(new InputStreamReader(fin));
                        String content = "";
                        String strFile = "";
                        while ((content = buffreader.readLine()) != null) {
                            System.out.println("data : " + content);
                            strFile = content;

                        }
                        buffreader.close();
                        if (strFile != null && strFile.trim().length() > 0) {
                            String strDate = strFile.substring(2, 4);
                            SimpleDateFormat sdff = new SimpleDateFormat("dd");
                            Date das = Calendar.getInstance().getTime();
                            String currdate = sdff.format(das);
                            System.out.println("curdate : " + currdate);
                            File sourceObjFile = null;
                            String strDestFile = "";
                            if (strDate.equalsIgnoreCase(currdate)) {
                                System.out.println("k");
                                String strSourceFilePath = m_strLogFilePath + strFile + ".csv";
                                sourceObjFile = new File(strSourceFilePath);
                                strDestFile = m_strLogFilePath + reportDate1 + reportTime1 + ".csv";
                                System.out.println("" + strDestFile);
                                File destFile = new File(strDestFile);
                                sourceObjFile.renameTo(destFile);
                                VoiceUtil.writeContentToFile(strDestFile, msisdn + "," + action + "," + shortcode + "," + reportDate2 + "\r", true);
                                VoiceUtil.writeContentToFile(temporaypath, reportDate1 + reportTime1, false);
                            } else {
                                String strCDRFile = m_strLogFilePath + reportDate1 + reportTime1 + ".csv";
                                System.out.println("==" + strCDRFile);
                                File file = new File(strCDRFile);
                                file.createNewFile();
                                VoiceUtil.writeContentToFile(strCDRFile, msisdn + "," + action + "," + shortcode + "," + reportDate2 + "\r", true);
                                VoiceUtil.writeContentToFile(temporaypath, reportDate1 + reportTime1, false);
                            }
                        } else {
                            String strCDRFile = m_strLogFilePath + reportDate1 + reportTime1 + ".csv";
                            System.out.println("==" + strCDRFile);
                            File file = new File(strCDRFile);
                            file.createNewFile();
                            VoiceUtil.writeContentToFile(strCDRFile, msisdn + "," + action + "," + shortcode + "," + reportDate2 + "\r", true);
                            VoiceUtil.writeContentToFile(temporaypath, reportDate1 + reportTime1, false);
                        }