Thursday, May 31, 2012

Create Simple SOAP Request Message Using SAAJ API


The SOAP with Attachments API for Java (SAAJ) enables developers to produce and consume messages conforming to the SOAP 1.1 and SOAP 1.2 specification and also and SOAP with Attachments note.

Hear is a simple example code to produce SOAP request message to get user detail using SAAJ API.

public void createSOAPRequestMessage () {

    MessageFactory messageFactory = MessageFactory

               .newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);

  SOAPMessage soapMessage = messageFactory.createMessage();

        SOAPPart soapPart = soapMessage.getSOAPPart();

        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        SOAPBody soapBody = soapEnvelope.getBody();

        soapEnvelope.addNamespaceDeclaration("xsi","http://www.w3.org/2001/XMLSchema-instance");

        soapEnvelope.addNamespaceDeclaration("xsd","http://www.w3.org/2001/XMLSchema");

        soapMessage.getSOAPHeader().detachNode();

        QName qNameRootTag = new QName("http://www.example.com/","GetUserDetail");

        SOAPBodyElement soapRootBodyElement = soapBody.addBodyElement(qNameRootTag);

        QName username = new QName("username");

        SOAPElement inputTagOne = soapRootBodyElement.addChildElement(username);

        inputTagOne.addTextNode("Mr Goni");

        QName userid = new QName("userid");

        SOAPElement inputTagTwo = soapRootBodyElement.addChildElement(userid);

        inputTagTwo.addTextNode("W2012X");

        soapMessage.saveChanges(); 

  soapMessage.writeTo(System.out);

        System.out.println();

}

This code will produce output like :





 

 Mr Goni
 W2012X

 






So , grub the code test and use or modify as your need .

Monday, May 28, 2012

Read File From /WEB-INF/ at runtime

Suppose one want to read a  example.properties  file located in /WEB-INF/props/example.properties in run time.

A simple way :

Properties properties = new java.util.Properties();
        InputStream inputStream =   
            getServletContext().getResourceAsStream("/WEBINF/props/example.properties");
properties.load(inputStream);

Now , we are ready to get value from example.properties file .

String value = properties.getProperty("propertyName");

Sample Properties File :

example.properties 

propertyName  = 123
-------------------------------------------------------------------

getResourceAsStream(String str) explained at java doc  :


public InputStream getResourceAsStream(String name)
Returns an input stream for reading the specified resource.The search order is described in the documentation for getResource(String).
Parameters:
name - The resource name
Returns:
An input stream for reading the resource, or null if the resource could not be found
Since:
1.1

Thursday, May 24, 2012

Introduction to SOAP Protocol


Official Definition of SOAP

W3 described SOAP as “SOAP Version 1.2 is a lightweight protocol intended for exchanging structured information in a decentralized, distributed environment ”
We can define it as a simple messaging framework .It build on XML technologies.
Two version of SOAP protocol is available now , 1.1 and 1.2 . Her I will focus on version 1.2.

Major Use Case : Exchanging information between systems.

Power of SOAP 1.2 :
This framework designed such a way that it is “independent of any particular programming model and other implementation specific semantics ”.

SOAP makes communication with web services smooth and more solid.
Example : SOAP message containing a SOAP header block and a SOAP body
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
 <env:Header>
  <n:alertcontrol xmlns:n="http://example.org/alertcontrol">
   <n:priority>1</n:priority>
   <n:expires>2050-06-22T14:00:00-05:00</n:expires>
  </n:alertcontrol>
 </env:Header>
 <env:Body>
  <m:alert xmlns:m="http://example.org/alert">
   <m:msg>Hello World SOAP Message</m:msg>
  </m:alert>
 </env:Body>
</env:Envelope>

SOAP Terminology :
Conceptual :
SOAP :
Simple object protocol.

SOAP node
 A SOAP node is responsible for enforcing the rules that govern the exchange of SOAP messages
SOAP role :
A SOAP receiver's expected function in processing a message. A SOAP receiver can act in multiple roles.
SOAP binding
Set of rules to exchange SOAP message in top of another protocol or a part of another protocol. Usually SOAP message exchanged with in an HTTP entity-body or over Tcp stream.
SOAP feature
"reliability", "security", "correlation", "routing", and "Message Exchange Patterns" (MEPs).
SOAP module
A SOAP Module is a specification that contains the combined syntax and semantics of SOAP header blocks.
SOAP message exchange pattern (MEP)
A template for the exchange of SOAP messages between SOAP nodes.
SOAP application
Can be a web service provider or a web service consumer system.

Data Encapsulation :

SOAP message
The basic unit of communication between SOAP nodes.
SOAP envelope
The outermost element information item of a SOAP message.
SOAP header
A collection of zero or more SOAP header blocks each of which might be targeted at any SOAP receiver within the SOAP message path.
SOAP header block
An element information item used to delimit data that logically constitutes a single computational unit within the SOAP header. The type of a SOAP header block is identified by the XML expanded name of the header block element information item.
SOAP body
A collection of zero or more element information items targeted at an ultimate SOAP receiver
SOAP fault
A SOAP element information item which contains fault information generated by a SOAP node.

Message Sender and Receiver Concepts

SOAP sender
A SOAP node that transmits a SOAP message.
SOAP receiver
A SOAP node that accepts a SOAP message.
SOAP message path
The set of SOAP nodes through which a single SOAP message passes. This includes the initial SOAP sender, zero or more SOAP intermediaries, and an ultimate SOAP receiver.
Initial SOAP sender
The SOAP sender that originates a SOAP message at the starting point of a SOAP message path. It can be a client application.
SOAP intermediary
A SOAP intermediary is both a SOAP receiver and a SOAP sender and is targetable from within a SOAP message. It processes the SOAP header blocks targeted at it and acts to forward a SOAP message towards an ultimate SOAP receiver.
Ultimate SOAP receiver
The SOAP receiver that is a final destination of a SOAP message. It can be a web service end point.

Monday, May 21, 2012

Enable Line Number in Eclipse


Generate Unique ID Using Java

Sometimes we need to generate unique ID for different purpose.Hear is a simple code block to do so. And ready to use .


public static String generateUniqueId () {
    UUID uuid = UUID.randomUUID();
    Date date = new Date();
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(uuid.toString());
    stringBuilder.append("-");
    stringBuilder.append(String.valueOf(date.getTime()));
   final String UNIQUEID = stringBuilder.toString();
   return UNIQUEID;
}


public static void main (String args[]) {
           System.out.println(PaymentUtil.generateUniqueId());
}



        Sample output : it will differ in every run :

       89c9f0ad-7c25-4955-9496-faf802976caf-1337661403009


Hot Eclipse Short Cut

Hear is some hot shortcut for eclipse user (java) :

Fix Code Shortcut :

  • Ctrl + 1

Indent Code : 
  • Ctrl + I
Format Code :
  • Ctrl +Shift + F
Quick Open Any File (or open resource) :
  • Ctrl + Shoft + R
Run :
  • Ctrl + F11
Debug : 
  • F11
See Outline of A Class :
  • Ctrl + O
Organize Import :
  • Ctrl + Shift + O 
Search In Project :
  • Ctrl + H
Find Next :
  • Ctrl + K
Find Previous :
  • Ctrl + Shift + K




shortcut to select column wise in notepad ++

I was almost giving up to find solution . Finally got it :)

To select a column in notepad++ use a simple shortcut :

"ALT +  Left Mouse Key (drag and drop way )"






Saturday, May 19, 2012

Singleton Design Pattern


Toady Mr. duffer go to his Guru named Goni to learn singleton design pattern.Let stay with Mr. duffer.

Singleton is one of the basic design patten. Name of these pattern comes from mathematical concept of singleton. In mathematics singleton is a set with exactly only one element . Example : Let S = {0} is a set with only one element . So set S is a singleton in mathematics . Hear is the end of background.

Now, i will describe singleton design pattern from software engineering view. Singleton design pattern is a conceptualization or a design pattern to restrict instantiation of a class only one object. And a global access point of that single instance across the system.

Further more :
GOF says, “Ensure a class has only one instance, and provide a global point of access to it. [GoF, p127].

     Example of singleton design pattern :
public class Singleton {
    private static Singleton singleInstance;

    private Singleton() {
    }
    public static Singleton getSingleInstance() {
        if (singleInstance.equals(null)) {
            synchronized (Singleton.class) {
                if (singleInstance.equals(null)) {
                    singleInstance = new Singleton();
                }
            }
        }
        return singleInstance;

    }

    public String helloSingleTon() {
        return "Hello Singles";
    }
}


When to use :
To coordinate actions across any software system with exactly one instance of a class. One can choose singleton design pattern to achieve these.
Some other use :
The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation.
  • Facade Objects are often Singletons because only one Facade object is required.
  • State objects are often Singletons.
Some points need to keep in mind in case of singleton design pattern :
  • It makes unit testing harder .
  • Access to the singleton in a multi-threaded context must be serialised 
  • Advocates of dependency injection would regard this as an anti-pattern, mainly due to its use of private and static methods
  • Sometimes singleton is actually is not a singleton.These issue can be explore with the article When a singleton is not a singleton?
Singleton Design Pattern n JAVA API

java.lang.Runtime#getRuntime()  java.awt.Desktop#getDesktop()

That's all. Thanks for stay with me through the journey of singleton .
Happy Coding.