java Web Services IBM
-
Upload
venu-kongara -
Category
Documents
-
view
221 -
download
0
Transcript of java Web Services IBM
-
8/13/2019 java Web Services IBM
1/21
Copyright IBM Corporation 2009 Trademarks
Create stand-alone Web services applications with Eclipse and
Java SE 6: Part 2: The Web service client application
Page 1 of 21
Create stand-alone Web services applications with
Eclipse and Java SE 6: Part 2: The Web service client
application
John Robertson
Staff Software Engineer
IBMFiona Lam
Software Engineer
IBMYaqian Fang
Software Engineer
IBMAngela Baird
Angela Baird
IBMElena Nossova
Analyst/Programmer
Independent
18 September 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.
View more content in this series
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
http://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/legal/copytrade.shtmlhttp://www.ibm.com/developerworks/edu/ws-dw-ws-eclipse-javase1.htmlhttp://www.ibm.com/developerworks/edu/ws-dw-ws-eclipse-javase1.htmlhttp://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtml -
8/13/2019 java Web Services IBM
2/21
developerWorks ibm.com/developerWorks/
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 2 of 21
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 tutorialThis 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.
ObjectivesAfter 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 touse 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.
PrerequisitesThis 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 Webservices servers and distributed clients to provide firewall-friendly remote communications and
applications processing.
System requirementsTo follow the examples, you need to download:
Eclipse IDE for Java EE Developers
Java SE 6
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 projectYou 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.
http://localhost/var/www/apps/conversion/tmp/scratch_1/#http://localhost/var/www/apps/conversion/tmp/scratch_1/#http://localhost/var/www/apps/conversion/tmp/scratch_1/#http://localhost/var/www/apps/conversion/tmp/scratch_1/# -
8/13/2019 java Web Services IBM
3/21
-
8/13/2019 java Web Services IBM
4/21
-
8/13/2019 java Web Services IBM
5/21
ibm.com/developerWorks/ developerWorks
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 5 of 21
8. Right click the srcfolder under thewsClientExampleproject and then select the menu
options New > Packageand enter a name for the client application package such as
com.myfirst.wsClient as shown in Figure 4.
Figure 4. Package creation in Eclipse
Generate the Web Services Client-side Code
To create the client-side code you will need to run the thewsimporttask. 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).
-
8/13/2019 java Web Services IBM
6/21
developerWorks ibm.com/developerWorks/
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 6 of 21
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
4. Enter the Ant project shown in Listing 1.
Listing 1. Ant Script
5. Before running the Ant build.xmlfile, you must first go back to the project you created in Part
1and start the service called RunService. To do this expand the project and right-click the
RunService file and select Run As > Java Application.
-
8/13/2019 java Web Services IBM
7/21
ibm.com/developerWorks/ developerWorks
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 7 of 21
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
7. To run the Ant build.xmlfile, 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 SUCCESSFULmessage in the Eclipse Console window, as
shown in Figure 7.
Figure 7. Ant Build Success
9. Return to the Eclipse project and refresh the project by right-clickingwsClientExampleand
selecting Refreshor 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
What has happened is that thewsimporttask 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.
wsgenreads the service endpoint class and generates all the required artifacts for web
service deployment and invocation.
wsimportreads 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.
-
8/13/2019 java Web Services IBM
8/21
developerWorks ibm.com/developerWorks/
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 8 of 21
Create the Client ApplicationNow 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 > Classthen configure it as shown in
Figure 9.
Figure 9. Creating a class
2. Create your class as publicwith 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 Applicationpackage com.myfirst.wsClient;
import javax.xml.ws.BindingProvider;
public class SayHelloClient {
public static void main(String args[]) {
SayHelloService shs = new SayHelloService();
-
8/13/2019 java Web Services IBM
9/21
ibm.com/developerWorks/ developerWorks
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 9 of 21
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.javaand 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 asshown in Figure 10.
Figure 10. Running the client application
When you run the SayHelloClientapplication, it creates a new service, SayHelloService, which
is one of the classes generated by thewsimporttask 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 SayHelloin 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.xmlso that it starts the server
and the client applications inside separate shell windows:
1. Double-click the build.xmlfile to edit it inside the Ant editor.
2. Modify it as shown in Listing 3.
Listing 3. Modified build.xml file
-
8/13/2019 java Web Services IBM
10/21
developerWorks ibm.com/developerWorks/
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 10 of 21
================================= -->
Running the following command from the terminal to run the server:
${java.home}/bin/java -cp "${basedir}/../wsServerExample/bin"
com.myfirst.wsServer.RunService
Running the following command from the terminal to run the client:
${java.home}/bin/java -cp "${basedir}/bin" com.myfirst.wsClient.SayHelloClient
-
8/13/2019 java Web Services IBM
11/21
ibm.com/developerWorks/ developerWorks
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 11 of 21
NOTE: to run on linux, you may have to set JAVA_HOME first; at the command line type: set
JAVA_HOME=
The new build.xmlhas two new targets, runServerand runClient. You may have noticed that
you also updated the defaulttarget value in the first line so that it doesn't run the wsimporttask
but the runClienttarget instead. Also, note that runClientalso 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 runServerwill run first. Another item of note is the osvalue. 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.namesystem property. The modified build.xmlscript only includes Windows
and Linux, but you can add applicable ones for your environment and change the Ant task
if required. (See Resourcesfor more information about Ant).
Note the 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:
3. Double-click SayHelloClient.javato edit the file as follows:
Listing 4. Modified SayHelloClient.java filepackage 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(
-
8/13/2019 java Web Services IBM
12/21
developerWorks ibm.com/developerWorks/
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 12 of 21
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 quitor exitis entered.
To run the Ant script:
4. Right-click build.xmland Run As > Ant Build.
5. Make sure that this results in a BUILD SUCCESSFULmessage in the Eclipse Console Window,as shown in Figure 11.
Figure 11. 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
SayHelloClientapplication iterates through a whileloop where it sends the name you entered to
the server which returns the greeting, displayed as Hello .
Figure 12. Command window for the server
-
8/13/2019 java Web Services IBM
13/21
ibm.com/developerWorks/ developerWorks
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 13 of 21
Figure 13. Command window for the client
Exit the server and client Java applications by typing "quit" in the separate command windows thenclose 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
1. To view this activity, you will need to open the TCP/IP Monitor View by selecting Window >
Show View > Other > Debug > TCP/IP Monitoras shown in Figure 15.
Figure 15. Show TCP/IP Monitor
-
8/13/2019 java Web Services IBM
14/21
developerWorks ibm.com/developerWorks/
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 14 of 21
The view will appear in the bottom pane of the Eclipse IDE, as shown in Figure 16.
Figure 16. View TCP/IP Monitor
2. To configure the TCP/IP Monitor, select Windows > Preferencesand expand Run/Debug
and click TCP/IP Monitoras shown in Figure 17.
Figure 17. Add TCP/IP Monitor.
-
8/13/2019 java Web Services IBM
15/21
ibm.com/developerWorks/ developerWorks
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 15 of 21
From this window (Figure 17), you can manage multiple TCP/IP monitoring servers listed in the
table with the Startand Stopbuttons. You can also add, edit, remove, start or stop the available
servers. The Statuscolumn 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.
-
8/13/2019 java Web Services IBM
16/21
developerWorks ibm.com/developerWorks/
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 16 of 21
The Communication Timeout is the length of time, in milliseconds, before the TCP/IP
connection to a server can be ended.
4. Click OKto save your changes.
Update the client codeNext, 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.xmlyou created to run the server and the client, and
Run As > Ant Build.
-
8/13/2019 java Web Services IBM
17/21
ibm.com/developerWorks/ developerWorks
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 17 of 21
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
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 HeaderPOST /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-aliveContent-Length: 226
Fiona
Listing 7. Response HeaderHTTP/1.1 200 OK
Content-type: text/xml; charset=utf-8
Transfer-encoding: chunked
fc
Hello Fiona
0
-
8/13/2019 java Web Services IBM
18/21
developerWorks ibm.com/developerWorks/
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 18 of 21
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.
http://java.sun.com/javase/downloads/index.jsphttp://www.eclipse.org/downloads -
8/13/2019 java Web Services IBM
19/21
ibm.com/developerWorks/ developerWorks
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 19 of 21
Resources
"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 yourskills in the architecture arena.
Browse the technology bookstorefor books on these and other technical topics.
Discover the new Java SE 6features.
Learn more about The Apache Ant Project.
Check out developerWorks blogsand get involved in the developerWorks community.
http://www.ibm.com/developerworks/communityhttp://www.ibm.com/developerworks/blogs/http://ant.apache.org/http://java.sun.com/javase/6/features.jsphttp://www.ibm.com/developerworks/apps/SendTo?bookstore=safarihttp://www.ibm.com/developerworks/architecturehttp://www.ws-i.org/http://www.w3.org/http://www.ibm.com/developerworks/opensource/top-projects/eclipse-starthere.html?ca=dgr-eclipse-1 -
8/13/2019 java Web Services IBM
20/21
developerWorks ibm.com/developerWorks/
Create stand-alone Web services applications with Eclipse andJava SE 6: Part 2: The Web service client application Page 20 of 21
About the authors
John Robertson
John Robertson is a Staff Software Engineer and works for the Australia Development
Laboratory as part of IBM Tivoli Security Development.
Fiona Lam
Fiona Lam is a Software Engineer and works for the Australia DevelopmentLaboratory 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.
-
8/13/2019 java Web Services IBM
21/21
ibm.com/developerWorks/ developerWorks
Copyright IBM Corporation 2009
(www.ibm.com/legal/copytrade.shtml)
Trademarks
(www.ibm.com/developerworks/ibm/trademarks/)
http://www.ibm.com/developerworks/ibm/trademarks/http://www.ibm.com/legal/copytrade.shtml