Create stand-alone Web services applications with Eclipse and Java SE 6: Part 2: The Web service client application

Use the Eclipse Integrated Development Environment (IDE) and Java Platform, Standard Edition (Java SE) 6 to create a stand-alone Web services application that can be run from the console. In this tutorial, the second in the series, continue getting familiar with the Eclipse IDE and its built-in feature the TCP/IP Monitor. View the network traffic between server and client applications and then run the applications from the command line.

John Robertson, Staff Software Engineer, IBM  

John RobertsonJohn Robertson is a Staff Software Engineer and works for the Australia Development Laboratory as part of IBM Tivoli Security Development.



Fiona Lam, Software Engineer, IBM  

Fiona LamFiona Lam is a Software Engineer and works for the Australia Development Laboratory as part of IBM Tivoli Security Development.



Yaqian Fang, Software Engineer, IBM  

Yaqian FangYaqian Fang is a Software Engineer and also works for the Australia Development Laboratory as part of IBM Tivoli Security Development.



Angela Baird, Angela Baird, IBM  

Angela Baird is a Staff Software Engineer and also works for the Australia Development Laboratory as part of IBM Tivoli Security Development.



Elena Nossova, Analyst/Programmer, Independent

Elena Nossova is an Analyst/Programmer and works in Brisbane, Australia.



18 September 2009

Also available in Chinese

Before you start

About this series

This tutorial series demonstrates how to create a stand-alone Web services server and client application that you can easily run from the command line with Java SE 6 rather than from within web application server containers. Using a simple Hello World example, you will leverage the Eclipse IDE, Java SE 6, and Apache Ant to easily create fully functioning Web services server and client applications. You will also use the TCP/IP Monitor to examine the communication traffic between the server and client, and use the Eclipse Web Services Explorer tool to test the Web Service.

About this tutorial

This tutorial, Part 2 of the series, describes the creation of a stand-alone Web service client application to communicate with the stand-alone Web service you developed and deployed in Part 1. You will be taken step-by-step through the development and deployment of the Web service client application using the Eclipse IDE, Java SE 6 and Ant.

Objectives

After completing this tutorial you should know:

  • How to create the client side of a Web service, using the Eclipse IDE to generate and compile the code using Java SE 6.
  • How to use the Ant Java-based build tool within the Eclipse IDE to run a special Java command to generate some of the code from the WSDL published in Part 1 of the series.
  • How to use the TCP/IP Monitor within the Eclipse IDE to observe, capture and validate the Web service's SOAP traffic between the server and client.
  • How to run the server and client applications directly from the command line outside of the Eclipse IDE.

Prerequisites

This tutorial includes simple steps written for beginning- to intermediate-level Java programmers with some working knowledge of the Java language and Ant builds. Novice to more advanced Java developers will gain some knowledge of how to build, deploy, and run stand-alone Web services servers and distributed clients to provide firewall-friendly remote communications and applications processing.

System requirements

To follow the examples, you need to download:

You don't have to download Ant, as its functionality is bundled with Eclipse. This tutorial uses the Ganymede Package for the Eclipse IDE for Java EE Developers.


Create a new project

You may recall from Part 1 that an Eclipse project contains the source code and other related files for your application. It lets you use the project as the code source container or to set up folders inside the project to organize files. You will need to create a new project to construct your Web service client:

  1. Select File > New > Project.
  2. Expand the Java folder and click Java Project (see Figure 1).

    Figure 1. Creating a project in Eclipse
    Creating a Project in Eclipse
  3. Click Next.
  4. Enter a project name, such as wsClientExample, when prompted, as shown in Figure 2.

    Figure 2. Entering project details in Eclipse
    Entering project details in Eclipse
  5. Select the Use default JRE radio button if it was previously selected by default; otherwise select the Use a project specific JRE radio button, ensuring it's Java SE 6.
  6. Click Finish to associate your project with the Java JDK you installed in Part 1.
  7. If you're prompted to switch Java perspective, click Yes.

    Your Eclipse environment should now have two projects listed in the Package Explorer, as shown in Figure 3. One project will be the one you created in Part 1 of the tutorial and the other will be the one you just created.

    Figure 3. Project Explorer in Eclipse
    Project Explorer in Eclipse
  8. Right click the src folder under the wsClientExample project and then select the menu options New > Package and enter a name for the client application package such as com.myfirst.wsClient as shown in Figure 4.

    Figure 4. Package creation in Eclipse
    Package creation in Eclipse

Generate the Web Services Client-side Code

To create the client-side code you will need to run the the wsimport task. As in the first part of the series, you will run this from an Ant script called build.xml:

  1. Right-click the project and select New > File.
  2. Enter the name build.xml, then click Finish (see Figure 5).
  3. Make sure this file opens with the Ant Editor by right-clicking it and selecting Open With > Ant Editor. From now on, whenever you double-click this file, it should open with the Ant Editor.

    Figure 5. Creating the build.xml file
    Creating a Project in Eclipse
  4. Enter the Ant project shown in Listing 1.
    Listing 1. Ant Script
    <project default="wsimport">
    
      <target name="wsimport">
        	
        <exec executable="{java.home}/../bin/wsimport">
        		
          <arg line="-keep -s ./src -p com.myfirst.wsClient 
              -d ./bin http://localhost:8080/wsServerExample?wsdl"/>
        		
        </exec>
        	
      </target>
    
    </project>
  5. Before running the Ant build.xml file, you must first go back to the project you created in Part 1 and start the service called RunService. To do this expand the project and right-click the RunService file and select Run As > Java Application.
  6. Make sure the Eclipse IDE console window displays the message saying that the service has started, as shown in Figure 6.

    Figure 6. Console with the service running
    Console with the service running
  7. To run the Ant build.xml file, return to this project (wsClientExample) and right-click Run As > Ant Build, which executes the Ant file.
  8. Make sure that this results in a BUILD SUCCESSFUL message in the Eclipse Console window, as shown in Figure 7.

    Figure 7. Ant Build Success
    Ant Build Success
  9. Return to the Eclipse project and refresh the project by right-clicking wsClientExample and selecting Refresh or by highlighting the project and pressing F5. You should now see the generated code to run the client under the new package com.myfirst.wsClient (see Figure 8).

    Figure 8. Generated Code
    Generated Code

What has happened is that the wsimport task generated the JAX-WS portable artifacts from the WSDL that is published when you ran RunService. This is why the service must be running first.

  • wsgen reads the service endpoint class and generates all the required artifacts for web service deployment and invocation.
  • wsimport reads the WSDL and generates all the required artifacts for web service development, deployment and invocation.

You will be using these generated classes in our Client application that we will create in the next section.


Create the Client Application

Now that you have generated the code for the Web Service's client, you will need to create the application that will use it under the package com.myfirst.wsClient:

  1. Right-click that package and select the options New > Class then configure it as shown in Figure 9.

    Figure 9. Creating a class
    Creating a class
  2. Create your class as public with a main method.

Once you have provided the package with a class, you can start writing the code for the client, as shown in Listing 2.

Listing 2. Client Application
package com.myfirst.wsClient;

import javax.xml.ws.BindingProvider;

public class SayHelloClient {

    public static void main(String args[]) {
		
        SayHelloService shs = new SayHelloService();
		
        SayHello sh = (SayHello) shs.getSayHelloPort();
		
        ((BindingProvider)sh).getRequestContext().put(BindingProvider.
            ENDPOINT_ADDRESS_PROPERTY, "http://localhost:8080/wsServerExample");

        System.out.println( ((BindingProvider)sh).toString() );

        System.out.println(sh.getGreeting("Fiona"));

    }
}

Run the Client Application

Using Eclipse

After you have written the client application, try running it inside Eclipse:

  1. Right-click SayHelloClient.java and select Run As > Java Application. The Eclipse IDE console window should be displayed. If it doesn't, go to the menu and select the options Window > Show View > Console. You should see the results of executing the Web Client as shown in Figure 10.

    Figure 10. Running the client application
    Running the client application

When you run the SayHelloClient application, it creates a new service, SayHelloService, which is one of the classes generated by the wsimport task you ran via the Ant script in Listing 1. It then gets the port, SayHello, which is a proxy to invoke operations on the target service endpoint. The client then gets the request context and adds the endpoint address, http://localhost:8080/wsServerExample, to the context which is a map used for processing request messages. There are two print statements, the first displays SayHello in readable format and the second displays the return greeting, Hello Fiona (see Figure 10).

When you're finished, you can stop the Web service by terminating it through the Eclipse console view.

Using a Script

To run without Eclipse you can modify the wsClientExample's build.xml so that it starts the server and the client applications inside separate shell windows:

  1. Double-click the build.xml file to edit it inside the Ant editor.
  2. Modify it as shown in Listing 3.
    Listing 3. Modified build.xml file
    <project default="runClient">
    
        <!-- ================================= 
                target: wsimport              
             ================================= -->
        <target name="wsimport" description="--> 
                Read the WSDL and generate the required artifacts">
            <exec executable="${java.home}/../bin/wsimport">
                <arg line="-keep -s ./src -p com.myfirst.wsClient -d ./bin 
                    http://localhost:8080/wsServerExample?wsdl"/>
            </exec>
        </target>
    
        <!-- ================================= 
                target: runServer              
             ================================= -->
        <target name="runServer" description="--> 
                Runs the Web service server from a terminal">
            <echo>
    Running the following command from the terminal to run the server:
    ${java.home}/bin/java -cp "${basedir}/../wsServerExample/bin" 
        com.myfirst.wsServer.RunService
           </echo>
            
            <exec dir="${java.home}/bin/" executable="cmd" spawn="true" 
            		os="Windows XP" description="runs on XP">
                <arg line="start cmd /K start cmd /K" />
                <arg line='${java.home}/bin/java -cp 
                	"${basedir}/../wsServerExample/bin" 
                	com.myfirst.wsServer.RunService' />
            </exec>
            
            <exec executable="xterm" spawn="true" os="Linux" 
                    description="Runs on Linux">
                <arg line="-e ${java.home}/bin/java -cp  
                	'${basedir}/../wsServerExample/bin' 
                	com.myfirst.wsServer.RunService"/>
            </exec>
        </target>
    
        <!-- ================================= 
                target: pause
             ================================= -->
        <target name="pause" depends="runServer" description="--> 
                Pauses briefly while the server starts">
            <sleep seconds="5"/>
        </target>
    	
        <!-- ================================= 
                target: runClient
             ================================= -->
        <target name="runClient" depends="pause" description="--> 
                Runs a Web service client from a terminal">
            <echo>
    Running the following command from the terminal to run the client:
    ${java.home}/bin/java -cp "${basedir}/bin" com.myfirst.wsClient.SayHelloClient
           </echo>
    
            <exec dir="${java.home}/bin/" executable="cmd" spawn="true" 
                    os="Windows XP" description="Runs on XP">
                <arg line="start cmd /K start cmd /K" />
                <arg line='${java.home}/bin/java -cp "${basedir}/bin" 
                    com.myfirst.wsClient.SayHelloClient' />
            </exec>
            
            <exec executable="xterm" spawn="true" os="Linux" 
                    description="Runs on Linux">
                <arg line="-hold -e ${java.home}/bin/java -cp '${basedir}/bin' 
                    com.myfirst.wsClient.SayHelloClient" />
            </exec>
        </target>
    
    </project>

NOTE: to run on linux, you may have to set JAVA_HOME first; at the command line type: set JAVA_HOME=<your/java/home>

The new build.xml has two new targets, runServer and runClient. You may have noticed that you also updated the default target value in the first line so that it doesn't run the wsimport task but the runClient target instead. Also, note that runClient also has a dependency on the pause which means that although the default is runClient, it will pause first. The pause task depends on the runServer. This allows for a pause before the client has run for the server to start properly. So the runServer will run first. Another item of note is the os value. This indicates which operating system (OS) command will be executed and is determined by the Java Virtual Machine (JVM). The OS is set in the os.name system property. The modified build.xml script only includes Windows and Linux, but you can add applicable ones for your environment and change the Ant <exec> task if required. (See Resources for more information about Ant).

Note the <echo> section in bold is not indented like the other lines. This is because all characters are echoed, including any whitespace characters. This means on the console window the messages won't have leading spaces (Figure 11). When the script is run, it will display (echo) the command you can run from the console to run the server application.

To test the script excecution, you can optionally make some modifications to the client application so that you can run it until you quit, as follows:

  1. Double-click SayHelloClient.java to edit the file as follows:
    Listing 4. Modified SayHelloClient.java file
    package com.myfirst.wsClient;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    import javax.xml.ws.BindingProvider;
    import com.myfirst.wsClient.SayHello;
    import com.myfirst.wsClient.SayHelloService;
    
    public class SayHelloClient {
    
        public static void main(String[] args) {
    		
            SayHelloService shs = new SayHelloService();
            SayHello sh = (SayHello) shs.getSayHelloPort();
            ((BindingProvider) sh ).getRequestContext().put(
                BindingProvider.ENDPOINT_ADDRESS_PROPERTY, 
                "http://localhost:8080/wsServerExample");
            System.out.println(((BindingProvider) sh).toString());
    
            String userName = null;
            boolean exit = false;
            while (!exit) {
                System.out.print("\nPlease enter your name 
                    (type 'quit' to exit): ");
                BufferedReader br = new BufferedReader(
                    new InputStreamReader(System.in));
                try {
                    userName = br.readLine();
                } catch (IOException e) {
                    System.out.println("Error reading name.");
                    System.exit(1);
                }
                if (!(exit = userName.trim().equalsIgnoreCase("quit") || 
                        userName.trim().equalsIgnoreCase("exit"))) {
                    System.out.println(sh.getGreeting(userName));
                }
            }
            System.out.println("\nThank you for running the client.");
        }
    }

When the client application is running, it will continue to ask for input until quit or exit is entered. To run the Ant script:

  1. Right-click build.xml and Run As > Ant Build.
  2. Make sure that this results in a BUILD SUCCESSFUL message in the Eclipse Console Window, as shown in Figure 11.

    Figure 11. Ant build success and echoed messages.
    Ant build success and echoed messages.

After executing the Ant script, two command windows should launch, one for the server application (see Figure 12) and one for the client application (see Figure 13). The client window will ask you to enter a name, continuing until you quit the application. Whenever you enter a name, the modified SayHelloClient application iterates through a while loop where it sends the name you entered to the server which returns the greeting, displayed as Hello <name>.

Figure 12. Command window for the server
Command window for the server
Figure 13. Command window for the client
Command window for the client

Exit the server and client Java applications by typing "quit" in the separate command windows then close each of the command window applications.


Monitor the Communications with a SOAP Monitor

Configure TCP/IP Monitor in Eclipse

Now that you have created a server and a client, you can monitor the SOAP traffic using the Eclipse TCP/IP Monitor. The monitor is a simple server that watches all requests and responses flowing between the server and the client as depicted in Figure 14.

Figure 14. Server and Client SOAP traffic
Server and Client SOAP traffic
  1. To view this activity, you will need to open the TCP/IP Monitor View by selecting Window > Show View > Other > Debug > TCP/IP Monitor as shown in Figure 15.

    Figure 15. Show TCP/IP Monitor
    how TCP/IP Monitor

The view will appear in the bottom pane of the Eclipse IDE, as shown in Figure 16.

Figure 16. View TCP/IP Monitor
View TCP/IP Monitor
  1. To configure the TCP/IP Monitor, select Windows > Preferences and expand Run/Debug and click TCP/IP Monitor as shown in Figure 17.

    Figure 17. Add TCP/IP Monitor.
    Add TCP/IP Monitor.

From this window (Figure 17), you can manage multiple TCP/IP monitoring servers listed in the table with the Start and Stop buttons. You can also add, edit, remove, start or stop the available servers. The Status column indicates whether a monitor has been started or stopped.

  1. Check the box to show the TCP/IP Monitor view when there is activity then click the Add... button to define a new set of configuration options, as shown in Figure 17. Enter the following details as shown in Figure 18:

    Figure 18. Configure TCP/IP Monitor
    Configure TCP/IP Monitor


    Option Descriptions
    • The Local monitoring port is a unique port number on your local machine, such as 8081.
    • The Host name is the name or IP address of the machine you are using to run the server such as localhost.
    • The Port is the port number of the remote server, such as 8080.
    • The Type is the request type sent from the browser, either HTTP or TCP/IP.
    • The Communication Timeout is the length of time, in milliseconds, before the TCP/IP connection to a server can be ended.
  1. Click OK to save your changes.

Update the client code

Next, you will need to make some changes to the client code in order to redirect the web service through the TCP/IP monitor. The endpoint of the web service client needs to be changed since the TCP/IP monitor listens on port 8081. The updated code is shown in Listing 5:

Listing 5. Client Application
package com.myfirst.wsClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.xml.ws.BindingProvider;
import com.myfirst.wsClient.SayHello;
import com.myfirst.wsClient.SayHelloService;

public class SayHelloClient {

    public static void main(String[] args) {
		
        SayHelloService shs = new SayHelloService();
        SayHello sh = (SayHello) shs.getSayHelloPort();
        ((BindingProvider) sh ).getRequestContext().put(
            BindingProvider.ENDPOINT_ADDRESS_PROPERTY, 
            "http://localhost:8081/wsServerExample");
        System.out.println(((BindingProvider) sh).toString());

        String userName = null;
        boolean exit = false;
        while (!exit) {
            System.out.print("\nPlease enter your name 
                (type 'quit' to exit): ");
            BufferedReader br = new BufferedReader(
                new InputStreamReader(System.in));
            try {
                userName = br.readLine();
            } catch (IOException e) {
                System.out.println("Error reading name.");
                System.exit(1);
            }
            if (!(exit = userName.trim().equalsIgnoreCase("quit") || 
                    userName.trim().equalsIgnoreCase("exit"))) {
                System.out.println(sh.getGreeting(userName));
            }
        }
        System.out.println("\nThank you for running the client.");
    }
}

Run the Web Service

Run the Ant script again: Right-click build.xml you created to run the server and the client, and Run As > Ant Build.

Once again, two command windows should launch, one for the server and one for the client. Enter your name as you did previously.

Check the TCP/IP Monitor view, which should look similar to the following picture, Figure 19:

Figure 19. TCP/IP Monitor Results
TCP/IP Monitor Results

What you see is the display request and response pairs that are being routed through the TCP/IP Monitor. For closer inspection, the full headers are shown in Listing 6 and 7:

Listing 6. Request Header
POST /wsServerExample HTTP/1.1
SOAPAction: ""
Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Content-Type: text/xml; charset=utf-8
User-Agent: Java/1.6.0
Host: localhost:8081
Connection: keep-alive
Content-Length: 226

<?xml version="1.0" encoding="UTF-8"?>
  <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Body>
    <ns2:getGreeting xmlns:ns2="http://wsServer.myfirst.com/">
      <arg0>Fiona</arg0>
    </ns2:getGreeting>
  </S:Body>
  </S:Envelope>
Listing 7. Response Header
HTTP/1.1 200 OK
Content-type: text/xml; charset=utf-8
Transfer-encoding: chunked

fc
<?xml version="1.0" encoding="UTF-8"?>
  <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
  <S:Body>
    <ns2:getGreetingResponse xmlns:ns2="http://wsServer.myfirst.com/">
      <return>Hello Fiona</return>
    </ns2:getGreetingResponse>
  </S:Body>
  </S:Envelope>
0

As you can see bolded in the request header envelope is the input you entered in the command window of the client application, in this case Fiona. Now looking at the response header envelope, you can see the return response, in this case Hello Fiona.

Optional Activity

You can ensure your Web service SOAP traffic is WS-I compliant by clicking the icon circled in red of Figure 18. This will prompt you to save a log file which will then be validated for compliance. You can open this log in an XML editor to examine its contents.


Downloads

Download the Eclipse IDE for Java EE Developers.

Download Java SE 6.


Appendix: A brief overview of Web services terms and acronyms

WS-I - Web services interoperability

WS-I is an open industry organization designed to promote Web service interoperability across platforms, operating systems, and programming languages.

Envelope

The envelope is part of a SOAP message. It defines a framework for describing what is in the message and how to process it. A SOAP message is an envelope consisting of zero or more headers and one body. It is the top element of the XML document and provides a container for control information, the address of the message, plus the message itself.

Headers

Headers transport any control information. It is a child element of the envelope.

Body

The body contains the message identification and its parameters. It is a child element of the envelope.


Summary

Creating, generating and publishing a Web Service Server is as simple as using Eclipse and of course Java SE 6. With these tools you can develop simple Web Services Servers and Clients with little effort.

Resources

Learn

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into SOA and web services on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=SOA and web services, Java technology
ArticleID=428604
ArticleTitle=Create stand-alone Web services applications with Eclipse and Java SE 6: Part 2: The Web service client application
publish-date=09182009