Tuesday, 6 December 2011

Programming without programming #1

One criticism levelled at java is the amount of programming you have to do to accomplish simple tasks. Its true that Java used to require seemingly large amounts of code before it did anything useful (often termed boilerplate code), but things have changed. This is mainly to do with annotations (introduced in Java 5) and a huge array of tools and frameworks available to solve common problems.

Today I'm going to show you how to create a web service client from WSDL. You'll be suprised how quick and easy it is to get this done using a few common tools.... and we're only going to write 5 lines of code!

You will need;

  • Eclipse
  • Maven 2

Step 1
Create a new maven project in eclipse. Skip archetype selection to create a simple project. We're going to use Apache CXF, a popular open source web service framework. CXF gives us a wsdl2java code generation plugin to do all the programming for us. Once we've added the plugin to our POM, it looks like this;

<project xmlns="http://maven.apache.org/POM/4.0.0"
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <name>Programming without programming #1</name>


Step 2
The webservice we're going to call is a public stock quote service provided by WebserviceX.net. Download the WSDL from http://www.webservicex.net/stockquote.asmx?WSDL and put it in /src/main/resources/wsdl/stockquote.wsdl in your workspace.

Step 3
Run maven generate-sources and notice that some classes have been generated in the package net.webservicex, don't forget to add src/generated/java to your project's build path.

Step 4
Finally we have to do a bit of programming ourselves. Here come our 5 lines! Use the eclipse new class wizard to create a new class, ticking the box to create a main method. Inside the class's main method we're going to create an instance of the generated soap class, give it an endpoint and get a stock quote.

String endpoint = "http://www.webservicex.net/stockquote.asmx";

URL wsdlUrl = StockCheck.class.getClassLoader().getResource("wsdl/stockquote.wsdl");
StockQuoteSoap soapRequest = new StockQuote(wsdlUrl).getStockQuoteSoap();
((BindingProvider)soapRequest).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpoint);


Finally, run your class and have a look at the output. Hopefully you should see some response XML with details of Google's current stocks. Check out the screenshot of my workspace.

No comments:

Post a Comment