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);
                        }

Monday, August 29, 2011

Unique 10-digits Sequential Number in Java



 private static Long UniqueRandomInteger() {

        int Start = 1000000000;
        long End = 9999999999L;

        Random random = new Random();

if (Start > End) {
            throw new IllegalArgumentException("Start cannot exceed End.");
        }
        //get the range, casting to long to avoid overflow problems
        long range = aEnd - (long) aStart + 1;
        //  System.out.println("range>>>>>>>>>>>"+range);

        // compute a fraction of the range, 0 <= frac < range
        long fraction = (long) (range * aRandom.nextDouble());
        //   System.out.println("Fraction>>>>>>>>>>>"+fraction);

         randomNumber = fraction + (long) aStart;
         System.out.println("randomNmber>>>>>>>>>>>" + randomNumber);

         return randomNumber;
    }

  Format - 2 :

 long number = (long) Math.floor(Math.random() * 9000000000L) + 1000000000L;


Wednesday, August 10, 2011

Hibernate Query vs SQL Query ( Inner Join )

Requirement :


Students table : student_id,student_name ( student_id primary key )


Courses table : course_id,course_name ( course_id primary key )


Student_Course table : student_id,course_id ( student_id,course_id foreign key references )


how to join these 3 tables ....


Case : 1 



select s.student_id,s.student_name,c.course_id,c.course_name from students s inner join student_course sc on s.student_id= sc.student_id inner join courses c on c.course_id=sc.course_id;

Case : 2 

select s.student_name,c.course_name from students s inner join student_course sc on s.student_id=sc.student_id inner join courses c on c.course_id=sc.course_id;


Hibernate Query :  ( from Student as s inner join s.courses )
Note : Student ( Pojo BeanClassName ) , courses : object of set interface in Student Pojo :


Happy Learing !! 

vaass

 









Monday, August 8, 2011

WebServices : Soap

Requirement :

1) How to prepare Soap XML Request
2) How to Generate Soap XML
3) How to parse Soap Request using Axis WebServices.
4) Response : transactionID | Status-Code | Etc.....



1)
public class RequestTypes {

     public static final String XML_SOAP_REQUEST = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
            "xmlns:ws=\"http://ws.mobitel.com/\">" +
            "<soapenv:Header/>" +
            "<soapenv:Body>" +
            "<ws:chargeFromMSISDN>" +
            "<transactionId>_tid_</transactionId>" +
            "<msisdn>_msisdn_</msisdn>" +
            "</ws:chargeFromMSISDN>" +
            "</soapenv:Body>" +
            "</soapenv:Envelope>";

   

}




2)  public String generateSoapRequest(String tid,String msisdn) {
       
        String soapReq = RequestTypes.XML_SOAP_REQUEST;
        soapReq = soapReq.replaceAll("_tid_", tid);
        soapReq = soapReq.replaceAll("_msisdn_", msisdn);
       
        System.out.println("soapReq.."+soapReq);
   
        return soapReq;
        }

3) public String executeRequest(String destUrl, String tid, String msisdn) {
        Node result = null;
        SOAPConnection connection = null;
        try {
            String soapReq = generateSoapRequest(tid, msisdn);
            InputStream inStream =
                    new ByteArrayInputStream(soapReq.getBytes());
            Message axisMessage = new Message(inStream);
            axisMessage.getMimeHeaders().addHeader("Content-type", "text/xml;charset=utf-8");
            axisMessage.saveChanges();
            connection = SOAPConnectionFactory.newInstance().createConnection();
            SOAPMessage reply = connection.call(axisMessage,
                    new java.net.URL(destUrl));
            SOAPPart soapPart = reply.getSOAPPart();
            SOAPEnvelope envelope = soapPart.getEnvelope();
            SOAPBody body = envelope.getBody();
            Iterator iter = body.getChildElements();
            Node resultOuter = ((Node) iter.next()).getFirstChild();
            result = resultOuter.getFirstChild();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ex.getMessage();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SOAPException ex) {
                    ex.printStackTrace();
                }
            }
        }
        if (result != null) {
            System.out.println("result node. value"+result.getNodeValue());
            return result.getNodeValue();
        } else {
            return "";
        }
    }


Note : In the above executeRequest Method () we have to provide tid,msidn,desturl...in order to parse the Soap XML........

  The response would be in your customized format.......

Happy Learning ::::


Note :

Jars required :



axis.jar
axis-ant.jar
commons-discovery.jar
commons-logging.jar
jaxrpc.jar
log4j-1.2.8.jar
saaj.jar
wsdl4j.jar
wss4j-1.5.4.jar