Tuesday, October 11, 2011

simple way to call a webserivce using HTTP URL Connection



Procedure :

Below is the method for calling werbservice :
Note : here we need to pass wsdl file and also soap request with required parameters

then we have to parse the soap response with xml parsers in our customized way ..




 public static String httpcallWebService() {
        String strXml = "";
        String output = "";
     
        String result = null;
        try {

            webserviceUrl = "http://localhost:8080/WSTest/HelloWorld?wsdl";
            String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:com='http://com.in/'><soapenv:Header/><soapenv:Body><com:sayHello><arg0>_name_</arg0></com:sayHello></soapenv:Body></soapenv:Envelope>";
            String xmldata = xml.replaceAll("_name_", "Haasini");

            xmldata = xmldata.trim();
            URL objURL = new URL(webserviceUrl);
            HttpURLConnection objCon = (HttpURLConnection) objURL.openConnection();
            objCon.setRequestMethod("POST");
            objCon.setRequestProperty("SOAPAction", "");
            objCon.setRequestProperty("Content-Type", "text/xml");
            objCon.setDoOutput(true);
            objCon.getOutputStream().write(xmldata.getBytes());
            InputStream ins = objCon.getInputStream();
            byte[] b = new byte[1024 * 4];

            int nBytes = 0;
            while ((nBytes = ins.read(b)) > 0) {
                output += new String(b, 0, nBytes);
            }
            System.out.println("..... Webservice Response ....... ");
            System.out.println("WebResp"+output);

            ByteArrayInputStream bin = new ByteArrayInputStream(output.getBytes());
            Hashtable table = XMLUtil.getXML(bin);
            String strXactionId = (String) table.get("/S:Envelope/S:Body/ns2:sayHelloResponse/return");
            System.out.println("xactionId : " + strXactionId);

            if (output.contains("<return>")) {
                int start = output.indexOf("<return>");
                int end = output.indexOf("</return>");
                start = start + 8;
                result = output.substring(start, end);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return result;
    }


Another Class ;

public class XMLUtil {

    public static void main(String[] arg){
        try {
            FileInputStream fin = new FileInputStream(arg[0]);
            Hashtable h = XMLUtil.getXML(fin);
            java.util.Enumeration en = h.keys();
            while( en.hasMoreElements()){
                String str = (String)en.nextElement();
                System.out.println(str + " = " + (String)h.get(str));
            }
            fin.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }

    }

    public static StringBuffer addXMLTag(StringBuffer buf,String strName,String strVal,String strDefValue){
        buf.append("<" + strName +">");
        if( ( strVal == null || strVal.length() == 0)){
            buf.append( htmlEncode(strDefValue) );
        }else{
            buf.append( htmlEncode(strVal));
        }
        buf.append("</" + strName +">\r\n");
        return buf;
    }
    public static StringBuffer addXMLTag(StringBuffer buf,String strName,String strVal){
        buf.append("<" + strName +">");
        buf.append(htmlEncode(strVal));
        buf.append("</" + strName +">\r\n");
        return buf;
    }
    public static StringBuffer addXMLTag(StringBuffer buf,String strName,int nVal){
        return addXMLTag(buf,strName,""+nVal);
    }

    public static Hashtable getXML(InputStream inputstream) {
        if(inputstream == null)
            return null;
        try {
            javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
            javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
            org.w3c.dom.Document d = db.parse(inputstream);
            org.w3c.dom.Element e = d.getDocumentElement();
            org.w3c.dom.NodeList nl = d.getElementsByTagName(e.getTagName());
            Hashtable h = new Hashtable();
            doProcess(nl, h);
            return h;
        }catch(Exception e) {
            System.out.println("Error is : " + e);
            return null;
        }
    }

    static String getName(org.w3c.dom.Node node){
        if( node == null ){
            return null;
        }
        String strName = node.getNodeName();
        org.w3c.dom.Node pNode = node.getParentNode();
        if( pNode != null ){
            return getName(pNode) + "/" + strName.trim();
        }else{
            return "";
        }
    }

    private  static void doProcess(org.w3c.dom.NodeList nl, Hashtable h) {
        int i = 0;
        while(i < nl.getLength()) {
            org.w3c.dom.Node n = nl.item(i);
            String strNodeName = getName(n);
            String strNodeValue = n.getNodeValue();
            if(strNodeName != null)
                strNodeName = strNodeName.trim();

            if(strNodeValue != null)
                strNodeValue = strNodeValue.trim();

            if(strNodeValue != null && strNodeValue.length() != 0) {
                //h.put(n.getParentNode().getNodeName(), strNodeValue);
                h.put(getName(n.getParentNode()), strNodeValue);
            }
            if(n.hasChildNodes())
                doProcess(n.getChildNodes(), h);
            i++;
        }
    }
    public static String htmlDecode(String strMsg){
        strMsg = strMsg.replaceAll("&amp;","&");
        strMsg = strMsg.replaceAll("&lt;","<");
        strMsg = strMsg.replaceAll("&gt;",">");
        strMsg = strMsg.replaceAll("&quot;","\"");
        strMsg = strMsg.replaceAll("&apos;","\'");
        strMsg = strMsg.replaceAll("&nbsp;"," ");
        return strMsg ;
    }
    public static String htmlEncode(String strMsg){
        if( strMsg == null || strMsg.length() == 0 ){
            return strMsg;
        }
        strMsg = strMsg.replaceAll("&","&amp;");
        strMsg = strMsg.replaceAll("<","&lt;");
        strMsg = strMsg.replaceAll(">","&gt;");
        strMsg = strMsg.replaceAll("\"","&quot;");
        strMsg = strMsg.replaceAll("\'","&apos;");
        //strMsg = strMsg.replaceAll("&nbsp;"," ");
        return strMsg ;
    }

}



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