Beruflich Dokumente
Kultur Dokumente
John Robertson
Staff Software Engineer
IBM
Fiona Lam
Software Engineer
IBM
Yaqian Fang
Software Engineer
IBM
Angela Baird
Angela Baird
IBM
Elena Nossova
Analyst/Programmer
Independent
18 Sep 2009
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.
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:
2. Expand the Java folder and click Java Project (see Figure 1).
Figure 1. Creating a project in Eclipse
3. Click Next.
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.
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
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
<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
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.
1. Right-click that package and select the options New > Class then
configure it as shown in Figure 9.
Figure 9. Creating a class
Once you have provided the package with a class, you can start writing the code for
the client, as shown in Listing 2.
package com.myfirst.wsClient;
import javax.xml.ws.BindingProvider;
Using Eclipse
After you have written the client application, try running it inside Eclipse:
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:
<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
================================= -->
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:
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:
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>.
Exit the server and client Java applications by typing "quit" in the separate command
windows then close each of the command window applications.
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
The view will appear in the bottom pane of the Eclipse IDE, as shown in Figure 16.
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.
3. 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
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.
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.");
}
}
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:
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:
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.
Section 7. Downloads
Download the Eclipse IDE for Java EE Developers.
Download Java SE 6.
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
Headers
Body
The body contains the message identification and its parameters. It is a child
element of the envelope.
Section 9. 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
• "Eclipse Project Resources" (developerWorks, Jan 2006) is an introduction to
Eclipse.
• Read about "W3C" - World Wide Web Consortium - Web Standards.
• Read about "WS-I" - Web Services Interoperability Organization.
• In the Architecture area on developerWorks, get the resources you need to
advance your skills in the architecture arena.
• Browse the technology bookstore for books on these and other technical topics.
• Discover the new Java SE 6 features.
• Learn more about The Apache Ant Project.
Discuss
• Check out developerWorks blogs and get involved in the developerWorks
community.
Fiona Lam
Fiona Lam is a Software Engineer and works for the Australia
Development Laboratory as part of IBM Tivoli Security Development.
Yaqian Fang
Yaqian Fang is a Software Engineer and also works for the Australia
Development Laboratory as part of IBM Tivoli Security Development.
Angela Baird
Angela Baird is a Staff Software Engineer and also works for the
Australia Development Laboratory as part of IBM Tivoli Security
Development.
Elena Nossova
Elena Nossova is an Analyst/Programmer and works in Brisbane,
Australia.