Create a Web Service Client with JAX-WS

This example shows how to create a web service client using JAX-WS reference implementation and its tool 'wsimport'. JAX-WS RI can be downloaded from Sun (http://java.sun.com). To create the web service client we need an existing web service, so we will use the one created in the example 'Create a simple Web Service': Click here to go to the 'Create a simple Web Service' example So we assume the web service is deployed on our local computer and it listens to port 8080. Go to the bin directory in the jax-ws ri installation directory and run the command wsimport.bat (if Windows, else wsimport.sh) and pass the url to the wsdl-file as a parameter. wsimport http://localhost:8080/JavaDbExamplesWeb/JavadbWebServiceService?WSDL There are a number of options you can pass to the wsimport utility so you might want to run wsimport -help to find out more. For example, you might want to use the option -keep to prevent the wsimport utility to delete the .java files after compilation. Now the utility has read the wsdl-file, created the necessary classes and compiled them for us to use. We can now create the class that will use them and call the web service.

package com.javadb.examples;

import com.javadb.ws.example.JavadbWebService;
import com.javadb.ws.example.JavadbWebServiceService;

/**
 *
 * @author www.javadb.com 
 */
public class Main {

    public void callWebService() {

        /* Note, the JavadbWebServiceService class has two constructors.
         * The default one that we use here uses the wsdl-location that was
         * specified at the time of the generation of the client classes, 
         * i.e. localhost. If the service is deployed at 
         * another location you need to use the constructor:
         * public JavadbWebServiceService(URL wsdlLocation, QName serviceName)
         */
        JavadbWebServiceService service = new JavadbWebServiceService();
        JavadbWebService port = service.getJavadbWebServicePort(); 
        
        String currentTime = port.getTime();
        
        System.out.println("Current time is: " + currentTime);
        
        
    }

    public static void main(String[] args) {
        new Main().callWebService();
    }
}
Note that you need the genereated classes and the jax-ws libraries in the classpath when you compile and run the above class. That is easiest done by pointing them out in your project properties in the IDE. The output looks something like this: Current time is: 15:54
Read More... Create a Web Service Client with JAX-WS

Create a simple Web Service

This code example shows how to create a simple web service. We use the annotation @WebService to declare the class as a such. The annotation @WebMethod is provided at method level to declare it as an operation for the web service. The operation getTime of the JavadbWebService simply returns the current time.
package com.javadb.ws.example;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.jws.WebMethod;
import javax.jws.WebService;

/**
 *
 * @author www.javadb.com 
 */

@WebService()
public class JavadbWebService {
    
    @WebMethod
    public String getTime() {
        
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        return (sdf.format(calendar.getTime()));
        
    }

}
The result of a call to the operation getTime produces something like this: 14:15 This is the SOAP request and response to the web service:

    
    
        
    






    
        
            14:15
        
    



Article from www.javadb.com/create-a-simple-web-service
Read More... Create a simple Web Service

Using a Message Handler to alter the SOAP Header in a Web Service Client

Sometimes you need to insert information in the soap header when calling a web service. Perhaps the service needs authentication information that needs to be set. This example shows how to set the security information for a Web Service that is deployed on a Weblogic server using JAX-WS and SAAJ. First we need to create the actual handler which implements the SOAPHandler interface. Next we need to create the class that implements the HandlerResolver interface. This class decides what handlers should be called and in what specific order. The handler above is added to this class. Finally we need to add the HandlerResolver instance to the Web Service Client. By default the SOAP header is empty, but this is what we want the header to look like on the outbound call (the call to the web service):

                                   
                                        
               TestUser
               TestPassword
          
     

In our handler we need to do the implementation of a few methods but it is only the handleMessage() method that is of essence here. This is what our handler class looks like:
package com.javadb.ws.example;

import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

/**
 *
 * @author www.javadb.com
 */
public class HeaderHandler implements SOAPHandler {

    public boolean handleMessage(SOAPMessageContext smc) {

        Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

        if (outboundProperty.booleanValue()) {

            SOAPMessage message = smc.getMessage();

            try {

                SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope();
                SOAPHeader header = envelope.addHeader();

                SOAPElement security =
                        header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

                SOAPElement usernameToken =
                        security.addChildElement("UsernameToken", "wsse");
                usernameToken.addAttribute(new QName("xmlns:wsu"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

                SOAPElement username =
                        usernameToken.addChildElement("Username", "wsse");
                username.addTextNode("TestUser");

                SOAPElement password =
                        usernameToken.addChildElement("Password", "wsse");
                password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
               password.addTextNode("TestPassword");

                //Print out the outbound SOAP message to System.out
                message.writeTo(System.out);
                System.out.println("");
                
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {
            try {
                
                //This handler does nothing with the response from the Web Service so
                //we just print out the SOAP message.
                SOAPMessage message = smc.getMessage();
                message.writeTo(System.out);
                System.out.println("");

            } catch (Exception ex) {
                ex.printStackTrace();
            } 
        }


        return outboundProperty;

    }

    public Set getHeaders() {
        //throw new UnsupportedOperationException("Not supported yet.");
        return null;
    }

    public boolean handleFault(SOAPMessageContext context) {
        //throw new UnsupportedOperationException("Not supported yet.");
        return true;
    }

    public void close(MessageContext context) {
    //throw new UnsupportedOperationException("Not supported yet.");
    }
}
The handler resolver that is to contain the SOAP handler above looks like this:
package com.javadb.ws.example;

import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;

/**
 *
 * @author www.javadb.com
 */
public class HeaderHandlerResolver implements HandlerResolver {
    
public List getHandlerChain(PortInfo portInfo) {
      List handlerChain = new ArrayList();

      HeaderHandler hh = new HeaderHandler();

      handlerChain.add(hh);

      return handlerChain;
   }
}
Finally we need to add the handler resolver to our web service client class.
   JavadbWebServiceService service = new JavadbWebServiceService();

   HeaderHandlerResolver handlerResolver = new HeaderHandlerResolver();
   service.setHandlerResolver(handlerResolver);

   JavadbWebService port = service.getJavadbWebServicePort();
        
   //Call web service
   String currentTime = port.getTime();
        
   System.out.println("Current time is: " + currentTime);
To find out how to generate the web service client classes check out this example: Create a Web Service Client with JAX-WS

This is an article from http://www.javadb.com/using-a-message-handler-to-alter-the-soap-header-in-a-web-service-client
Read More... Using a Message Handler to alter the SOAP Header in a Web Service Client