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




Wednesday, August 3, 2011

How to Parse XML Documents using JDOM


JDOM : Alternative of DOM and SAX.

DOM : parse xml document and load it into memory.  Too slow and consume more memory .
SAX  : it does'nt load xml document in to memory. instead it create object representation of xml document.
too fast and , efficient and

JDOM : Efficient reading, manipulation, and writing. This is lightweight api , fast and well optimized for java programmer . apart from that it will integrate well with both DOM and SAX.




Note : JDOM.jar  API should be used to work with these examples.


Example ! :



<xml>
<response>
<status-code>0</status-code>
<status-text>ACCEPTED</status-text>
<tid>131113893927817642</tid>
</response>
</xml>


 Requirement : Parsing XML using JDOM  Example 1  



public String parsingXMLUsingJDOM(String strXml) throws Exception {
        String xmlResponse = null;
        SAXBuilder builder = new SAXBuilder();
        InputStream is = new ByteArrayInputStream(strXml.getBytes());


        try {


            Document document = (Document) builder.build(is);
            Element rootNode = document.getRootElement();
            List list = rootNode.getChildren("response");
            for (int i = 0; i < list.size(); i++) {
            Element node = (Element) list.get(i);
            xmlResponse = node.getChildText("status-code");
            
            }
        } catch (IOException io) {
            System.out.println(io.getMessage());
        }  finally {
              if (builder != null) {
                builder = null;
             }
             if (is != null) {
                try {




                    is.close();
                    is = null;
                } catch (Exception e) {
                    e.printStackTrace();
                    ;
                }
            }
        }


        return xmlResponse;
    }




Note : In order to retrieve all the child nodes in the above XML Format , use concat() method .


Example 2 : Parsing XML Document using JDOM Example 2


XML Format :


<xml>
<x_extraparams>name=dasari , empid=1786</x_extraparams>
<xml>





public String parsingXMLUsingJDOM1(String strXml) throws Exception {
        String xmlResponse = null;
        SAXBuilder builder = new SAXBuilder();
        InputStream is = new ByteArrayInputStream(strXml.getBytes());


        try {


            Document document = (Document) builder.build(is);
            Element rootNode = document.getRootElement();
            List list = rootNode.getChildren("x_extraparams");
            for (int i = 0; i < list.size(); i++) {
            Element node = (Element) list.get(i);
            xmlResponse = node.getValue();


            String array[]=xmlResponse.split(",");


            xmlResponse=array[0].split("=").length > 1 ? array[0].split("=")[1]:"";
            xmlResponse+=",";
            xmlResponse+=array[1].split("=").length> 1 ? array[1].split("=")[1]:"";




            }
        } catch (IOException io) {
            System.out.println(io.getMessage());
        }  finally {


            if (builder != null) {
                builder = null;
            }
            if (is != null) {
                try {




                    is.close();
                    is = null;
                } catch (Exception e) {
                    e.printStackTrace();
                    ;
                }
            }
        }


        return xmlResponse;
    }


       Main Class :

      Simply Pass XML String to that specific method.

        SYN :     

 public class Dasari
{
 public static void main(String []a)
                      {

Dasari d=new Dasari();

d.parsingXMLUsingDOM("Pass XML String here ");

............ print the output here -----------
                        
             
                       }


}

  

Cheers Dasari




Happy Learning !!!