The document discusses the Axis 2.0 framework for developing and deploying web services. It provides an overview of key web services concepts like WSDL, SOAP, and describes how Axis implements these standards. It also includes examples of SOAP requests and responses as well as using Axis to develop a simple math web service.
21. WSDL
WSDL Schema
Interface
<definitions>
• <definitions> are root node of WSDL
• <import> allows other entities for
inclusion
• <types> are data definitions - xsd
<import>
• <message> defines parameters of a
Web Service function
<types>
• <portType> defines input and output
operations
<message>
<portType>
<binding>
• <binding> specifies how each
message is sent over the wire
23. WSDL Elements
Open – allows for other namespaces and thus highly
extensible
Ability to import other schemas & WSDL
Provides “recipe” for Web Services
Provides both interface and implementation details
77. Building Web Services the REST Way
What is REST?
REST is a term coined by Roy Fielding in his Ph.D. dissertation [1] to describe
an architecture style of networked systems. REST is an acronym standing for
Representational State Transfer.
Here is Roy Fielding's explanation of the meaning of Representational State
Transfer:
"Representational State Transfer is intended to evoke an image of how a welldesigned Web application behaves: a network of web pages (a virtual statemachine), where the user progresses through an application by selecting links
(state transitions), resulting in the next page (representing the next state of the
application) being transferred to the user and rendered for their use."
78. Rest
REST uses the following standards:
HTTP
URL
XML/HTML/GIF/JPEG/etc (Resource Representations)
text/xml, text/html, image/gif, image/jpeg, etc (MIME Types)
79. Rest – A sample Illustration
Parts Depot Web Services
Parts Depot, Inc (fictitious company) has deployed some web services to
enable its customers to:
get a list of parts
get detailed information about a particular part
submit a Purchase Order (PO)
Let's consider how each of these services are implemented in a RESTful
fashion.
80. Rest
Get Parts List
The web service makes available a URL to a parts list resource. For example, a
client would use this URL to get the parts list:
http://www.parts-depot.com/parts
Note that "how" the web service generates the parts list is completely
transparent to the client.
All the client knows is that if he/she submits the above URL then a document
containing the list of parts is returned.
Since the implementation is transparent to clients, Parts Depot is free to modify
the underlying implementation of this resource without impacting clients.
This is loose coupling.
81. Rest
Here's the document that the client receives:
<?xml version="1.0"?>
<p:Parts xmlns:p="http://www.parts-depot.com"
xmlns:xlink="http://www.w3.org/1999/xlink">
<Part id="00345" xlink:href="http://www.parts-depot.com/parts/00345"/>
<Part id="00346" xlink:href="http://www.parts-depot.com/parts/00346"/>
<Part id="00347" xlink:href="http://www.parts-depot.com/parts/00347"/>
<Part id="00348" xlink:href="http://www.parts-depot.com/parts/00348"/>
</p:Parts>
Assume that through content negotiation the service determined that the client
wants the representation as XML (for machine-to-machine processing).
Note that the parts list has links to get detailed info about each part. This is a
key feature of REST. The client transfers from one state to the next by
examining and choosing from among the alternative URLs in the response
document.
82. Rest
Get Detailed Part Data
The web service makes available a URL to each part resource. Example,
here's how a client requests part 00345:
http://www.parts-depot.com/parts/00345
Here's the document that the client receives:
<?xml version="1.0"?>
<p:Part xmlns:p="http://www.parts-depot.com"
xmlns:xlink="http://www.w3.org/1999/xlink">
<Part-ID>00345</Part-ID>
<Name>Widget-A</Name>
<Specification xlink:href="http://www.partsdepot.com/parts/00345/specification"/>
</p:Part>
Again observe how this data is linked to still more data - the specification for
this part may be found by traversing the hyperlink. Each response document
allows the client to drill down to get more detailed information.
83. Rest
Submit PO
The web service makes available a URL to submit a PO. The client creates a
PO instance document which conforms to the PO schema that Parts Depot has
designed (and publicized in a WSDL document). The client submits PO.xml as
the payload of an HTTP POST.
The PO service responds to the HTTP POST with a URL to the submitted PO.
Thus, the client can retrieve the PO any time thereafter (to update/edit it). The
PO has become a piece of information which is shared between the client and
the server. The shared information (PO) is given an address (URL) by the
server and is exposed as a Web service.
84. Rest
Logical URLs versus Physical URLs
A resource is a conceptual entity. A representation is a concrete manifestation
of the resource. This URL:
http://www.parts-depot.com/parts/00345
is a logical URL, not a physical URL.
Thus, there doesn't need to be, for example, a static HTML page for each part.
In fact, if there were a million parts then a million static HTML pages would not
be a very attractive design.
[Implementation detail: Parts Depot could implement the service that gets
detailed data about a particular part by employing a Java Servlet which parses
the string after the host name, uses the part number to query the parts
database, formulate the query results as XML, and then return the XML as the
payload of the HTTP response.]
As a matter of style URLs should not reveal the implementation technique
used. You need to be free to change your implementation without impacting
clients or having misleading URLs.
85. Rest
REST Web Services Characteristics
Here are the characteristics of REST:
Client-Server: a pull-based interaction style: consuming components pull
representations.
Stateless: each request from client to server must contain all the information
necessary to understand the request, and cannot take advantage of any stored
context on the server.
Cache: to improve network efficiency responses must be capable of being
labeled as cacheable or non-cacheable.
Uniform interface: all resources are accessed with a generic interface (e.g.,
HTTP GET, POST, PUT, DELETE).
Named resources - the system is comprised of resources which are named
using a URL.
86. Rest
Interconnected resource representations - the representations of the resources
are interconnected using URLs, thereby enabling a client to progress from one
state to another.
Layered components - intermediaries, such as proxy servers, cache servers,
gateways, etc, can be inserted between clients and resources to support
performance, security, etc.
87. Rest
Principles of REST Web Service Design
1. The key to creating Web Services in a REST network (i.e., the Web) is to
identify all of the conceptual entities that you wish to expose as services.
Above we saw some examples of resources: parts list, detailed part data,
purchase order.
2. Create a URL to each resource. The resources should be nouns, not verbs.
For example, do not use this:
http://www.parts-depot.com/parts/getPart?id=00345
Note the verb, getPart. Instead, use a noun:
http://www.parts-depot.com/parts/00345
88. Rest
3. Categorize your resources according to whether clients can just receive a
representation of the resource, or whether clients can modify (add to) the
resource. For the former, make those resources accessible using an HTTP
GET. For the later, make those resources accessible using HTTP POST, PUT,
and/or DELETE.
4. All resources accessible via HTTP GET should be side-effect free. That is,
the resource should just return a representation of the resource. Invoking the
resource should not result in modifying the resource.
5. No man/woman is an island. Likewise, no representation should be an
island. In other words, put hyperlinks within resource representations to enable
clients to drill down for more information, and/or to obtain related information.
89. Rest
6. Design to reveal data gradually. Don't reveal everything in a single response
document. Provide hyperlinks to obtain more details.
7. Specify the format of response data using a schema (DTD, W3C Schema,
RelaxNG, or Schematron). For those services that require a POST or PUT to it,
also provide a schema to specify the format of the response.
8. Describe how your services are to be invoked using either a WSDL
document, or simply an HTML document.
90. Rest – POX over HTTP
import javax.xml.bind.annotation.XmlType;
@XmlType
public class Product {
private String id;
private String name;
private double price;
public Product() { }
//Getters and Setters omitted...
91. Rest
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class ProductCatalog {
private List<Product> products;
public ProductCatalog() {
products = new ArrayList<Product>();
Product p = new Product();
p.setId("123");
p.setName("Shirt");
p.setPrice(159.95D);
Product p2 = new Product();
p2.setId("456");
p2.setName("Monkey");
p2.setPrice(2500D);
products.add(p);
products.add(p2);
}
92. Rest
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
@Override
public String toString() {
return products.toString();
}
}
93. Rest
public class SimpleRestServlet extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet {
public SimpleRestServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
System.out.println("DoGet invoked on RESTful service.");
ProductCatalog catalog = new ProductCatalog();
Source xmlSource = asXml(catalog);
ServletOutputStream out = response.getOutputStream();
response.setContentType("text/xml");
StreamResult st = new StreamResult(out);
try {
99. Rest
Developing REST Webservices in MyEclipse – Using JAX-RS
1. Introduction
We will outline the process of developing a REST web service, deploying it to
the internal MyEclipse Tomcat server and testing it with the REST Web
Services Explorer.
The REST features in MyEclipse are based on Jersey, which is the reference
implementation for JAX-RS, the Java API for RESTful Web Services. We will be
creating a simple web service which we will use to maintain a list of customers.
MyEclipse also supports developing SOAP web services using JAX-WS; for
folks needing to develop and deploy WebSphere JAX-RPC or WebSphere JAXWS web services, please take a look at MyEclipse Blue Edition.
100. Rest
System Requirements
This tutorial was created with MyEclipse 7.0. If you are using another version of
MyEclipse (possibly newer), most of these screens and instructions should still
be very similar
Creating the REST Web Service Project
Invoke the wizard using File > New > Other > MyEclipse > Java Enterprise
Projects > Web Service Project.
Name the project restdemo and select REST (JAX-RS) from the list of
frameworks.
Click Next to move to page 2 of the wizard. On this page you can specify the
path at which the services will be available, the name of the corresponding
JAX-RS servlet and libraries which you wish to add to your project. For this
project the defaults are fine, so click Finish to create the project.
101. Rest
Instead of creating a new project, you may also add REST capabilities to any
existing Java EE 5 Web project. From the project's context menu,
select MyEclipse > Add REST Capabilities...
Creating the REST Web Service
Creating the Customer entity
To start, create a simple Customer class with id, name and address fields; this
class represents the Customer entity we will be managing with our web service.
Use the File > New > Class wizard, put Customer in
theName field, com.myeclipseide.ws in the Package field and Finish the
wizard. Replace the contents of the generated class with the following code:
102. Rest
we will be using XML as the serialization format, i.e. we will send and receive
Customer entities from the web service using XML.
The @XMLRootElement annotation on the Customer class is a JAXB
annotation which allows JAXB to convert this entity from Java to XML and back.
It is possible to annotate the fields and methods within the class to customize
the serialization, but for our tutorial the JAXB defaults are fine.
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
private int id;
private String name;
private String address; //write setters and getters
…} – Rest refer the Study Material
103. Rest
Mapping HTTPMethods to Operations Performed
HTTP Method Operations Performed
GET Get a resource
POST Create a resource and other operations, as it has no defined semantics
PUT Create or update a resource
DELETE Delete a resource
104. Rest
HowDoes Jersey Fit In?
Jersey is Sun's production quality reference implementation for JSR 311: JAXRS:
The Java API for RESTful Web Services. Jersey implements support for the
annotations defined in JSR-311, making it easy for developers to build RESTful
web services with Java and the Java JVM.
Jersey also adds additional features not specified by the JSR.
The latest version of the JAX—RS API's can be viewed at
https://jsr311.dev.java.net/nonav/javadoc/index.html
105. Rest
Working with Jersey
To successfully run the JAX-RS reference implementation, you need a lot of
JARs. It’s
probably easiest to put them on your server’s classpath, but you can certainly
add them
to your WAR’s WEB-INF/lib directory if you like. As of the current release, they
are:
• activation.jar
• asm-3.1.jar
• grizzly-servlet-webserver-1.7.3.2.jar• http.jar
• jaxb-api.jar
• jaxb-impl.jar
• jaxb-xjc.jar
• jaxws-api.jar• jdom-1.0.jar• jersey.jar• jettison-1.0-RC1.jar• jsr173_api.jar
• jsr250-api.jar• jsr311-api.jar• rome-0.9.jar• wadl2java.jar
106. Rest
Modifying the web.xml file
You need to modify your web.xml file to use the Jersey adapter servlet, much
as you
would when using JavaServer Faces:
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>ServletAdaptor</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletAdaptor</servlet-name>
<url-pattern>/resources/*</url-pattern>
</servlet-mapping>
107. Rest
Creating Hello World with Jersey
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.ProduceMime;
/**
* Simplest REST web service.
*/
@Path("/helloRest")
public class HelloRest {
/**
•Retrieves representation of an instance of
•HelloRest.java
* @return a string with HTML text.
*/
@GET
@ProduceMime("text/html")
public String sayHello() {
return "<html><body><h1>Hello from REST!</body></h1></html>";
}
}
108. Rest
Here you create a POJO that is annotated with
javax.ws.rs.Path. Its value attribute indicates the path where this resource will
be made available. The resource path follows the adapter servlet path, so you
will be able to reach an instance of this class at
<server>:<port>/<context>/<jersey-servletmapping>/<path-value>
By using the JAX-RS
@GET annotation, you indicate that the sayHello method is the one you want
to respond to HTTP GET requests.
Then use the @ProduceMime annotation to indicate the MIME
type you want to return on response. Here you use text/html, but you can use
any MIME type that makes sense for your application, including text/xml and
image/gif.
109. Rest
Creating a Single Path for Variable Resources of the Same Type
@Path("/products/{id}")
public class ProductResource {
@Context
private UriInfo context;
/** Creates a new instance of ProductResource */
public ProductResource() { }
@GET
@ProduceMime("text/plain")
public String getProduct(@PathParam("id") int productId) {
switch (productId) {
case 1: return "A Shiny New Bike";
case 2: return "Big Wheel";
case 3: return "Taser: Toddler Edition";
default: return "No such product";
}
}
}
110. Rest
Restricting the Structure of Values in a Path Template
@Path("products/{id:[a-zA-Z][a-zA-Z_0-9]}”).
@Path("/products/{id: d{3}}") - the input should be exactly three digits.
URL http://
localhost:8080/restexamples/resources/products/555,
111. Rest
Accessing Query Parameters
Use the @QueryParam annotation on your method parameter. Optionally,
include the @DefaultValue in case the query parameter you’re expecting is not
passed.
@GET
@Produces("text/xml")
public String getProducts(
@PathParam("id") int productId,
@QueryParam("results")
@DefaultValue("5") int numResults) {
StringBuilder result = new StringBuilder("<products>");
//return the number of results requested
for (int i = 0; i < numResults; i++) {
result.append("<p>Product " + i + "</p>");
}
result.append("</products>");
return result.toString();
}
112. Rest
Marshaling a Custom Type to XML in a Response
Problem You want your service to provide an XML view of a custom Java type
you’ve defined.
Hint: @XmlRootElement, and create a JAX-RS service that indicates that it
produces XML with the @Produces("application/xml") annotation.
shows a basic Java type that your service can automatically marshal to
XML using JAXB.
Employee.java with JAXB annotations to assist in automatic marshaling
package com.soacookbook.rest.xml;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="employee")
public class Employee {
@XmlElement(name="id")
int id;
@XmlElement(name="name") String name; }
113. Rest
public class EmployeeService {
private static Map<Integer, Employee> emps = populateDatabase();
public EmployeeService() { }
@GET
@Path("{id}")
@Produces("application/xml")
public Employee getEmployee(@PathParam("id") int empId) {
return emps.get(empId);
}
private static Map<Integer, Employee> populateDatabase(){
Map<Integer, Employee> emps = new HashMap<Integer, Employee>();
Employee e1 = new Employee(); e1.id = 1; e1.name = "Bill Gates";
Employee e2 = new Employee();e2.id = 2;e2.name = "Larry Ellison";
Employee e3 = new Employee();e3.id = 3;e3.name = "Steve Jobs";
emps.put(1, e1);
emps.put(2, e2);
emps.put(3, e3);
return emps;}}
114. Rest
Offering Different Representations of the Same Resource
Problem
You want your service to provide alternate views of the same resource.
Discussion
A standard browser will pass the MIME types it can handle by passing the
HTTP Accept header in its request. A typical request header sent from Firefox
looks like this:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
The client is telling the server that it would prefer to get HTML or XHTML, and
its next preference is to accept XML. The preferences are indicated not only by
the order in which they appear, but with the q parameter, used to specify a
relative “quality factor” or how strong the preference is for the given media type
on a scale of 0 to 1.
115. Rest
import java.io.File;
import javax.activation.MimetypesFileTypeMap;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
/**
* If we put a @Produces annotation on the class level,
* that will be the value matched despite browser preferences
* in the Accept header.
*/
@Path("/duke")
@Produces("text/plain")
public class DifferentRepresentations {
private static final String IMG_PATH =
"C:programs/eclipse/workspace/restexamples/WebContent/duke.gif";
Contd…
116. Rest
@GET
@Produces("text/html")
public String doGetAsHtml() {
return "<html><h1>Html Duke</h1></html>";
}
//notice no override, as this method returns the default
@GET
public String doGetAsPlainText() {
return "Plain Duke";
}
@GET
@Produces("image/*")
public Response doGetAsImage() {
File image = new File(IMG_PATH);
if (!image.exists()) {
throw new WebApplicationException(404);
}
String type = new MimetypesFileTypeMap().getContentType(image);
return Response.ok(image, type).build();
} contd…
118. Rest
Creating a Resource
Problem
You want to provide a way for users to create a RESTful resource in JAX-RS.
Solution
Use the @POST annotation on a resource method to indicate that it accepts
HTTP POST data, and add the entity in the method with the incoming data.
119. Rest
@Path("user/{id}")
@Singleton
public class UserService {
private Map<Integer, User> userDatabase;
//create fake user database to keep example simple
public UserService() {
userDatabase = new HashMap<Integer, User>();
}
@POST
@Consumes("application/xml")
public Response postUser(User user) {
System.out.println("Post User.");
//save to database here...
userDatabase.put(user.getId(), user);
System.out.println("Posted user: " + user);
URI createdUri = UriBuilder.fromPath("user/" +
user.getId()).build(user);
System.out.println("post: createdUri: " + createdUri);
//return a 201 'created' status
return Response.created(createdUri).build();
}
126. Web Services Overview
Distributed Computing
Client/server model
Doesn‘t scale
Not secure
Distributed object model
Components: packaging and interoperability
Remoting: remote method invocation
COM, CORBA, Java RMI and EJB
Not Internet-friendly
Interoperability issues: poor/non-existent standards
Tightly coupled: still doesn‘t scale
127. Web Services Overview
Distributed Computing
3-tier Application Architecture
Great way to build scalable Web applications
But such applications are silos
Integration is an afterthought
They can be integrated behind the firewall
Even that can be a problem
They do not provide a way to integrate across the
firewall (i.e. over the Internet)
129. Web Services Overview
Portal Limitations
No standard way to expose functionality
Integration is expensive and error-prone
Hard to outsource
Not designed to be used outside original
scope
The problem?
HTML is designed for presentation to people
Can’t repurpose it in a general, reliable way
130. Web Services Overview
What Is a Web Service?
The solution? Web Services!
A Web Service exposes functionality to a consumer
Over the Internet or intranet
A programmable URL
Functions you can call over the Internet
Based on Web standards
HTTP, XML, SOAP, WSDL, UDDI, with more to come
Can be implemented in any language on any platform
Black boxes
Component-like, reusable
131. Web Services Overview
What Is a Web Service?
A Web Service combines the best features of
distributed computing and portals and
eliminates the worst
Provides a mechanism for invoking methods
remotely
Uses Web standards (e.g. HTTP, XML) to do so
132. Web Services Overview
What Is a Web Service?
Web Services allow you to interconnect:
Different companies
Many/any devices
Applications
Different clients
Not just browsers
Distribution and integration of application
logic
Enable the programmable Web
Not just the purely interactive Web
Web Services are loosely coupled
133. Web Services Overview
What is a Web Service?
New paradigm for Internet development
Deliver applications as services
Richer, customer-driven experience
Continuous delivery of value/bits
Third-generation Internet
134. Web Services Overview Evolution
of the Web
HTML
HTML
HTML, XML
HTML, XML
Generation 1
Static HTML
Generation 2
Web Applications
Generation 3
Web Services
138. Web Services
What Are Web Services?
Allow applications to communicate across the
internet
Platform independent
Protocol independent
Synchronous/asynchronous
Statefull/stateless
BizTalk®
ASP.NET
143. Web Services Overview
Application Model
Partner
Web Service
Other Web Services
Internet + XML
End Users
YourCompany.com
Application Business Logic Tier
Data Access and Storage Tier
Other Applications
Partner
Web Service
144. Web Services Overview
Sample Web Services
E-commerce: order books, office supplies,
other products
Track packages: UPS, FedEx
Weather
Maps
Telephone redirection, customizable rules
and messages
145. Underlying Technologies
XML Is the Glue
Connectivity
Connect
the Web
Presentation
Browse
the Web
Connecting
Applications
Program
the Web
146. Underlying Technologies
Web Services Stack
Directory: Publish & Find Services:
UDDI
Inspection: Find Services on server:
DISCO
Description: Formal Service Descriptions:
WSDL
Wire Format: Service Interactions:
SOAP
Universal Data Format:
XML
Ubiquitous Communications:
Internet
Simple, Open, Broad Industry Support
147. Underlying Technologies
Web Services Stack
Discovery
Directory allows potential clients to locate relevant
Web Services
UDDI
Inspection allows you to locate documents about
Web Services located on at a given URL
DISCO
A Description language defines the format of
methods provided by a Web Service
WSDL
148. Underlying Technologies
Web Services Stack
UDDI
Link to Discovery Document (XML)
http://www.ibuyspy.com/ibuyspy.disco
Request Discovery Document
DISCO
Return Discovery Document (XML)
Description
WSDL
http://www.ibuyspy.com/ibuyspycs/InstantOrder.asmx?wsdl
Request Service Description
Return Service Description (XML)
Wire Format
Request Service
Return Service Response (XML)
SOAP
Web Service
Web Service Client
Inspection
UDDI or
other
directory
service
Directory
http://www.uddi.org
Locate a Service
149. Underlying Technologies
Web Service Wire Format
The Web Service Wire Format specifies how
specific messages are exchanged
HTTP-GET
HTTP-POST
SOAP
HTTP-GET and HTTP-POST use a minimal
HTTP interface to invoke Web Services
Limited support for data types
SOAP provides a robust HTTP/XML interface
Extensive support for data types
150. XML Overview
XML Basics
XML is designed to represent and transfer
structured data
In HTML:
In XML:
XML does not display or transform data
XML separates data from formatting and
transforming
HTML and XML are both derived from SGML
In different ways
151. XML Overview
XML Syntax
XML is composed of tags and attributes
Tags can be nested
Representing entities, entity properties, and entity
hierarchy
<ROOT>
<Orders OrderID="10643" CustomerID="ALFKI" EmployeeID="6"
OrderDate="1997-08-25T00:00:00" RequiredDate="1997-09-22T00:00:00"
ShippedDate="1997-09-02T00:00:00" />
</ROOT>
152. XML Overview
XML Schemas
XML schemas describe the structure of an
XML document
XML schemas describe the tag and attribute
specifications
Simple and compound data types
XML schemas also describe constraints on the
contained text
XML schemas and the DTD are mutually
exclusive