In this chapter you’ll add Web services to the League Planet site in the following iterations: ❍ In Iteration 1 you develop a Web service that retrieves League Planetschedule information
Trang 1technologies such as CORBA, Java RMI, and DCOM failed to gain significanttraction on the Internet When XML emerged, Microsoft proposed that it could
be used as an architecturally neutral way to serialize graphs of objects SOAPwas proposed as the carrier for these serialized object graphs and the serializa-
tion algorithm was dubbed SOAP encoding The fact that XML was used as the
serialization syntax was incidental To use SOAP encoding, you had to havematching client and service implementations that understood the SOAP encod-ing algorithm The client and the server were assumed to both be implemented inconventional object-oriented programming languages The flaw in this approach
is that exchanging objects is really not what the Web is all about The Web ishighly heterogeneous, and there are many types of clients and ways of processingXML For example, XML can be processed using DOM, SAX, StAX, XPath,XSLT, and XQuery to name a few In fact, one of the design principles behindXML is that it should be easily processable by a variety of applications SOAPencoding clearly violates that principle
A better approach to the design of Web service interfaces is to view Web service operations as document exchanges After all, business in the realworld is transacted by the exchange of documents For example, I fill out a driver’s license application form and the motor vehicle department sends me mydriver’s license I do not remotely invoke the driver’s license procedure or sendthe motor vehicle department a serialized driver’s license application formobject graph Documents are very natural, and XML is an excellent way to rep-resent them in information systems XML Schema is the W3C standard typesystem for XML documents But XML is really just a representation of a docu-ment, albeit a very convenient one for many purposes In general, there may beother useful representations of documents For example, if I just want to displaythe document to a human, then HTML or PDF is a better representation Or if
I want a highly interactive AJAX-based Web user interface to display the ment, then perhaps JavaScript Object Notation (JSON) is a good representa-tion On the other hand, if I want to use the document in a Service-OrientedArchitecture (SOA) application, then document/literal SOAP is probably thebest representation
docu-REST
Web architecture teaches us that the way to design an application is to identify
its important concepts, model them as resources, and assign them Uniform Resource Identifiers (URI) Software agents, such as Web browsers or Web appli-
cations, then request these resources, specifying their preferred representation
formats The Web server or service responds by transferring the representation
of the resource to the agent in the format that most closely satisfies the request
Trang 2The selection of the best representation is referred to as content negotiation The agent then transitions to its next state based on the content of the received
resource, which typically contains hyperlinks to other resources The hyperlinksare then used for subsequent requests, which cause the agent to transition to anew state This architectural style is referred to as Representational State Transfer
(REST), a term coined in Chapter 5 of the Ph.D dissertation Architectural Styles
and the Design of Network-based Software Architectures [Fielding2000], by Roy
Fielding
For example, consider League Planet Its important concepts include leagues,schedules, games, teams, and locations Each of these concepts is physicallystored in a relational database and is identified by a unique number that acts asits primary key This gives us a simple way to define URIs Each row of the main
entity tables corresponds to a URI We create the URI by combining the table
name and the primary key value; for example,
http://www.leagueplanet.com/resources/game/42
identifies game number 42
There are a few other key ideas in Web architecture One of the most important
is the notion of hyperlinking The representation of a resource will often contain
links to other resources An agent will typically follow these links to retrieve relatedinformation In the context of Web services, this means that the messages exchangedwill often contain references to other Web services A full description of a Web serv-ice must also describe the interfaces of these references to other Web services Forexample, it is not enough to know that the League Planet schedule Web servicereturns URIs to teams; it is also necessary to know that these URIs are in fact theendpoints of League Planet team Web services
Another key idea in REST is the notion of uniform interface, which means that there is a standard set of verbs or methods that can be used to access any
resource In HTTP, the most common methods are PUT, GET, POST, andDELETE, which roughly correspond to the Create, Retrieve, Update, and Delete(CRUD) operations on databases In practice, most Web applications just useGET and POST
The proper use of GET has important performance benefits GET should be
used for operations that are safe, which means that they are idempotent and don’t incur any obligations Idempotence means that the result of performing the
operation twice is the same as performing it once For example, in banking, gettingyour account balance is idempotent, but withdrawing money from it is not Anobligation could be something like having your account charged for the operation.Safe operations admit certain optimizations such as prefetching and caching Forexample, a Web browser could prefetch linked pages and cache the results toimprove response time and reduce network traffic
Trang 3Finally, let’s examine content negotiation This is the mechanism by which
an agent can specify the types of resource representation it prefers to receive inresponse to a request For example, suppose a Web browser requests an HTMLpage Part of the request is an HTTP Accept header that lists the image mediatypes that the Web browser can render, with weightings that indicate its prefer-ences When the Web application receives the request, it inspects the Acceptheader and generates a Web page with links to the image media type that best fitthe Web browser’s preference A similar mechanism can be used to specify thedesired natural language of the response
Content negotiation applies also to Web services For example, an AJAXclient may prefer a response encoded as JSON as its first choice, then plain XML,and then finally SOAP, since this is the order that minimizes its parsing time Theclient includes an Accept header in its requests indicating that it accepts thesethree media types and then assigns them suitable preferences In this way, theAJAX client receives the response in the format that is most efficient for it toprocess if the Web service provides it, but can still function if the Web service pro-vides other acceptable formats The nice thing about this architecture is that theWeb service can be upgraded at a later date to improve performance and theclients will automatically benefit without any modification on their end Forexample, suppose League Planet provides REST style Web services initially usingplain XML, but then finds after reviewing the server logs that many clients preferJSON The service can then be upgraded to also provide JSON, and the existingclients will experience a performance boost without changing a line of their code
REST Style Web Services
The REST architectural style is directly applicable to Web services See Building
Web Services the REST Way [Costello2002] by Roger Costello for an excellent
description of this approach Some vendors, such as Amazon, offer both SOAPand REST interfaces The use of REST for Web services received a mindshareboost when, in the brief article “REST vs SOAP at Amazon” [O’Reilly2003],Tim O’Reilly reported that Amazon was finding that 85 percent of their Webservice usage was via the REST interface This overwhelming preference for RESTversus SOAP is undoubtedly due to the fact that the main use of the AmazonWeb service is for providing product links on Web pages Nevertheless, RESTstyle interfaces are easier to use in this type of application and deserve to begiven serious consideration when designing Web services in general
Now let’s briefly examine how well SOAP 1.1 and WSDL 1.1 align withREST principles For starters, most SOAP 1.1 engines employ a single URL thatacts like a router for service requests The SOAP engine examines the request to
Trang 4determine the operation and then invokes the service implementation associatedwith it Furthermore, SOAP 1.1 over HTTP always uses POST, so all operationsare treated as unsafe WSDL 1.1 is not much better In addition to the SOAP 1.1binding, WSDL 1.1 defines two HTTP bindings, one for GET and another forPOST This means you cannot describe a service that has a combination of safeand unsafe operations Nor can you always use the correct HTTP method forany given operation since PUT, DELETE, and so forth are not supported Finally,WSDL 1.1 provides no way to describe messages that refer to other Web services,that is, no support for hyperlinking.
So we see that SOAP 1.1 and WSDL 1.1 are somewhat REST-hostile.Nevertheless, these specifications do provide the basis for a large and rich set
of additional specifications collectively referred to as * These include Security, WS-Reliability, and WS-Addressing to name a few The way to thinkabout WS-* is that it defines a way to flow Web services messages over multi-ple transport hops involving a combination of protocols For example, anenterprise Web service might receive a request over HTTP and then place it on
WS-a messWS-age queue This is the domWS-ain of SOA
Although SOA is undoubtedly useful in many contexts, it is overkill in ers For example, suppose you want to build an AJAX client You need to getXML data from somewhere Why not use a Web service? In this situation,you’d like the XML to be very easy to process, so SOAP encoding is ruled out.Document/literal style is much more appropriate But maybe XML is even toocomplex here Perhaps JSON is a better representation Still, this is program-matic access, and even though you are not using SOAP or even XML, you’d like
oth-a well-defined interfoth-ace you coth-an progroth-am to
Fortunately, the combination of SOAP 1.2 and WSDL 2.0 brings the world
of Web services into much better alignment with REST architectural principles.SOAP 1.2 supports the use of GET for requests WSDL 2.0 allows the descrip-tion of safe operations, has a much improved HTTP binding, and includessupport for describing messages that refer to other Web services; that is, hyper-linking between Web services can be described As we enter the so-called Web2.0 technology era, we could see a unification of WS-* and REST style Web servicesbased on SOAP 1.2 and WSDL 2.0
Overview of Iterations
Enough theory It’s time to write some code In this chapter you’ll add Web services
to the League Planet site in the following iterations:
❍ In Iteration 1 you develop a Web service that retrieves League Planetschedule information using the Top-Down approach This means you
Trang 5create the description of the Web service interface first using the XSD andWSDL editors, and then generate its Java skeleton using the Web servicewizard You fill in the implementation of the Web service by writing Javacode that accesses the League Planet business logic tier Finally, you test theWeb service using the Web Services Explorer.
❍ In Iteration 2 you develop a Web service that updates the game scoresusing the Bottom-Up approach This means you write Java code thataccesses the League Planet business logic tier first, and then use the Webservice wizard to deploy the Java code as a Web service and generate itsWSDL
❍ In Iteration 3 you create a Web client that uses the update Web service.You use the Web service wizard to generate a Java client proxy from theWSDL of the Web service and a JSP test client that uses the proxy
❍ In Iteration 4 you test your Web service for interoperability You use theTCP/IP monitor and the WS-I test tools to test your Web service for com-patibility with the WS-I profiles
❍ In Iteration 5 you use your Web services in a Web application that displaysschedules and updates game scores The Web application accesses the Webservices using Java client proxies
❍ In Iteration 6 you use the Web Services Explorer to discover Web services
in UDDI and WSIL registries You also use the Web service wizard topublish WSIL documents that describe your Web services
Iteration 1: Developing Web Services Top-Down
Top-Down development means designing the Web service interface first and then
developing the implementation code This approach yields the best ity because the underlying implementation details cannot “bleed through” intothe interface Top-Down development is required if the messages must use exist-ing industry or corporate standard XML document formats To perform Top-Down development you need to have XSD and WSDL design skills Luckily,WTP has two great editors that make this task easier
interoperabil-In this iteration, you’ll perform the following tasks:
1 Use the XSD editor to describe the League Planet schedule format
2 Use the WSDL editor to describe a Web service for querying schedules
3 Use the Web service wizard to generate a Java skeleton for the service anddeploy it to the Axis SOAP engine running on Tomcat
Trang 64 Fill in the implementation of the Java skeleton by accessing the LeaguePlanet business logic tier.
5 Use the Web Services Explorer to test the schedule query service
XSD
XML Schema Description (XSD) is the W3C Recommendation for describing
the format or schema of XML documents, and is the preferred schema
descrip-tion language for use with Web services XSD is far more expressive than itspredecessor, DTD, and, like many specifications produced by industrial collab-orations, is extremely feature rich Fortunately, only a small portion of theXSD language is needed in practice to describe typical Web service messages
For an easily digestible overview of XSD, see Chapters 8 and 9 of Essential
XML Quick Reference [Skonnard2002] by Aaron Skonnard and Martin
Gudgin
The definitive sources of information about XSD are, of course, the W3C
specifications themselves The best way to get started is to read XML Schema
Part 0: Primer [XSD10-Part0], which gradually introduces all the major
con-cepts and illustrates them using simple examples The remaining parts, XML
Schema Part 1: Structures [XSD10-Part1] and XML Schema Part 2: Datatypes
[XSD10-Part2], provide normative definitions of the schema constructs and typesystem, but are very difficult to read They are intended for people who need tobuild software that processes XSD However, you might need to refer to thesespecifications in order to understand error messages produced by XSD proces-sors Be warned, though, this task is not for the faint-hearted
WTP has a powerful XSD editor that includes both a source and a graphicalview as well as an outline view and property sheets that greatly simplify the edit-ing task However, don’t let the power of the XSD editor tempt you into using allthe features of XSD when you design your Web service messages You shouldkeep the design simple to ensure that developers can understand it and that itwill be consumable by the widest possible set of Web service toolkits The initialtoolkit support for the more exotic features of XSD was somewhat patchy, butthe situation has steadily improved over time
To create the schema for the League Planet schedule, do the following:
1 Create a new dynamic Web project named IceHockeyService to containthe Web service (see Figure 10.1)
2 League Planet has an XML format for schedules Import
IceHockeyService/schedule.xml
Trang 7430 CHAPTER 10 • Web Services
Figure 10.1 New Dynamic Web Project—IceHockeyService
Example 10.1 Listing of schedule.xml
Trang 83 Create a new XML Schema file named schedule.xsdinIceHockeyService (see Figure 10.2).
Trang 9432 CHAPTER 10 • Web Services
Figure 10.2 New XML Schema File—schedule.xsd
4 In general, there are many equivalent ways to describe a given formatusing XSD For Web services, it’s a good practice to describe formats in away that works well with XML data binding toolkits such as JAX-RPCand JAX-WS Define complex types for the content model of each element.The XSD editor lets you edit in the source tab, the graphical tab, the out-line view, and the property view Try to develop schedule.xsdyourself.Import
IceHockeyService/schedule.xsd
before proceeding (see Example 10.2)
Example 10.2 Listing of schedule.xsd
Trang 10<element name="name" type="string" />
<element name="league" type="tns:LeagueResourceType" />
<element name="games" type="tns:GamesType" />
<element name="name" type="string" />
<element name="timeZone" type="string" />
<element name="dateTime" type="dateTime" />
<element name="arena" type="tns:LocationResourceType" />
<element name="visitor" type="tns:TeamResourceType" />
<element name="home" type="tns:TeamResourceType" />
<element name="score" type="tns:ScoreType" />
Trang 11<complexType name="ScoreType">
<sequence>
<element name="visitor" type="int" />
<element name="home" type="int" />
</sequence>
</complexType>
</schema>
5 The XSD editor provides two types of graphical views The first is an
overview of the entire schema This view acts like a visual table of contents Itarranges the definitions in the schema into the main top-level categories such
as global element declarations and type definitions View schedule.xsdin theGraphtab of the XSD editor (see Figure 10.3)
Figure 10.3 Graphical View of schedule.xsd
6 The second type of graphical view is the detailed structure of an elementdeclaration or type definition View the ScheduleContentcomplex typedefinition in the Graph tab of the XSD editor (see Figure 10.4)
Trang 12Iteration 1: Developing Web Services Top-Down 435
Figure 10.4 Graphical View of ScheduleContent
7 The XSD editor is linked to an outline view You can edit the schema fromthis view View schedule.xsdin the Outline view of XSD editor (see Figure 10.5)
WSDL
Now that you’ve described the message format using XSD, your next goal is todescribe a Web service for retrieving it For simplicity, the Web service will have
a single operation named getSchedule.The operation will take the schedule id
as input and return the corresponding schedule document as output
1 Create a new WSDL file named query.wsdlinIceHockeyService
Trang 13Figure 10.6 New WSDL File—query.wsdl
Figure 10.5 Outline View of schedule.xsd
436
Trang 14Iteration 1: Developing Web Services Top-Down 437
Figure 10.7 New WSDL File Options
3 You can edit the document in the graph tab, the source tab, the outlineview, and the property view WSDL describes Web services using a hierarchy
of constructs: message, portType, binding, and service The editor has awizard that generates binding content for you Try to develop query.wsdlyourself Import
IceHockeyService/query.wsd
before proceeding (see Example 10.3)
Example 10.3 Listing of query.wsdl
Trang 15xmlns:tns="http://leagueplanet.com/message/query/"
xmlns:s="http://leagueplanet.com/resource/schedule">
<xsd:import namespace="http://leagueplanet.com/resource/schedule"
4 View query.wsdlin the Design tab of the WSDL editor (see Figure 10.8)
5 View query.wsdlin the Outline view of the WSDL editor (see Figure 10.9)
Trang 16Iteration 1: Developing Web Services Top-Down 439
Figure 10.8 WSDL Editor Graph Tab—query.wsdl
Figure 10.9 WSDL Editor Outline View—query.wsdl
Trang 17Deploying Web Services
WTP provides a Web service wizard to simplify the task of deploying Web services
In the Top-Down approach, the WSDL document is used to define a Java serverskeleton that implements the Web service The Java server skeleton is deployed
in a Web application The wizard also sets up the Web application, copies aSOAP engine into it, Apache Axis for example, and generates any requireddeployment descriptors All you need to do then is fill in the implementation ofthe Java server skeleton with the business logic of the Web service
1 You have now described the Web service Your next goal is to deploy it Thisstep assumes you have previously installed Tomcat and added it to WTP Selectquery.wsdland execute the command Web Services䉴 Generate Java beanskeleton This command launches the Web service wizard (see Figure 10.10).Pull the Web service slider up to the Start service position
Figure 10.10 Web Service Wizard—Top-Down Development
Trang 18Iteration 1: Developing Web Services Top-Down 441
2 Since you selected query.wsdlwhen you started the wizard, it appears
as the Service definition You can select a different WSDL file at this
point by clicking the Browse button, which opens the Select Service
Definitiondialog (see Figure 10.11) Click the OK button to keep
query.wsdlhere
Figure 10.11 Select Service Definition
3 The wizard selects Axis and Tomcat by default, which is what you’ll use here To change these, click the Server or Web service runtime links,which open the Service Deployment Configuration dialog (see Figure 10.12).Click the OK button to dismiss the dialog and keep the current
selections
4 The wizard assumes that you are deploying the service to the same project
as the WSDL file To change this, click the Service project link, whichopens the Specify Service Project Settings dialog (see Figure 10.13) Click the
OKbutton to keep IceHockeyService.
5 Click the Next button to proceed The wizard lets you select a sourcefolder and change the package name for the generated Java skeleton (see Figure 10.14)
Trang 19442 CHAPTER 10 • Web Services
Figure 10.13 Specify Service Project Settings
Figure 10.12 Service Deployment Configuration
6 Click the Next button to proceed The wizard is now ready to generate thecode and deploy the Web service The server must be started to completethis step (see Figure 10.15)
7 Click the Start server button, wait until the server starts, and then click Next.The Web service is now deployed Finally, the wizard lets you publish theWSDL to UDDI (see Figure 10.16) Just click Finish
Trang 20Figure 10.14 Web Service Skeleton Java Bean Configuration
Figure 10.15 Web Service Wizard—Server startup page
443
Trang 21444 CHAPTER 10 • Web Services
Figure 10.16 Web Service Publication
Steps the Web Service Wizard Performed
You probably noticed that there are a lot of steps involved in deploying a Webservice Fortunately, the Web service wizard handles all of these steps for you
In fact, if you are happy with the default behavior, you can simply click the Finishbutton on the first page of the wizard
You can also avoid using the wizard altogether and use an Ant task thatWTP provides instead The Ant task is handy when you find yourself repeatedlyusing the wizard to redeploy a modified WSDL file Consult the WTP Helpsystem for more information about the Web service Ant tasks
The Web service wizard:
1 installed the Axis SOAP engine in your dynamic Web project,
2 generated the Java bean skeleton for your service, and lots of Java XMLdata binding classes in the src folder,
3 copied query.wsdltoWebContent/wsdl/QuerySOAPPort.wsdland set itsendpoint address to your Web application (it also copied schedule.xsd),
Trang 224 created the Axis deployment descriptor WebContent/WEB-INF/
server-config.wsdd,
5 created a couple of handy Axis files to deploy and undeploy your
Web service in a subfolder of WebContent/WEB-INF, and
6 started Tomcat to make your Web service available
To verify that the Web service is actually deployed and running, do thefollowing:
1 Use the Project Explorer view to examine the IceHockeyServiceprojectafter the wizard completed (see Figure 10.17) Note that the Axis runtimeincludes a servlet named AxisServlet, which lists the deployed Web serv-ices Select the AxisServletservlet and execute the Run As 䉴Run on Servercommand
Figure 10.17 Project Explorer—IceHockeyService Project
Trang 232 Running AxisServletopens a Web browser with its URL View the list ofdeployed Web services (see Figure 10.18) Note that querySOAPappears inthe list.
Figure 10.18 Web Browser—AxisServlet
Implementing the Web Service
The Web service is running but it just returns null at this point Next, you need
to fill in the implementation of the Java bean skeleton The Web service needs toaccess the League Planet business logic tier
1 If you have not previously done so, create a new J2EE utility project namedLeaguePlanetModeland import the example source code from LeaguePlanetModel/srcinto it Now, make this project available to theWeb service as follows: Select the IceHockeyServiceproject and open itsPropertiesdialog Add LeaguePlanetModelas a J2EE Module Dependency (see Figure 10.19)
2 View the module structure of the server in the Servers view (see Figure 10.20).Note that LeaguePlanetModelis shown as a dependent module of
IceHockeyService
Trang 243 You now have a Web service skeleton and access to the League Planetbusiness logic tier Your next goal is to implement the Web service
The generated skeleton class is
com.leagueplanet.ws.query.QuerySOAPImpl
Import
IceHockeyService/src/com/leagueplanet/ws/query/QuerySOAPImpl.javanow (see Example 10.4)
Figure 10.19 J2EE Module Dependencies—IceHockeyService Project
Figure 10.20 Servers View—IceHockeyService Project
Trang 25Example 10.4 Listing of QuerySOAPImpl.java
/**
* QuerySOAPImpl.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.3 Oct 05, 2005 (05:23:37 EDT) WSDL2Java emitter.
public class QuerySOAPImpl implements QueryInterface {
public ScheduleContent getSchedule(GetScheduleRequest request)
throws RemoteException { return new Query().getSchedule(request);
busi-IceHockeyService/src/com/leagueplanet/Query.java
before proceeding (see Example 10.5)
Trang 26Example 10.5 Listing of Query.java
public class Query {
// use the ice hockey implementation for this service
private LeagueFacade facade = IceHockeyFacade.getLeagueFacade();
public ScheduleContent getSchedule(GetScheduleRequest request) {
long scheduleId = request.getScheduleId();
Schedule schedule = facade.findSchedule(scheduleId);
Trang 27private ScheduleType makeUnknownScheduleType(long scheduleId) {
ScheduleType scheduleType = new ScheduleType();
private ScheduleType makeScheduleType(Schedule schedule) {
ScheduleType scheduleType = new ScheduleType();
private GameType[] makeGamesType(Set events) {
Iterator eventIterator = events.iterator();
Vector games = new Vector();
while (eventIterator.hasNext()) {
Object event = eventIterator.next();
if (event instanceof Game) { Game game = (Game) event;
GameType gameType = makeGameType(game);
games.add(gameType);
} }
GameType[] gamesType = new GameType[games.size()];
games.copyInto(gamesType);
// sort the games by date
Arrays.sort(gamesType, new Comparator() {
public int compare(Object o1, Object o2) { long t1 = ((GameType) o1).getDateTime().getTimeInMillis();
long t2 = ((GameType) o2).getDateTime().getTimeInMillis();
if (t1 < t2) return -1;
if (t1 > t2) return 1;
return 0;
} });
return gamesType;
}
private GameType makeGameType(Game game) {
GameType gameType = new GameType();
Trang 28private ScoreType makeScoreType(Score score) {
return new ScoreType(score.getVisitor(), score.getHome());
}
private TeamResourceType makeResourceType(Team team) {
return new TeamResourceType(team.getName(), team.getId());
}
private LeagueResourceType makeResourceType(League league) {
return new LeagueResourceType(league.getName(), league.getId());
}
private LocationResourceType makeResourceType(Location location) {
return new LocationResourceType(location.getName(), location
.getTimeZoneId(), location.getId());
}
}
Testing with the Web Services Explorer
At this point the Web service is ready to test, and you will test it using the WebServices Explorer The Web Services Explorer lets you test Web services withoutwriting or generating any code The Web Services Explorer accomplishes this bydynamically interpreting the WSDL for the Web service You can test Web serv-ices that are deployed on your own machine or anywhere else on the Web.The Web Services Explorer is itself a Web application It runs in the embeddedservlet container that Eclipse uses for displaying Help The Web ServicesExplorer uses servlets and JSPs to generate its user interface, like any other JavaWeb application, but it is also integrated with Eclipse and can access the contents
View QuerySOAPPort.wsdlin the Web Services Explorer The Web ServicesExplorer user interface consists of three panes named Navigation, Action,
Trang 29and Status The Navigation pane displays an object tree, which grows asyou perform actions The Action pane displays information about thecurrently selected object and lets you perform actions on it The Statuspane displays messages from the last performed action.
Click the getSchedule link in the Action pane to explore the getScheduleoperation
Figure 10.21 Web Services Explorer—QuerySOAPPort.wsdl
2 View the getScheduleoperation (see Figure 10.22) To test the operation,enter1in the scheduleIdfield and click the Go button The schedule isreturned in the Status pane
3 Double-click the Status pane title bar to maximize it (see Figure 10.23) TheStatuspane displays the response from the Web service formatted as a formthat hides the XML detail The request and response can also be displayed
in raw source format Click the Source link to view the messages as rawXML SOAP envelopes
Trang 30Iteration 1: Developing Web Services Top-Down 453
Figure 10.22 Web Services Explorer—getSchedule Operation
Figure 10.23 Message Form View—getSchedule Response
Trang 314 View the SOAP message source (see Figure 10.24) Click the Form link toreturn to the form display.
Figure 10.24 Message Source View—getSchedule SOAP Envelopes
Summary of Iteration 1
In this iteration you developed a Web service to retrieve League Planet schedulesusing the Top-Down approach You designed an XML schema for the scheduleusing the XSD editor You then used this schema in a Web service interface thatyou designed using the WSDL editor You deployed the WSDL file to the ApacheAxis SOAP engine using the Web service wizard and verified that it was runningusing the AxisServlet servlet You then developed the implementation of theWeb service using the League Planet business tier Finally, you tested it, withoutcreating any code, using the Web Services Explorer You’re now ready to designanother Web service in iteration 2 using the Bottom-Up approach
Iteration 2: Developing Web Services Bottom-Up
The Bottom-Up approach to Web service development begins with creation of aJava service class The methods of the class define the operations of the Web service
Trang 32The argument lists and return types define the messages of the operations Afterthe service class is created, a tool is used to deploy it as a Web service and to generatethe WSDL document that describes it If changes are made to the interface of theclass, the deployment and WSDL generation steps must be repeated.
The Bottom-Up approach lets Java developers become immediately productive
at Web service development No new XSD and WSDL design skills are required.Bottom-Up development results in good Web service interfaces when the Java serviceclass uses simple data transfer objects as the inputs and outputs of its operations.However, if complex objects are used, then the resulting XSD may be hard tounderstand and less interoperable There is also the risk of “bleed-through” fromthe implementation into the service interface, which results in undesirable couplingbetween the client and service If the Web service interface changes whenever youchange the implementation of the Java service class, then you will continuallybreak your clients and largely defeat the benefits of Web services
The best way to create a clean, stable, interoperable Web service interface is
to design the XSD for the messages first, and use the Top-Down approach Thenext best way is to design a simple data transfer object layer for use in the Javaservice class interface, and use the Bottom-Up approach If you do use theBottom-Up approach, be disciplined about not changing the method signatures ofthe Java service class Confine your changes to the method implementations toavoid breaking your clients
In this iteration, you’ll do the following:
1 Develop a Java service class to get details about a game and to update itsscore
2 Use the Web service wizard to deploy the service
3 Use the WSDL editor to view the generated WSDL
Develop the Java Service Implementation
1 The Java service implementation is in the com.leagueplanetpackage.Create this package now in the IceHockeyServiceproject You will createJava classes in the following steps The complete source for these classes isavailable in the IceHockeyService/src/com/leagueplanetexamples folder
2 The UpdateWeb service has two operations: getGameDetail, which
retrieves the details of a game, and updateScore, which updates the score
of a game The getGameDetailoperation takes as input the identifier of agame and returns as output the game detail You therefore need to develop
a simple data transfer class to store the game detail Create the class
Trang 33GameDetailand try your hand at designing it Import GameDetail.javabefore proceeding (see Example 10.6).
Example 10.6 Listing of GameDetail.java
package com.leagueplanet;
import java.util.Calendar;
/**
* This class contains detail about games It is a simple JavaBean It is
* suitable for populating a data entry form.
*
* @author Arthur Ryman
*
*/
public class GameDetail {
private Calendar dateTime;
.
.
.
private int visitorScore;
public Calendar getDateTime() {
problem diagnosis The operations of the UpdateWeb service take thegame identifier and score as inputs
Both the getGameDetailandupdateScoreoperations take a game identifier asinput A game identifier is valid if it is the identifier of a game that exists in thedatabase Create the class GameExceptionnow and try to implement it ImportGameException.javabefore proceeding (see Example 10.7)
Trang 34Example 10.7 Listing of GameException.java
package com.leagueplanet;
public class GameException extends Exception {
private static final long serialVersionUID = 1L;
private long gameId;
public long getGameId() {
ScoreException.java before proceeding (see Example 10.8)
Example 10.8 Listing of ScoreException.java
package com.leagueplanet;
public class ScoreException extends Exception {
private static final long serialVersionUID = 1L;
private String team;
private int score;
public ScoreException(String message, String team, int score) {
Trang 35public void setScore(int score) {
Example 10.9 Listing of Update.java
public class Update {
// use the ice hockey implementation for this service
private LeagueFacade facade = IceHockeyFacade.getLeagueFacade();
public void updateScore(long gameId, int visitorScore, int homeScore)
Trang 36throws GameException, ScoreException { Game game = facade.findGame(gameId);
throw new GameException("Unknown game.", gameId);
GameDetail gameDetail = new GameDetail();
Trang 37Deploy the Service
Deploying a Java class as a Web service is the process of adding it to the SOAPengine’s configuration Some aspects of this process are standardized and othersare implementation dependent Fortunately, the Web service wizard makesdeploying Java classes easy You simply select the Java service class and run thewizard The wizard lets you control many aspects of how the service is deployed,tested, and published To deploy the Updateclass, do the following:
1 Select the Updateclass and execute the Web Services䉴 Create Web servicecommand The Web service wizard opens (see Figure 10.25) Note that theWeb service type is Bottom up Java bean Web Service since the Updateclasswas selected when you invoked the wizard
Ensure that the service slider is at the Start service position and that theclient slider is at the No client position You could click the Finish button atthis point since the wizard picks sensible defaults Instead, click the Nextbutton to step through the wizard pages
Figure 10.25 Web Service Wizard—Bottom Up Java Bean Web Service