Friday 27 September 2013

Generating a Web Service Java Client from a given WSDL using Eclipse

Objective

To develop a Java web service client from a given WSDL using Eclipse IDE.

Environment

Java 7
Eclipse IDE (Juno)
A WS wsdl xml file

Development

  • Open your Eclipse IDE and Workspace.
  • Create a new Java Project (File -> New -> Java Project).
  • Give Project name as "TestWSClient" and click on Finish
  • Copy the given WSDL file under Project "TestWSClient" root folder.
  • Right click on Project and select New -> Other -> Web Service Client  and then Next.
  • A new window will come up, give Service Definition value by clicking on Browse -> Browser and then select the WSDL file we copied earlier into Project root folder. Click OK -> Finish.

  • Ensue that the actual WS for which the WSDL is present exists and running; otherwise we will get exception in above step. At successful creation we will see many java classes get created under project src folder with the name ending with Stub, Proxy, Location, etc.

Testing

  • Now the Java APIs are generated for the WS client, let us write a simple Java class to test how can we call operations exposed by WS.
  • Create a Java class with name "Client" (File -> New -> Class) and write code similar to what shown below in your main method:
AlarmingServiceLocator asLocator = new AlarmingServiceLocator();
asLocator.setEndpointAddress("AlarmPort",
                    "http://localhost:9001/alarmingService");
Alarm service = asLocator.getAlarmPort();
service.sendAlarm("test mahesh alarm");

  • What matters here is the right parameters on call to setEndpointAddress() method when called from Locator class. And then how you get the reference to your Service from Locator which will then be used to call the WS operations (here we called sendAlarm() operation).
  • In case you face some compilation or runtime exceptions just browse through the generated Location, Stub and Proxy classes to get the idea of how things work.
Thanks!

2 comments:

  1. In case the WS exposed on HTTPS, you will have to import the WS's certificate into your JDK certificate trust store. Kindly refer to my bog Java Keytool usage for exact command and steps to do the same.

    ReplyDelete
  2. The source code can be found here: https://github.com/mchopker/myprojects.git

    ReplyDelete