Create stand-alone Web services applications with … stand-alone Web services applications with...

27
Create stand-alone Web services applications with Eclipse and Java SE 6, Part 1: The Web service server application Skill Level: Intermediate Fiona Lam ([email protected]) Software Engineer IBM John Robertson ([email protected]) Staff Software Engineer IBM 13 Nov 2008 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 first in a series, start by getting familiar with the Eclipse IDE. Configure the environment; create projects, packages, and classes; then run the application from the command line. Section 1. 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'll leverage the Eclipse IDE, Java SE 6, and Apache Ant to easily create fully functioning Web services server and client applications. You'll 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. The Web service server application © Copyright IBM Corporation 2008. All rights reserved. Page 1 of 27

Transcript of Create stand-alone Web services applications with … stand-alone Web services applications with...

Create stand-alone Web services applications withEclipse and Java SE 6, Part 1: The Web serviceserver applicationSkill Level: Intermediate

Fiona Lam ([email protected])Software EngineerIBM

John Robertson ([email protected])Staff Software EngineerIBM

13 Nov 2008

Use the Eclipse Integrated Development Environment (IDE) and Java™ Platform,Standard Edition (Java SE) 6 to create a stand-alone Web services application thatcan be run from the console. In this tutorial, the first in a series, start by gettingfamiliar with the Eclipse IDE. Configure the environment; create projects, packages,and classes; then run the application from the command line.

Section 1. Before you start

About this series

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

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 1 of 27

About this tutorial

This tutorial, Part 1 of the series, introduces you to publishing a Web serviceapplication using the Eclipse IDE, Java SE 6, and Ant. It lays the groundwork forPart 2, which describes the creation of the Web services client application.

Objectives

After completing this tutorial you should know:

• What a Web service is and the standards it uses in relation to a browserbeing used from within Eclipse to view the published Web ServicesDescription Language (WSDL) file.

• How to create the server side of a Web service, including how to installand configure the Eclipse IDE and the Java Development Kit (JDK) sothat they perform together to generate the code that's compiled usingJava SE 6.

• How to use the Ant Java-based build tool within the Eclipse IDE to run aspecial Java command to generate some of the code.

Prerequisites

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

System requirements

To follow the examples, you need to download:

• Eclipse IDE for Java Developers

• Java SE 6

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

developerWorks® ibm.com/developerWorks

The Web service server applicationPage 2 of 27 © Copyright IBM Corporation 2008. All rights reserved.

Section 2. Set up your development environment

Install Java SE 6

1. Download and install the latest Java SE 6 JDK. Java SE 6 has many newfeatures, including Web services APIs.

2. Double-click the executable file and follow the installation instructions. Werecommend you perform the typical installation and maintain all defaultsettings, such as location.

3. When asked, select whether you want to install the Java runtimeenvironment as the system JVM and whether you want any browsers tobe associated with the Java plug-in.

4. Click Finish to install.

5. Close any browser windows that are open.

6. When complete, you should be presented with a thank-you messageconfirming successful installation. Click OK to close.

Note: Installing the Java Runtime Environment (JRE) as the system Java VirtualMachine (JVM) means that it replaces any JVM found in the Microsoft® Windows®directory or places a new copy in there if one is not found. Associating any browserswith the Java plug-in means that this new version of Java will be used for applets.

Install Eclipse

Eclipse is an open source, extensible development platform, which can be installedon almost all operating systems. (Learn more about Eclipse.)

Installing Eclipse is fairly straightforward because there's no installation process:

• Download the Eclipse IDE for Java EE Developers.

• Extract the file to the desired location on your computer. You should thensee a folder named eclipse. It's a good idea to create a shortcut to theeclipse.exe file on your desktop for convenience.

ibm.com/developerWorks developerWorks®

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 3 of 27

Configure Eclipse

When you first run Eclipse, the Welcome page is displayed, as shown in Figure 1. Ifyou don't want to read the Overview and other offerings, simply close that page andcome back to it later by selecting Help > Welcome.

Figure 1. Welcome screen

Configure Eclipse to use the Java SE 6 JDK you installed earlier; you want toassociate your project with this version of Java:

1. Select Window > Preferences > Java > Installed JREs, and click theAdd button.

2. Enter a name, such as Java SE 6, to easily identify what version it is.

3. Click the Browse button and locate the directory where JRE 60 wasinstalled.

4. Click OK (see Figure 2).Figure 2. Adding a new JRE

developerWorks® ibm.com/developerWorks

The Web service server applicationPage 4 of 27 © Copyright IBM Corporation 2008. All rights reserved.

The new JRE should now appear in the list of installed JREs, as shown inFigure 3.

5. Select the Java SE 6 check box, then click OK.Figure 3. Selecting the new JRE

ibm.com/developerWorks developerWorks®

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 5 of 27

6. To set compliance to the installed version of Java, select Window >Preferences > Java > Compiler.

7. Select 1.6 from the Compiler compliance level drop-down list, as shown inFigure 4.Figure 4. Setting compliance

developerWorks® ibm.com/developerWorks

The Web service server applicationPage 6 of 27 © Copyright IBM Corporation 2008. All rights reserved.

Create a project

Next you create a project to construct your Web services server. A project containsthe source code and other related files, and it lets you use the project as the sourcecontainer or to set up folders inside the project to organize files.

1. Select File > New > Project.

2. Expand the Java folder and click Java Project (see Figure 5).Figure 5. Creating a project in Eclipse

ibm.com/developerWorks developerWorks®

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 7 of 27

3. Click Next.

4. Enter a project name, such as wsServerExample, when prompted, asshown in Figure 6.Figure 6. Entering project details in Eclipse

developerWorks® ibm.com/developerWorks

The Web service server applicationPage 8 of 27 © Copyright IBM Corporation 2008. All rights reserved.

5. Select the Use default JRE radio button if it was previously selected bydefault; otherwise select the Use a project specific JRE radio button,ensuring that it's Java SE 6.

ibm.com/developerWorks developerWorks®

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 9 of 27

6. Click Finish to associate your project with the Java JDK you installedearlier.

7. If you're prompted to switch Java perspective, click Yes.

Section 3. Create the server

First you need to create a Java package to house your Java classes:

1. Select File > New > Package.

2. When the New Java Package window opens, enter a name for thepackage, such as com.myfirst.wsServer, as shown in Figure 7.Figure 7. Creating a package

developerWorks® ibm.com/developerWorks

The Web service server applicationPage 10 of 27 © Copyright IBM Corporation 2008. All rights reserved.

Next you need to create a class for the server code:

3. Right-click the package name you just created, then select New > Class.Configure it as shown in Figure 8.Figure 8. Creating a class

ibm.com/developerWorks developerWorks®

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 11 of 27

4. Create your class as public with no main method stub.

Now that you've provided your package with a class, you can write the code for theserver, as shown in Listing 1.

Listing 1. Server code

package com.myfirst.wsServer;

import javax.jws.WebService;

developerWorks® ibm.com/developerWorks

The Web service server applicationPage 12 of 27 © Copyright IBM Corporation 2008. All rights reserved.

@WebService

public class SayHello {

private static final String SALUTATION ="Hello";

public String getGreeting( String name ) {return SALUTATION + " " + name;

}}

Note the text in bold in Listing 1. This is called an annotation, or metadata, which isused by the Web Services Metadata Specification introduced in Java SE 5.Developers define their classes and methods before applying annotations to them toindicate to the runtime engine how to enable the class and its methods as a Webservice and Web service operations. Java SE 6 comes bundled with such an engine.

The @WebService annotation marks the SayHello class as implementing a Webservice, which results in a deployable Web service being produced. This particularannotation is a WSDL mapping annotation and associates the Java source code tothe WSDL elements that represent the Web service. (See Resources for moreinformation about other annotations in Java SE 6.)

Section 4. Generate the server code with Ant

After you've written the server application, you need to generate the Webservice-supporting code. First, create a new Ant file called build.xml:

1. Right-click the project and select New > File.

2. Enter the name build.xml when prompted, then click Finish (seeFigure 9).

3. Make sure this file opens with the Ant Editor by right-clicking it andselecting Open With > Ant Editor. From now on, whenever youdouble-click this file, it opens with the Ant Editor.Figure 9. Creating an Ant file

ibm.com/developerWorks developerWorks®

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 13 of 27

4. Enter the Ant project shown in Listing 2.Listing 2. Ant script

<project default="wsgen">

<target name="wsgen" >

<exec executable="wsgen">

<arg line="-cp ./bin -keep -s ./src -d ./bincom.myfirst.wsServer.SayHello"/>

</exec>

</target>

developerWorks® ibm.com/developerWorks

The Web service server applicationPage 14 of 27 © Copyright IBM Corporation 2008. All rights reserved.

</project>

5. To run the Ant build.xml file, right-click Run As and select Ant Build,which executes the Ant file.

6. Make sure that this results in a BUILD SUCCESSFUL message in theEclipse Console window, as shown in Figure 10.Figure 10. Ant build success

7. Return to the Eclipse project and refresh the project by right-clickingwsServerExample and selecting Refresh. You should now see thegenerated code to run the Web service created under the new packagecalled com.myfirst.wsServer.jaxws (see Figure 11).Figure 11. Generated code

ibm.com/developerWorks developerWorks®

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 15 of 27

Section 5. Publish the Web service

After you've generated the code for the Web service's server, you need to publish itso you can start using it:

1. Create a new class under the com.myfirst.wsServer package you created,and call it something like RunService.

2. Right-click the package and select New > Class, but this time select theoption to create the main method stub.

3. Write the code to publish your Web service, as shown in Listing 3.Listing 3. Publishing code

package com.myfirst.wsServer;

import Javax.xml.ws.Endpoint;

public class RunService {

/*** @param args*/

public static void main(String[] args) {

System.out.println("SayHello Web Service started.");Endpoint.publish("http://localhost:8080/wsServerExample",new SayHello());

}}

Java SE 6 provides new support for publishing Web services. TheEndpoint API simply publishes the Web service endpoint, whichgenerates the WSDL at run time at a URL.

4. Run this class by right-clicking it and selecting Run As > JavaApplication. The Eclipse IDE Console window should display. If itdoesn't, select Window > Show View > Console. You should see anindication that the Web server has started, as shown in Figure 12.Figure 12. Console with the service running

developerWorks® ibm.com/developerWorks

The Web service server applicationPage 16 of 27 © Copyright IBM Corporation 2008. All rights reserved.

Section 6. View the WSDL

Now that the server is up and running, you should test it to make sure it's working asexpected:

1. Open the internal Web browser in Eclipse by selecting Window > ShowView > Other > General > Internal Web Browser.

2. type the URL, such ashttp://localhost:8080/wsServerExample?wsdl, which shoulddisplay the Web service's WSDL text, as shown in Figure 13.Figure 13. Console with the internal Web browser

3. When you're finished, you can stop the Web service by clicking the redsquare in the Eclipse Console view. However, to continue the tutorial theWeb service needs to remain running.

ibm.com/developerWorks developerWorks®

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 17 of 27

Section 7. Test the server

Next you use the Eclipse Web Services Explorer tool to invoke the operations of aWeb service via native WSDL and SOAP to test the getGreeting method of theWeb service you just created.

1. You may need to change to the Java EE perspective. Click Window >Open Perspective > Other.

2. When the window appears, select Java EE.

3. Select Run > Launch the Web Services Explorer. Maximize the view bydouble-clicking its tab. You should see the screen shown in Figure 14.Figure 14. The Web Services Explorer

4. Click the icon indicated by the red circle. This displays the WSDL page,as shown in Figure 15.Figure 15. WSDL page

developerWorks® ibm.com/developerWorks

The Web service server applicationPage 18 of 27 © Copyright IBM Corporation 2008. All rights reserved.

5. In the Navigator pane, click WSDL Main. The Actions pane is updated, asshown in Figure 16.

6. Enter the WSDL URL, in this casehttp://localhost:8080/wsServerExample?wsdl, then click theGo button.Figure 16. Entering WSDL URL

ibm.com/developerWorks developerWorks®

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 19 of 27

7. The WSDL should successfully open, and you should see a screensimilar to Figure 17.Figure 17. Successfully opened WSDL

developerWorks® ibm.com/developerWorks

The Web service server applicationPage 20 of 27 © Copyright IBM Corporation 2008. All rights reserved.

8. Next you invoke an operation by clicking getGreeting under Operations(shown in Figure 17). This results in a screen similar to Figure 18.Figure 18. Invoking an operation

ibm.com/developerWorks developerWorks®

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 21 of 27

9. Under getGreeting in the Body section, click the Add link (as shown inFigure 18) to add a new row to the values table.

10. Enter a name (here, Fiona), and click the Go button.

11. In the Status section, getGreetingResponse displays the result. Youshould see a You should see a result like return (string): HelloFiona (see Figure 19) in the Status section. You might need to scroll ordrag the views to see the result.Figure 19. Result of the operation

developerWorks® ibm.com/developerWorks

The Web service server applicationPage 22 of 27 © Copyright IBM Corporation 2008. All rights reserved.

Section 8. Summary

Creating, generating, and publishing a Web service server is as simple as usingEclipse and, of course, Java SE 6. Stay tuned for Part 2 of this tutorial series whereyou'll build the stand-alone client to use with this stand-alone Web service server.

ibm.com/developerWorks developerWorks®

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 23 of 27

Section 9. Appendix: A brief overview of Web servicesterms and acronyms

Web service

According to W3C, a Web service is the "software system designed to supportinteroperable Machine to Machine interaction over a network." In other words, Webservices are programmatic interfaces used for application-to-applicationcommunication. Typically, they are used as Web applications that enable thecommunication between computers over a network, such as the Internet.

Clients and servers communicate using XML messages that follow the SOAPstandard. That is, Web services use XML to code and decode data and SOAP totransport it using open protocols. Two of the basic elements of Web servicesplatforms are SOAP and WSDL.

XML

Extensible Markup Language (XML) lets users define their own elements. It's ageneral purpose specification facilitating the sharing of structured data acrossdifferent information systems, typically across a network. XML is designed to carryinformation and not to display it. In other words, XML does not actually do anythingother than to structure, store, and transport information; it's just plain text.

SOAP

SOAP used to stand for Simple Object Access Protocol, but this was dropped inversion 1.2 because it was believed to be too misleading. It's a lightweightcommunication protocol that lets applications exchange information over networksusing XML, or more simply, for accessing a Web service. SOAP allows applicationsto communicate with each other regardless of which operating system they'rerunning on and what programming language they were written in.

WSDL

A WSDL is an application-readable Web Services Description Language. It's used todescribe the Web service's features and how it should be called by the client

developerWorks® ibm.com/developerWorks

The Web service server applicationPage 24 of 27 © Copyright IBM Corporation 2008. All rights reserved.

application. That is, it describes all the methods and its signatures, the namespaces,plus the handling Uniform Resource Identifier (URI) for the Web service in an XMLdocument. The URI names a resource on a network.

ibm.com/developerWorks developerWorks®

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 25 of 27

Resources

Learn

• Start here for more Eclipse IDE project resources.

• Visit the W3C site.

• In the Architecture area on developerWorks, get the resources you need toadvance your skills in the architecture arena.

• Discover the new Java SE 6 features.

• The SOA and Web services zone on IBM developerWorks hosts hundreds ofinformative articles and introductory, intermediate, and advanced tutorials onhow to develop Web services applications.

• Play in the IBM SOA Sandbox! Increase your SOA skills through practical,hands-on experience with the IBM SOA entry points.

• The IBM SOA Web site offers an overview of SOA and how IBM can help youget there.

• Stay current with developerWorks technical events and webcasts.

• Browse for books on these and other technical topics at the Safari bookstore.

• Check out a quick Web services on demand demo.

Get products and technologies

• Download the Eclipse IDE for Java EE developers.

• Download Java SE 6.

• Download IBM product evaluation versions and get your hands on applicationdevelopment tools and middleware products from DB2®, Lotus®, Rational®,Tivoli®, and WebSphere®.

Discuss

• Participate in the discussion forum for this content.

• Get involved in the developerWorks community by participating indeveloperWorks blogs.

About the authors

Fiona LamFiona Lam is a software engineer and works for the Australian Development

developerWorks® ibm.com/developerWorks

The Web service server applicationPage 26 of 27 © Copyright IBM Corporation 2008. All rights reserved.

Laboratory as part of IBM Tivoli Security Development.

John RobertsonJohn Robertson is a staff software engineer and also works for the AustralianDevelopment Laboratory as part of IBM Tivoli Security Development.

Trademarks

IBM, the IBM logo, ibm.com, DB2, developerWorks, Lotus, Rational, Tivoli, andWebSphere are trademarks or registered trademarks of International BusinessMachines Corporation in the United States, other countries, or both. These and otherIBM trademarked terms are marked on their first occurrence in this information withthe appropriate symbol (® or ™), indicating US registered or common lawtrademarks owned by IBM at the time this information was published. Suchtrademarks may also be registered or common law trademarks in other countries.See the current list of IBM trademarks.Adobe, the Adobe logo, PostScript, and the PostScript logo are either registeredtrademarks or trademarks of Adobe Systems Incorporated in the United States,and/or other countries.Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in theUnited States, other countries, or both.Microsoft and Windows are trademarks of Microsoft Corporation in the United States,other countries, or both.

ibm.com/developerWorks developerWorks®

The Web service server application© Copyright IBM Corporation 2008. All rights reserved. Page 27 of 27