Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

ECLIPSE WEB TOOLS PLATFORM developing java web applications PHẦN 7 potx
Nội dung xem thử
Mô tả chi tiết
technologies such as CORBA, Java RMI, and DCOM failed to gain significant
traction on the Internet. When XML emerged, Microsoft proposed that it could
be used as an architecturally neutral way to serialize graphs of objects. SOAP
was proposed as the carrier for these serialized object graphs and the serialization algorithm was dubbed SOAP encoding. The fact that XML was used as the
serialization syntax was incidental. To use SOAP encoding, you had to have
matching client and service implementations that understood the SOAP encoding algorithm. The client and the server were assumed to both be implemented in
conventional object-oriented programming languages. The flaw in this approach
is that exchanging objects is really not what the Web is all about. The Web is
highly heterogeneous, and there are many types of clients and ways of processing
XML. 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 behind
XML is that it should be easily processable by a variety of applications. SOAP
encoding 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 real
world 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 my
driver’s license. I do not remotely invoke the driver’s license procedure or send
the motor vehicle department a serialized driver’s license application form
object graph. Documents are very natural, and XML is an excellent way to represent them in information systems. XML Schema is the W3C standard type
system for XML documents. But XML is really just a representation of a document, albeit a very convenient one for many purposes. In general, there may be
other useful representations of documents. For example, if I just want to display
the 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 document, then perhaps JavaScript Object Notation (JSON) is a good representation. On the other hand, if I want to use the document in a Service-Oriented
Architecture (SOA) application, then document/literal SOAP is probably the
best representation.
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 applications, 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.
424 CHAPTER 10 • Web Services
The 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 hyperlinks
are then used for subsequent requests, which cause the agent to transition to a
new 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 physically
stored in a relational database and is identified by a unique number that acts as
its 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 related
information. In the context of Web services, this means that the messages exchanged
will often contain references to other Web services. A full description of a Web service must also describe the interfaces of these references to other Web services. For
example, it is not enough to know that the League Planet schedule Web service
returns URIs to teams; it is also necessary to know that these URIs are in fact the
endpoints 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, and
DELETE, which roughly correspond to the Create, Retrieve, Update, and Delete
(CRUD) operations on databases. In practice, most Web applications just use
GET 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, getting
your account balance is idempotent, but withdrawing money from it is not. An
obligation could be something like having your account charged for the operation.
Safe operations admit certain optimizations such as prefetching and caching. For
example, a Web browser could prefetch linked pages and cache the results to
improve response time and reduce network traffic.
REST 425
Finally, let’s examine content negotiation. This is the mechanism by which
an agent can specify the types of resource representation it prefers to receive in
response to a request. For example, suppose a Web browser requests an HTML
page. Part of the request is an HTTP Accept header that lists the image media
types that the Web browser can render, with weightings that indicate its preferences. When the Web application receives the request, it inspects the Accept
header and generates a Web page with links to the image media type that best fit
the Web browser’s preference. A similar mechanism can be used to specify the
desired natural language of the response.
Content negotiation applies also to Web services. For example, an AJAX
client 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. The
client includes an Accept header in its requests indicating that it accepts these
three media types and then assigns them suitable preferences. In this way, the
AJAX client receives the response in the format that is most efficient for it to
process if the Web service provides it, but can still function if the Web service provides other acceptable formats. The nice thing about this architecture is that the
Web service can be upgraded at a later date to improve performance and the
clients will automatically benefit without any modification on their end. For
example, suppose League Planet provides REST style Web services initially using
plain XML, but then finds after reviewing the server logs that many clients prefer
JSON. The service can then be upgraded to also provide JSON, and the existing
clients 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 SOAP
and REST interfaces. The use of REST for Web services received a mindshare
boost 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 Web
service usage was via the REST interface. This overwhelming preference for REST
versus SOAP is undoubtedly due to the fact that the main use of the Amazon
Web service is for providing product links on Web pages. Nevertheless, REST
style interfaces are easier to use in this type of application and deserve to be
given serious consideration when designing Web services in general.
Now let’s briefly examine how well SOAP 1.1 and WSDL 1.1 align with
REST principles. For starters, most SOAP 1.1 engines employ a single URL that
acts like a router for service requests. The SOAP engine examines the request to
426 CHAPTER 10 • Web Services
determine the operation and then invokes the service implementation associated
with it. Furthermore, SOAP 1.1 over HTTP always uses POST, so all operations
are treated as unsafe. WSDL 1.1 is not much better. In addition to the SOAP 1.1
binding, WSDL 1.1 defines two HTTP bindings, one for GET and another for
POST. This means you cannot describe a service that has a combination of safe
and unsafe operations. Nor can you always use the correct HTTP method for
any 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 WS-*. These include WSSecurity, WS-Reliability, and WS-Addressing to name a few. The way to think
about WS-* is that it defines a way to flow Web services messages over multiple transport hops involving a combination of protocols. For example, an
enterprise Web service might receive a request over HTTP and then place it on
a message queue. This is the domain of SOA.
Although SOA is undoubtedly useful in many contexts, it is overkill in others. For example, suppose you want to build an AJAX client. You need to get
XML 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 too
complex here. Perhaps JSON is a better representation. Still, this is programmatic access, and even though you are not using SOAP or even XML, you’d like
a well-defined interface you can program 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 description of safe operations, has a much improved HTTP binding, and includes
support for describing messages that refer to other Web services; that is, hyperlinking between Web services can be described. As we enter the so-called Web
2.0 technology era, we could see a unification of WS-* and REST style Web services
based 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 Planet
schedule information using the Top-Down approach. This means you
Overview of Iterations 427
create the description of the Web service interface first using the XSD and
WSDL editors, and then generate its Java skeleton using the Web service
wizard. You fill in the implementation of the Web service by writing Java
code that accesses the League Planet business logic tier. Finally, you test the
Web service using the Web Services Explorer.
❍ In Iteration 2 you develop a Web service that updates the game scores
using the Bottom-Up approach. This means you write Java code that
accesses the League Planet business logic tier first, and then use the Web
service wizard to deploy the Java code as a Web service and generate its
WSDL.
❍ 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 the
WSDL 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 the
TCP/IP monitor and the WS-I test tools to test your Web service for compatibility with the WS-I profiles.
❍ In Iteration 5 you use your Web services in a Web application that displays
schedules and updates game scores. The Web application accesses the Web
services 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 to
publish 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 interoperability because the underlying implementation details cannot “bleed through” into
the interface. Top-Down development is required if the messages must use existing industry or corporate standard XML document formats. To perform TopDown development you need to have XSD and WSDL design skills. Luckily,
WTP has two great editors that make this task easier.
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 and
deploy it to the Axis SOAP engine running on Tomcat.
428 CHAPTER 10 • Web Services
4. Fill in the implementation of the Java skeleton by accessing the League
Planet 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 description language for use with Web services. XSD is far more expressive than its
predecessor, DTD, and, like many specifications produced by industrial collaborations, is extremely feature rich. Fortunately, only a small portion of the
XSD 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 concepts 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 type
system, but are very difficult to read. They are intended for people who need to
build software that processes XSD. However, you might need to refer to these
specifications in order to understand error messages produced by XSD processors. Be warned, though, this task is not for the faint-hearted.
WTP has a powerful XSD editor that includes both a source and a graphical
view as well as an outline view and property sheets that greatly simplify the editing task. However, don’t let the power of the XSD editor tempt you into using all
the features of XSD when you design your Web service messages. You should
keep the design simple to ensure that developers can understand it and that it
will be consumable by the widest possible set of Web service toolkits. The initial
toolkit support for the more exotic features of XSD was somewhat patchy, but
the 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 contain
the Web service (see Figure 10.1).
2. League Planet has an XML format for schedules. Import
IceHockeyService/schedule.xml
Iteration 1: Developing Web Services Top-Down 429
430 CHAPTER 10 • Web Services
Figure 10.1 New Dynamic Web Project—IceHockeyService
Example 10.1 Listing of schedule.xml
<?xml version="1.0" encoding="UTF-8"?>
<schedule scheduleId="1"
xmlns="http://leagueplanet.com/resource/schedule"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://leagueplanet.com/resource/schedule schedule.xsd">
<name>2005-2006 Regular Season</name>
<league leagueId="1">
<name>Rosehill Girls Hockey League</name>
</league>
<games>
<game gameId="1">
<dateTime>2006-01-07T19:00:00-05:00</dateTime>
<arena locationId="1">
<name>Hillview High School</name>
<timeZone>Canada/Eastern</timeZone>
</arena>
<visitor teamId="1">
<name>Ladybugs</name>
</visitor>
for an example instance document (see Example 10.1). Your goal is to
describe this format using XSD.