Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Simple Java SOAP Web Service Using JDK Tools

DZone's Guide to

Simple Java SOAP Web Service Using JDK Tools

A tutorial on how to use JDK tools to publish and consume a simple SOAP web service.

· Java Zone
Free Resource

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

The JDK allows us to both publish and consume a web service using some of its tools. The sample service “Hello world” will be responsible for saying hello to the name that I’ll send it to that service. This example also includes creating a client for this service (you can follow the same steps in client to communicate with any service you like).

A. Creating the Service

1. Construct Simple Hello Class

Suppose you have a simple class that receives a string and return another string

package wsserver;

public class Hello {
	public String sayHello(String name) {
		return "Hello " + name;
	}
}


2. Convert Hello Class to a Web Service

Simply we can convert this class to be a web service using some annotations

  • @WebService — This identifies the class as being a web service.

  • @SOAPBinding(style=SOAPBinding.Style.RPC) — This specifies the type of the communication, in this case RPC.

package wsserver;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService
@SOAPBinding(style=SOAPBinding.Style.RPC)
public class Hello {
	public String sayHello(String name) {
		return "Hello " + name;
	}
}

3. Publish Hello Service

To publish this service, we can use the Endpoint class. We will provide the publish method with any URL and an instance of our service class

package wsserver;

import javax.xml.ws.Endpoint;

public class ServiceStarter {
	public static void main(String[] args) {
		String url = "http://localhost:1212/hello";
		Endpoint.publish(url, new Hello());
		System.out.println("Service started @ " + url);
	}
}

4. Compile Code

We can compile our two classes using the simple Javac command:

javac -d . *.java

5. Start Service

We can start our service by running ServiceStarter class using the following Java command:

java wsserver/ServiceStarter

6. Check Running Service

Now the service has been started, you can check your service by seeing its WSDL file by getting the url in setp 3. We can get the Service WSDL file by appending “?wsdl” to the URL: http://localhost:1212/hello?wsdl

The result of the WSDL file will look like the following XML file:

<?xml version="1.0" encoding="UTF-8"?><!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.6 in JDK 6. --><!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.6 in JDK 6. -->
<definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://wsserver/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://wsserver/" name="HelloService">
    <types></types>
    <message name="sayHello">
        <part name="arg0" type="xsd:string"></part>
    </message>
    <message name="sayHelloResponse">
        <part name="return" type="xsd:string"></part>
    </message>
    <portType name="Hello">
        <operation name="sayHello">
            <input message="tns:sayHello"></input>
            <output message="tns:sayHelloResponse"></output>
        </operation>
    </portType>
    <binding name="HelloPortBinding" type="tns:Hello">
        <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"></soap:binding>
        <operation name="sayHello">

            <soap:operation soapAction=""></soap:operation>
            <input>
                <soap:body use="literal" namespace="http://wsserver/"></soap:body>
            </input>
            <output>
                <soap:body use="literal" namespace="http://wsserver/"></soap:body>
            </output>
        </operation>
    </binding>
    <service name="HelloService">
        <port name="HelloPort" binding="tns:HelloPortBinding">
            <soap:address location="http://localhost:1212/hello"></soap:address>
        </port>
    </service>
</definitions>

B. Creating the client

The first thing we should have is an interface of that service class to be able to call its methods using java code. After that we'll write some code to connect to that service. Fortunately there is a tool in JDK called wsimport that can do all of that if you just provided it with a valid WSDL URL.

1. Import Service Interface and Service Client Creator Class

Using wsimport tool we will write the following command:

wsimport -d . -p wsclient -keep http://localhost:1212/hello?wsdl

The -p arg tells the tool to put the generated classes into a specific package. Executing this command will result in generating two classes. The first class, called Hello.java and its interface that contains our method sayHello.

The code should be something like this:

package wsclient;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.6 in JDK 6
 * Generated source version: 2.1
 *
 */
@WebService(name = "Hello", targetNamespace = "http://wsserver/")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface Hello {

    /**
     *
     * @param arg0
     * @return
     *     returns java.lang.String
     */
    @WebMethod
    @WebResult(partName = "return")
    public String sayHello(
        @WebParam(name = "arg0", partName = "arg0")
        String arg0);

}

The second file would be called HelloService.java, and it will contain the methods that would help us to connect to our service we are only concerned with the no-arg constructor and the getHelloPort() method:

package wsclient;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.6 in JDK 6
 * Generated source version: 2.1
 *
 */
@WebServiceClient(name = "HelloService", targetNamespace = "http://wsserver/", wsdlLocation = "http://localhost:1212/hello?wsdl")
public class HelloService
    extends Service
{

    private final static URL HELLOSERVICE_WSDL_LOCATION;
    private final static Logger logger = Logger.getLogger(wsclient.HelloService.class.getName());

    static {
        URL url = null;
        try {
            URL baseUrl;
            baseUrl = wsclient.HelloService.class.getResource(".");
            url = new URL(baseUrl, "http://localhost:1212/hello?wsdl");
        } catch (MalformedURLException e) {
            logger.warning("Failed to create URL for the wsdl Location: 'http://localhost:1212/hello?wsdl', retrying as a local file");
            logger.warning(e.getMessage());
        }
        HELLOSERVICE_WSDL_LOCATION = url;
    }

    public HelloService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public HelloService() {
        super(HELLOSERVICE_WSDL_LOCATION, new QName("http://wsserver/", "HelloService"));
    }

    /**
     *
     * @return
     *     returns Hello
     */
    @WebEndpoint(name = "HelloPort")
    public Hello getHelloPort() {
        return super.getPort(new QName("http://wsserver/", "HelloPort"), Hello.class);
    }

    /**
     *
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the <code>features</code> parameter will have their default values.
     * @return
     *     returns Hello
     */
    @WebEndpoint(name = "HelloPort")
    public Hello getHelloPort(WebServiceFeature... features) {
        return super.getPort(new QName("http://wsserver/", "HelloPort"), Hello.class, features);
    }

}

2. Invoke the Web Service

We are now ready to write the code responsible for invoking the web service by making a new instance of the HelloService class, we are ready to get Hello interface by calling the method getHelloPort() from the HelloService instance. After that we can call the method and get the response as a simple Java method:

package wsclient;

public class HelloClient {
	public static void main(String[] args) {
		HelloService service = new HelloService();
		Hello hello = service.getHelloPort();
		String text = hello.sayHello("hany");
		System.out.println(text);
	}
}

3. Compile Classes and Run

javac -d . *.java
java wsclient/HelloClient

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:
soap ,web service ,web service clients ,jdk

Published at DZone with permission of Hany Ahmed. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}