0% found this document useful (0 votes)
173 views86 pages

Unit 1: Web Services Basics

This document discusses web services and distributed computing. It defines web services as self-contained software modules that can complete tasks over a network on behalf of users or applications. Web services allow for loose coupling between applications and dynamic assembly of services. The document also describes types of web services including informational and complex services. It discusses key aspects of distributed computing including middleware, Internet protocols like TCP/IP, and reference models like OSI.

Uploaded by

Sneha Biswas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
173 views86 pages

Unit 1: Web Services Basics

This document discusses web services and distributed computing. It defines web services as self-contained software modules that can complete tasks over a network on behalf of users or applications. Web services allow for loose coupling between applications and dynamic assembly of services. The document also describes types of web services including informational and complex services. It discusses key aspects of distributed computing including middleware, Internet protocols like TCP/IP, and reference models like OSI.

Uploaded by

Sneha Biswas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES

FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Unit 1 : Web services basics


What Are Web Services?
A Web service is a self-describing, self-contained software module available via a network, such as the
Internet, which completes tasks, solves problems, or conducts transactions on behalf of a user or
application.

Web services constitute a distributed computer infrastructure made up of many different interacting
application modules trying to communicate over private or public networks (including the Internet and
Web) to virtually form a single logical system.

A Web service can be:

1. a self-contained business task, such as a funds withdrawal or funds deposit service;


2. a full-fledged business process, such as the automated purchasing of office supplies;
3. an application, such as a life insurance application or demand forecasts and stock
replenishment;
4. a service-enabled resource, such as access to a particular back-end database containing patient
medical records.

Web services address the problems of rigid implementations of predefined relationships and isolated
services scattered across the Internet.

The long-term goal of Web services technology is to enable distributed applications that can be
dynamically assembled according to changing business needs, and customized based on device (such as
personal computers, workstations, laptops, WAP-enabled cellular phones, personal digital assistants),
network (such as cable, UMTS, XDSL, Bluetooth, etc.) and user access while enabling wide utilization of
any given piece of business logic wherever it is needed.

Once a Web service is deployed, other applications and Web services can discover and invoke it.

Web services are loosely coupled software modules: Web services protocols, interfaces, and registry
services enable applications to work cooperatively together using the principle of loose coupling.

Web services semantically encapsulate discrete functionality: A Web service is a self-contained


software module that performs a single task. The module describes its own interface characteristics, i.e.,
the operations available, the parameters, data typing, and the access protocols, in such a way that other
software modules can determine what it does, how to invoke its functionality, and what result to expect
in return.

Web services can be accessed programmatically: A Web service provides programmable access – this
allows embedding Web services into remotely located applications. This enables information to be

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

1
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
queried and updated, thus improving efficiency, responsiveness, and accuracy – ultimately leading to
high added value to the Web services clients.

Web services can be dynamically found and included in applications: Unlike existing interface
mechanisms, Web services can be assembled to serve a particular function, solve a specific problem, or
deliver a particular solution to a customer.

Web services are described in terms of a standard description language: the Web Services Description
Language or WSDL describes both functional as well as nonfunctional service characteristics.

Web services are distributed over the Internet: Web services make use of existing, ubiquitous transport
Internet protocols like HTTP.

Types of Web services


Topologically, Web services can come in two flavors

1. Informational, or type I, Web services, which support only simple request/response operations
and always wait for a request; they process it and respond.
2. Complex, or type II Web services implement some form of coordination between inbound and
outbound operations.

Simple or informational services

Informational services are services of relatively simple nature. They either provide access to content
interacting with an end user by means of simple request/response sequences, or alternatively may
expose back-end business applications to other applications. Web services that typically expose the

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

2
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
business functionality of the applications and components that underlie them are known as
programmatic services.

Informational services can be subdivided into three subcategories

1. Pure content services, which give programmatic access to content such as weather report
information, simple financial information, stock quote information, design information, news
items, and so on.
2. Simple trading services, which are more complicated forms of informational services that can
provide a seamless aggregation of information across disparate systems and information
sources, including back-end systems, giving programmatic access to a business information
system so that the requestor can make informed decisions.
eg: logistic services
3. Information syndication services, which are value-added information Web services that purport
to “plug into” commerce sites of various types, such as e-marketplaces, or sell-sites.
Typical examples of syndicated services might include reservation services on a travel
site or rate quote services on an insurance site.

Complex services or business processes

• Enterprises can use a singular (discrete) service to accomplish a specific business task, such as
billing or inventory control.
• When enterprises need to compose several services together to create a business process such
as customized ordering, customer support, procurement, and logistical support, they need to
use complex Web services.
• Complex (or composite) services typically involve the assembly and invocation of many pre-
existing services possibly found in diverse enterprises to complete a multi-step business
interaction.

Distributed computing infrastructure

A distributed system is characterized as a collection of (probably heterogeneous) networked computers,


which communicate and coordinate their actions by passing messages. Distribution is transparent to the
user so that the system appears as a single integrated facility.

A distributed system has numerous operational components (computational elements, such as servers
and other processors, or applications) which are distributed over various interconnected computer
systems.

Distributed systems usually use some kind of client–server organization. A computer system that hosts
some component of a distributed system is referred to as a host. Distributed components are typically

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

3
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
heterogeneous in that they are written in different programming languages and may operate under
different operating systems and diverse hardware platforms.

Internet protocols
To enable data to be transmitted across the Internet typical distributed platforms, such as J2EE, rely on
the support of Internet protocols.

The most prominent of the Internet protocols is the Transport Control Protocol over Internet Protocol
(or TCP/IP). The Internet Protocol (IP), the basic protocol of the Internet, enables the unreliable delivery
of individual packets from one host to another.

The Transport Control Protocol (TCP) adds the notions of connection and reliability.

These two protocols provide for the reliable delivery of streams of data from one host to another across
communication networks, and the Internet in particular.

Open Systems Interconnection

A reference model is a conceptual blueprint of how communications should take place. It addresses all
the processes required for effective communication and divides these processes into logical groupings
called layers. When a communication system is designed in this manner, it is known as layered
architecture.

The TCP/IP network protocol

The TCP/IP stack is shown in Figure in association with the various layers of the ISO/OSI model. This
figure shows that each level of the TCP/IP stack builds on the services provided by the layer below it.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

4
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Middleware
Middleware is connectivity software that is designed to help manage the complexity and heterogeneity
inherent in distributed systems by building a bridge between different systems thereby enabling
communication and transfer of data.

Middleware could be defined as a layer of enabling software services that allow application elements to
interoperate across network links, despite differences in underlying communications protocols, system
architectures, operating systems, databases, and other application services.

The role of middleware is to ease the task of designing, programming, and managing distributed
applications by providing a simple, consistent, and integrated distributed programming environment.
Essentially, middleware is a distributed software layer, or “platform,” that lives above the operating
system and abstracts over the complexity and heterogeneity of the underlying distributed environment
with its multitude of network technologies, machine architectures, operating systems, and programming
languages.

The figure shows that the middleware abstraction comprises two layers. The bottom layer is concerned
with the characteristics of protocols for communicating between processes in a distributed system and
how the data objects, e.g., a sales order, and data structures used in application programs can be
translated into a suitable form for sending messages over a communications network, taking into
account that different computers may rely on heterogeneous representations for simple data items. The
layer above is concerned with interprocess communication mechanisms, while the layer above that is
concerned with non-message- and message-based forms of middleware.

Non-message-based forms of middleware provide synchronous communication mechanisms designed to


support client–server communication.

Message-based forms of middleware provide asynchronous messaging and event notification


mechanisms to exchange messages or react to events over electronic networks.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

5
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

client–server model
The client–server architecture is one of the common solutions to the conundrum of how to handle the
need for both centralized data control and widespread data accessibility.

Client–server involves client processes (service consumers) requesting service from server processes
(service providers).

Servers may in turn be clients of other servers. For instance, a Web server is often a client of a local file
server (or database server) that manages the files (storage structures) in which Web pages are stored
.

Characteristics of interprocess communication

Messaging
Distributed systems and applications communicate by exchanging messages. Messaging is a technology
that enables high-speed, asynchronous, program-to-program communication with reliable delivery.

Programs communicate by sending packets of data called messages to each other. The concept of a
message is a well-defined, data-driven text format – containing the business message and a network
routing header – that can be sent between two or more applications.

A message typically comprises three basic elements: a header, its properties, and a message payload or
body.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

6
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

The message header is used by both the messaging system and the application developer to provide
information about characteristics such as the destination of a message, the message type, the message
expiration time, and so forth.

The properties of a message contain a set of application-defined name/value pairs.

The message body carries the actual “payload” of the message. The format of the message payload can
vary across messaging implementations. Most common formats are plain text, a raw stream of bytes for
holding any type of binary data, or a special XML message type that allows the message payload to be
accessed using any number of common XML parsing technologies.

Message passing between a pair of processes is supported by two message communication operations:
send and receive, defined in terms of destinations and messages.

Marshalling is the process of taking an object or any other form of structured data items and breaking it
up so that it can be transmitted as a stream of bytes over a communications network in such a way that
the original object or data structure can be reconstructed easily on the receiving end.

Unmarshalling is the process of converting the assembled stream of bytes on arrival to produce an
equivalent object or form of structured data at the destination point. Therefore, marshalling comprises
the transformation of structured data items and primitive values into an agreed standard form of
representation for transmission across the network.

Java and XML use the terms serialization and deserialization to denote the process of marshalling and
unsmarshalling

Message destinations and sockets

messages are sent to ports.

Servers usually publicize their port numbers for use by clients and processes use multiple ports from
which to receive messages.

During interprocess communication messages are sent to (Internet address, local port) pairs.

Many applications involve two processes in different hosts communicating with each other over a
network. These two processes communicate with each other by exchanging (sending and receiving)
messages. A process sends messages into, and receives messages from, the network through its socket.

A process’s socket could be thought of as the entry point to the process. Interprocess communication
consists of transmitting a message between a client and a socket in another process Once the message
arrives at its destination, it passes through the receiving process’s socket and the receiving process then
acts on the message.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

7
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Synchronous and asynchronous forms of message communication

These modes are: synchronous or time dependent and asynchronous or time independent.

The defining characteristic of a synchronous form of execution is that message communication is


synchronized between two communicating application systems, which must both be up and running,
and that execution flow at the client’s side is interrupted to execute the call. Both the sending and the
receiving application must be ready to communicate with each other at all times.

When using asynchronous messaging, the caller employs a send and forget approach that allows it to
continue to execute after it sends the message. With asynchronous communication, an application
sends (requestor or sender) a request to another while it continues its own processing activities. The
sending application does not have to wait for the receiving application to complete and for its reply to
come back.

Synchronous forms of middleware

Programming models for synchronous forms of middleware are composed of cooperating programs
running in several interacting distributed processes. Such programs need to be able to invoke operations
synchronously in other processes, which frequently run in different computing systems.

The most familiar approaches to non-message-based forms of middleware are typified by the remote
procedure call (RPC) and the remote method invocation (RMI).

Remote procedure calls


RPC is a basic mechanism for interprogram communication. In effect, RPC is the middleware mechanism
used to invoke a procedure that is located on a remote system, and the results are returned.

By design, the RPC programming style mimics the serial thread of execution that a “normal” non-
distributed application would use, where each statement is executed in sequence.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

8
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

The RPC mechanism is the simplest way to implement client–server applications because it keeps the
details of network communications out of the application code.

In RPC-style programming, an object and its methods are “remoted” such that the invocation of the
method can happen across a network separation.

In client application code, an RPC looks like a local procedure call, because it is actually a call to a local
proxy known as a client stub (a surrogate code that supports RPCs).

The client stub communicates with a server stub using the RPC runtime library, which is set of
procedures that support all RPC applications. A server stub is like a skeleton method in that it
unmarshals the arguments in the request message, calls the corresponding service procedure, and
marshals the return results for the reply message.

The server stub communicates its output to the client stub, again by using the RPC runtime library.
Finally, the client stub returns to the client application code.

Remote method invocation


The Java RMI provides a simple and direct model for distributed computation with Java objects on the
basis of the RPC mechanism.

If the particular method happens to be on a remote machine, Java provides the capability to make the
RMI appear to the programmer to be the same as if the method is on the local machine.

RMI applications comprise two separate programs: a server and a client. RMI provides the mechanism
by which the server and the client communicate and pass information back and forth.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

9
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

There are two different kinds of classes that can be used in RMI: remote and serializable classes.

A remote object is an instance of a remote class. When a remote object is used in the same address
space, it can be treated just like an ordinary object. But if it is used externally to the address space, the
object must be referenced by an object handle.

Asynchronous forms of middleware


Asynchronous communication promotes a loosely coupled environment in which an application does
not need to know the intimate details of how to reach and interface with other applications.

Store and forward messaging

With the store and forward queuing mechanism, messages are placed on a virtual channel called a
message queue by a sending application and are retrieved by the receiving application as needed.
Messages are exchanged through a queue, which is the destination to which senders send messages and
a source from which receivers receive messages.

The queue is a container that can keep hold of a message until the recipient collects it. The message
queue is independent of both the sender and receiver applications and acts as a buffer between the
communicating applications.

Asynchronous communication with the store and forward queuing mechanism allows work to be
performed whenever applications are ready.

The message delivery semantics include several delivery options which range from exactly-once delivery
to at-least-once delivery and to at-most-once delivery.

The store and forward queuing mechanism is typical of a many-to-one messaging paradigm where
multiple applications can send messages to a single application. The same application can be sender,
receiver, or both sender and receiver. Message queuing provides a highly reliable, although not always
timely, means of ensuring that application operations are completed.

In many applications there is an additional requirement that the concept of store and forward is capable
of being repeated across multiple message servers that are chained together.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

10
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

In this configuration, each message server uses the principle of store and forward and message
acknowledgements to get the message to the next server in the chain of interconnected message
servers.

Publish/subscribe messaging
This mode of messaging is a slightly more scalable form of messaging when compared to the store and
forward mechanism. The publish/subscribe messaging works as follows. Suppose that a publisher
application publishes messages on a specific topic, such as sending out new product prices or new
product descriptions to retailers.

Multiple subscribing applications can subscribe to this topic and receive the messages published by the
publishing application.

This figure describes how the publish/subscribe semantics work:

1. Publishers publish messages to specific topics.


2. A message server keeps track of all the messages, and all its currently active and durable
subscribers (subscribers who specifically expressed a durable interest in the topic). The message
server provides a secure environment for the messaging system by handling authorization and
authentication.
3. As soon as messages are published on a specific topic, they are distributed to all of its
subscribers. Durable subscribers, who were not connected at the time of message

Event-driven processing mechanisms

The familiar one-to-one request/reply interaction pattern that is commonly used in client–server
systems is inadequate for systems that must react to events representing changes in the environment,
information of interest, or process status, which are particularly well suited for distributed environments
without central control.

The asynchrony, heterogeneity, and inherent loose coupling that characterize modern applications in a
wide area network promote event interaction as a natural design abstraction for a growing class of
software systems. Such systems are based on a technical infrastructure known as an event notification
service

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

11
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
An event notification service complements other general-purpose middleware services, such as point-
to-point and multicast communication mechanisms, by offering a manyto- many communication and
integration facility. Clients in an event notification scheme are of two kinds: objects of interest, which are
the producers of notifications, and interested parties, which are the consumers of notifications.

Point-to-point queuing

The point-to-point messaging model allows clients to send and receive messages both synchronously
and asynchronously via queues. The point-to-point messaging model provides reliable communication
for multi-staged applications. This model has traditionally been a pull-based or pollingbased model,
where messages are requested from a queue instead of being pushed to the client automatically as is
the case with publish/subscribe model.

Request/reply messaging

On many occasions applications require that request/reply messaging operations be performed. Here,
we can distinguish between two types of request/reply messaging operations: synchronous
request/reply messaging and asynchronous request/reply messaging operations. Synchronous
request/reply messaging is often necessary when trying to integrate with a Web service client that
blocks and waits for a synchronous response to return to it

In the asynchronous version of request/reply messaging, the requestor (sender) expects the reply to
arrive at a later time and continue its work unaffected.

a simple request /reply asynchronous messaging configuration. Observe that in this figure message
delivery channels are not bidirectional. To perform a request/reply operation the sender must use two
channels: one for the request and one for the reply.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

12
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Message-oriented middleware

Message-oriented middleware (MOM) is an infrastructure that involves the passing of data between
applications using a common communication channel that carries self-contained messages.

In an MOM-based communication environment, messages are usually sent and received


asynchronously.

Using message-based communications, applications are abstractly decoupled as senders and receivers
are not aware of each other.

Instead they send and receive messages from the messaging system and it is the responsibility of the
messaging
system, namely the MOM, to forward the messages to their intended destination.

MOM is interposed between the client and the server part of client–server architecture and handles
asynchronous calls between clients and servers,

To support this asynchronous model, MOM products typically use message queues to store calls
temporarily and allow clients and servers to run at different times. Messages in the queue can consist of
formatted data, requests for action, or both.

The messaging system is responsible for managing the connection points between messaging clients,
and for managing multiple channels of communication between the connection points. The messaging
system is usually implemented by a software module known as the message (or integration) broker.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

13
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Integration brokers

Integration brokers perform necessary content and format transformation to translate incoming
messages into a scheme that the destination system(s) can understand and utilize. Integration brokers
are usually built on top of some MOM implementations and so the general principles of MOM also apply
to them.

Initially integration brokers were called message brokers but this name often led to a
mischaracterization and confusion between message brokers and message-oriented middleware. More
recently, message brokers have been renamed integration brokers, which is a more descriptive name for
the features they provide.

An integration broker is an application-to-application middleware service that is capable of one-to-


many, many-to-one, and many-to-many message distribution. An integration broker is a software hub
that records and manages the contracts between publishers and subscribers of messages.

The Java Message Service (JMS)

JMS is a vendor-agnostic API for enterprise messaging that can be used with many different MOM
vendors. JMS acts as a wrapper around different messaging products, allowing developers to focus on
actual application development and integration, rather on the particulars of each other’s APIs.

Application developers use the same API to access many different systems. JMS is not a messaging
system itself. It is an abstraction of the interfaces and classes needed by messaging clients when
communicating with different messaging systems.

JMS not only provides a Java API for connectivity to MOM systems, but also supports messaging as a
first-class Java distributed computing paradigm on an equal footing with RPC

A common application for JMS involves interfacing Enterprise Java Beans (EJBs) with legacy applications
and sending legacy-related data between the two.

The JMS messaging point-to-point model allows JMS clients to send and receive messages both
asynchronously and synchronously via queues.

JMS supports two types of message delivery: reliable message delivery and guaranteed message
delivery.

overview of XML
XML is an extensible markup language used for the description and delivery of marked-up electronic text
over the Web.

Two important characteristics of XML distinguish it from other markup languages: its document type
concept and its portability.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

14
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
An important aspect of XML is its notion of a document type. XML documents are regarded as having
types. XML’s constituent parts and their structure formally define the type of a document.

An XML document is composed of named containers and their contained data values. Typically, these
containers are represented as declarations, elements, and attributes. A declaration declares the version
of XML used to define the document. The technical term used in XML for a textual unit, viewed as a
structural component, is element.

An XML document is also known as an instance or XML document instance. This signifies the fact that an
XML document instance represents one possible set of data for a particular markup language.

The example in Listing typifies an XML document instance. This example shows billing information
associated with a purchase order issued by plastics manufacturer.

<?xml version="1.0" encoding="UTF-8"?>


<BillingInformation>
<Name> Right Plastic Products </Name>
<BillingDate> 2002-09-15 </BillingDate>
<Address>
<Street> 158 Edward st. </Street>
<City> Brisbane </City>
<State> QLD </State>
<PostalCode> 4000 </PostalCode>
</Address>
</BillingInformation>

XML declaration
The XML processing software uses the declaration to determine how to deal with the subsequent XML content. A
typical XML declaration begins with a prologue that typically contains a declaration of conformity to version 1.0 of
the XML standard and to the UTF-8 encoding standard: <?xml version="1.0" encoding="UTF-8"?>.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

15
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Elements
The topmost element of the XML document is a single element known as the root element.

The content of an element can be character data, other nested elements, or a combination of both.
Elements contained in other elements are referred to as nested elements.

The containing element is the parent element and the nested element is called the child element.

Attributes
Another way of putting data into an XML document is by adding attributes to start tags. Attributes are
used to better specify the content of an element on which they appear by adding information about a
defined element.

An attribute specification is a name–value pair that is associated with an element.

Unlike elements, attributes cannot be nested. They must also always be declared in the start tag of an
element.

URIs and XML namespaces


A Web architecture starts with a uniform syntax for resource identifiers, so that one can refer to
resources, access them, describe them, and share them.

The Uniform Resource Identifier (URI) is the basis for identifying resources in WWW. A URI consists of a
string of characters that uniquely identifies a resource.

The W3C uses the newer and broader term URI to describe network resources rather than the familiar
but narrower term Uniform Resource Locator (URL).

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

16
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
XML allows designers to choose the names of their own tags and as a consequence it is possible that
name clashes (i.e., situations where the same tag name is used in different contexts) occur when two or
more document designers choose the same tag names for their elements.

XML namespaces provide a way to distinguish between elements that use the same local name but are
in fact different, thus avoiding name clashes.

A namespace declaration is indicated by a URI denoting the namespace name. The URI may be mapped
to a prefix that may then be used in front of tag and attribute names, separated by a colon.

In order to reference a namespace, an application developer needs to first declare one by creating a
namespace declaration using the form

An XML example using namespaces

xmlns:<Namespace Prefix> = <someURI>

<?xml version="1.0" encoding="UTF-8"?>


<BillingInformation customer-type="manufacturer"
xmlns="http://www.plastics_supply.com/BillInfo">

XML Schema
An XML Schema describes the structure of an XML document.
The XML Schema language is also referred to as XML Schema Definition (XSD).

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:schema>

Using XSLT to transform documents

To perform document transformation, a document developer usually needs to supply a style sheet,
which is written in XSLT. The style sheet specifies how the XML data will be displayed.

XSLT uses the formatting instructions in the style sheet to perform the transformation. The converted
document can be another XML document or a document in another format, such as HTML, that can be
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

17
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
displayed on a browser. Formatting languages, such as XSLT, can access only the elements of a
document that are defined by the document structure, e.g., XML schema.

SOAP: Simple Object Access Protocol


Web services rely on SOAP, an XML-based communication protocol for exchanging messages between
computers regardless of their operating systems, programming environment, or object model
framework.

SOAP codifies the use of XML as an encoding scheme for request and response parameters using HTTP
as a means for transport.

In particular, a SOAP method is simply an HTTP request and response that complies with the SOAP
encoding rules. A SOAP endpoint is simply an HTTP-based URL that identifies a target for method
invocation.

SOAP provides a wire protocol in that it specifies how service-related messages are structured when
exchanged across the Internet.

SOAP as a wire representation


SOAP makes use of openly available technologies that, when combined, specify a wire protocol. SOAP
commonly uses HTTP to transport XML-encoded serialized method argument data from system to
system. This serialized argument data is used on the remote end to execute a client’s method call on
that system, rather than on a local system.

Wire protocols, such as SOAP, are designed to meet specific design criteria, including [Scribner 2002]
compactness, protocol efficiency, coupling, scalability, and interoperability:

• Compactness refers to how terse a network package becomes while conveying the same
information. Small degree of compactness is usually best.
• Protocol efficiency is directly related to compactness. Efficiency is rated by examining the
overhead required to send the payload. The more overhead required, the less efficient the
protocol is.
• Coupling is the rate at which the client application needs to adapt to changes. Loosely coupled
protocols are quite flexible and can easily adapt to changes, while tightly coupled protocols
require significant modifications to both the server and existing clients.
• Scalability addresses the ability of a protocol to work with a large number of potential
recipients. Some protocols are limited to a few hundreds of clients, while others can easily
handle millions.
• Interoperability refers to the ability of the protocol to work with a variety of computing
platforms. For instance, general-purpose protocols enable clients to send information to a
variety of systems.

SOAP as a messaging protocol

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

18
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

The Web services communication and messaging network

SOAP has a clear purpose: exchanging data over networks. Specifically, it concerns itself with
encapsulating and encoding XML data and defining the rules for transmitting and receiving that data

Structure of a SOAP message


A SOAP message is an ordinary XML document containing the following elements −
• Envelope − Defines the start and the end of the message. It is a mandatory element.
• Header − Contains any optional attributes of the message used in processing the message,
either at an intermediary point or at the ultimate end-point. It is an optional element.
• Body − Contains the XML data comprising the message being sent. It is a mandatory element.
• Fault − An optional Fault element that provides information about errors that occur while
processing the message.

<?xml version = "1.0"?>


<SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://www.w3.org/2001/12/soap-envelope"
SOAP-ENV:encodingStyle = "http://www.w3.org/2001/12/soap-encoding">

<SOAP-ENV:Header>
...
...
</SOAP-ENV:Header>
<SOAP-ENV:Body>
...
...
<SOAP-ENV:Fault>
...
...
</SOAP-ENV:Fault>
...
</SOAP-ENV:Body>
</SOAP_ENV:Envelope>
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

19
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

The SOAP communication model


The Web services communication model describes how to invoke Web services and relies on SOAP. The
SOAP communication model is defined by its communication style and its encoding style. SOAP supports
two possible communication styles:
1. RPC and
2. document (or message).

RPC-style Web service

Document-style Web services

Error handling in SOAP


SOAP provides a model for handling situations when faults arise in the processing of a message. SOAP
distinguishes between the conditions that result in a fault and the ability to signal that fault to the
originator of the faulty message or another node. The SOAP <Body> element has another distinguishing
role in that it is the place where fault information is placed.

The SOAP fault model requires that all SOAP-specific and application-specific faults
be reported using a special-purpose element called env:Fault.

<env:Body>
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

20
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
<env:Fault>
<env:Code>
<env:Value>env:Sender</env:Value>
<env:Subcode>
<env:Value> m:InvalidPurchaseOrder </env:Value>
</env:Subcode>
</env:Code>
<env:Reason>
<env:Text xml:lang="en-UK"> Specified product
did not exist </env:Text>
</env:Reason>
<env:Detail>
<err:myFaultDetails
xmlns:err="http://www.plastics_supply.com/
faults">
<err:message> Product number contains invalid
characters
</err:message>
<err:errorcode> 129 </err:errorcode>
</err:myFaultDetails>
</env:Detail>
</env:Fault>
</env:Body>

SOAP over HTTP


Quite logically, SOAP requests are sent via an HTTP request and SOAP responses are returned within the
content of the HTTP response. While SOAP requests can be sent via an HTTP GET, the specification
includes details on HTTP POST only.

Additionally, both HTTP requests and responses are required to set their content type to text/xml.
The SOAP specification mandates that the client must provide a SOAPAction header, but the actual value
of the SOAPAction header is dependent on the SOAP server implementation.

For example, to access the AltaVista BabelFish Translation service, hosted by XMethods, you must
specify the following as a SOAPAction header.

urn:xmethodsBabelFish#BabelFish

Even if the server does not require a full SOAPAction header, the client must specify an empty string ("")
or a null value. For example −

SOAPAction: ""
SOAPAction:

Here is a sample request sent via HTTP to the XMethods Babelfish Translation service −

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

21
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
POST /perl/soaplite.cgi HTTP/1.0
Host: services.xmethods.com
Content-Type: text/xml; charset = utf-8
Content-Length: 538
SOAPAction: "urn:xmethodsBabelFish#BabelFish"

<?xml version = '1.0' encoding = 'UTF-8'?>


<SOAP-ENV:Envelope
xmlns:SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi = "http://www.w3.org/1999/XMLSchema-instance"
xmlns:xsd = "http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
<ns1:BabelFish
xmlns:ns1 = "urn:xmethodsBabelFish"
SOAP-ENV:encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/">
<translationmode xsi:type = "xsd:string">en_fr</translationmode>
<sourcedata xsi:type = "xsd:string">Hello, world!</sourcedata>
</ns1:BabelFish>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Note the content type and the SOAPAction header. Also note that the BabelFish method requires two
String parameters. The translation mode en_fr translates from English to French.

Here is the response from XMethods

HTTP/1.1 200 OK
Date: Sat, 09 Jun 2001 15:01:55 GMT
Server: Apache/1.3.14 (Unix) tomcat/1.0 PHP/4.0.1pl2
SOAPServer: SOAP::Lite/Perl/0.50
Cache-Control: s-maxage = 60, proxy-revalidate
Content-Length: 539
Content-Type: text/xml

<?xml version = "1.0" encoding = "UTF-8"?>


<SOAP-ENV:Envelope
xmlns:SOAP-ENC = "http://schemas.xmlsoap.org/soap/encoding/"
SOAP-ENV:encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi = "http://www.w3.org/1999/XMLSchema-instance"
xmlns:SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd = "http://www.w3.org/1999/XMLSchema">

<SOAP-ENV:Body>
<namesp1:BabelFishResponse xmlns:namesp1 = "urn:xmethodsBabelFish">
<return xsi:type = "xsd:string">Bonjour, monde!</return>
</namesp1:BabelFishResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

SOAP responses delivered via HTTP are required to follow the same HTTP status codes. For example, a
status code of 200 OK indicates a successful response. A status code of 500 Internal Server Error
indicates that there is a server error and that the SOAP response includes a Fault element.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

22
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Advantages and disadvantages of SOAP


Simplicity: SOAP is simple as it based on XML, which is highly structured and easy to parse.
Portability: SOAP is portable without any dependencies on the underlying platform like byte-ordering
issues or machine-word widths. Today, XML parsers exist for virtually any platform from mainframes to
write-watch-size devices.
Firewall-friendly: Posting data over HTTP means not only that the delivery mechanism is widely
available but also that SOAP is able to get past firewalls that pose problems for other methods.
Use of open standards: SOAP uses the open standard of XML to format the data, which makes it easily
extendable and well supported.
Interoperability: SOAP is built on open, rather than vendor-specific, technologies and facilitates true
distributed interoperability and loosely coupled applications. Because SOAP is a wire protocol based on
XML and HTTP, it is possibly the most widely interoperable protocol to date and can be used to describe
message exchanges between autonomous technical environments and highly diverse enterprise
applications.
Universal acceptance: SOAP is the most widely accepted standard in the message communication
domain.
Resilience to changes: Changes to the SOAP infrastructure will likely not affect applications using the
protocol, unless significant serialization changes are made to the SOAP specification.

Building Web Services with JAX-WS


Java API for XML Web Services (JAX-WS) is a technology for building web services and clients that
communicate using XML. JAX-WS allows developers to write message-oriented as well as Remote
Procedure Call-oriented (RPC-oriented) web services.

In JAX-WS, a web service operation invocation is represented by an XML-based protocol, such as SOAP.
The SOAP specification defines the envelope structure, encoding rules, and conventions for representing
web service invocations and responses. These calls and responses are transmitted as SOAP messages
(XML files) over HTTP.

Although SOAP messages are complex, the JAX-WS API hides this complexity from the application
developer. On the server side, the developer specifies the web service operations by defining methods
in an interface written in the Java programming language. The developer also codes one or more classes
that implement those methods. Client programs are also easy to code. A client creates a proxy (a local
object representing the service) and then simply invokes methods on the proxy. With JAX-WS, the
developer does not generate or parse SOAP messages. It is the JAX-WS runtime system that converts the
API calls and responses to and from SOAP messages.

With JAX-WS, clients and web services have a big advantage: the platform independence of the Java
programming language

Communication between a JAX-WS Web Service and a Client

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

23
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
The starting point for developing a JAX-WS web service is a Java class annotated with
the javax.jws.WebService annotation. The @WebService annotation defines the class as a web service
endpoint.

The basic steps for creating a web service and client are as follows:
1. Code the implementation class.
2. Compile the implementation class.
3. Package the files into a WAR file.
4. Deploy the WAR file. The web service artifacts, which are used to communicate with clients, are
generated by the GlassFish Server during deployment.
5. Code the client class.
6. Use a wsimport Ant task to generate and compile the web service artifacts needed to connect to
the service.
7. Compile the client class.
8. Run the client.

CREATING AND USING WEBSERVICES


1. new project
2. choose java web-->web application
3. give name to project (myfirstwebservice)
4. select server (glassfish or tomcat)
5. click finish
6. right click on project-->new-->web service
7. give name to webservice (sidwebservice) and package (weit.org) "here webservice will have
hello sample method by default"
8. now right click on project and deploy
9. now in project you will able to see web services folder (inside you will able to see sidwebservice)
right click and test websevice
10. now in browser you will able to see wsdl file output with hello button and textbox(copy the wsdl
url)
11. our webservice server is ready dont stop deployment keep it running
12. now we have to create a client or subscriber to consume server
13. preparing client
14. new project
15. choose java web-->web application
16. give name to project (retrivingwebservice)
17. select server (glassfish or tomcat)
18. click finish
19. now right click on project-->new-->webserviceclient
20. now in wsdl url paste (copy the wsdl url)
21. now in web pages create a jsp file (right click on web pages-->add-->jsp)
22. new drag and drop webservice from (web service references) to jsp page

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

24
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

23. now pass a parameter to webservice and print the result as given above
24. now right click on jsp page and run the page.
25. now on browser you will able to see the output which is returned from web service.

Registering and Discovering Web Services


webref:
https://pdfs.semanticscholar.org/presentation/b6e3/41c606a9b155054ac67cb6a16510720797f6.pdf

Service registries
To exploit the full potential of e-business, organizations must be able to discover each other, make their
needs and capabilities known, and compose Web services from diverse organizations into new services
and business processes.

This solution requires the creation of a service registry architecture that enables enterprises to
introduce a global, platform-independent, open framework for businesses to
(i) discover each other,
(ii) define how they interact over the Internet, and
(iii) share information in a global registry that will more rapidly accelerate the global adoption of e-
business.

Service registries are all about visibility and control. At the simplest level, a service registry keeps track
of what services an organization has and characteristics of those services.

two types of e-business registries can be discerned

document-based
A document-based service registry enables its clients to publish information by storing
XML-based service documents, such as business profiles or technical specifications
(including WSDL descriptions of the service), in the registry.

metadata-based

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

25
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Metadata is stored in the service registry and is used by the registry to provide meaningful
attachments to its descriptive documents, which are made persistent in the storage facility of the
service registry.

advanced registry offers several appealing characteristics

• Maximizes Web services reuse and encourages broad usage by all potential users in an SOA
solution.
• Creates a management and governance structure to grow and sustain a successful SOA
implementation.
• Contains all the metadata about Web services and their associated objects. It also contains
information about service providers, consumers, and their relationships.
• Provides general- and special-purpose interfaces that address the needs of providers,
consumers, administrators, and operators.
• Ensures that the evolving SOA can handle the growing number of services and service
consumers and quickly adapt to changing business requirements.

Service discovery

Service discovery is an important element of an SOA(service-oriented architecture)

Service discovery is the process of locating Web service providers, and retrieving Web service
descriptions that have been previously published.

two basic types of service discovery


static
Static service discovery generally occurs at design time
dynamic
dynamic discovery occurs at run-time

UDDI Universal Description, Discovery, and Integration

To address the challenges of service registration and discovery, the Universal Description, Discovery, and
Integration specification was created. UDDI is a cross-industry initiative to create a registry standard for
Web service description and discovery together with a registry facility that supports the publishing and
discovery processes.

UDDI enables a business to


• describe its business and its services
• discover other businesses that offer desired services
• integrate (interoperate) with these other businesses.

The UDDI specifications take advantage of World Wide Web Consortium (W3C) and Internet Engineering
Task Force (IETF) standards such as XML, HTTP, and Domain Name System (DNS) protocols.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

26
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
UDDI is designed for use by developer tools and applications that use Web services standards such as
SOAP/XML and WSDL. UDDI provides a global, platform-independent, open framework.

UDDI is a registry that contains relatively lightweight data. As a registry its prime purpose is to provide
network addresses to the resources it describes.

The core concept of the UDDI initiative is the UDDI business registration, an XML document used to
describe a business entity and its Web services.

Conceptually, the information provided in a UDDI business registration consists of three interrelated
components

• “white pages”, including address, contact, and other key points of contact.
• “yellow pages” , the classification of information according to industrial classifications based on
standard industry taxonomies
• “green pages”, the technical capabilities and information about services that are exposed by the
business including references to specifications for Web services and pointers to various file- and
URL-based discovery mechanisms.

The information that is stored in the UDDI registry allows applications and developers to determine who
the business entity represents, what they do, where the services they provide can be found, and how
they can be accessed.

UDDI data structures


For Web services to be meaningful there is a need to provide information about them beyond the
technical specifications of the service itself.

UDDI – main characteristics

UDDI provides a mechanism to categorize businesses and services using taxonomies.


• Service providers can use a taxonomy to indicate that a service implements a specific domain
standard, or that it provides services to a specific geographic area
• UDDI uses standard taxonomies so that information can be discovered on the basis of
categorization.
UDDI business registration
• an XML document used to describe a business entity and its Web services

UDDI usage model

An enterprise may set up multiple private UDDI registries in-house to support intranet and eBusiness
operations.

Public UDDI registries can be set up by customers and business partners of an enterprise.

Services must be published in a public UDDI registry so that potential clients and service developers can
discover them.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

27
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Queries address the following

• Find Web services implementations that are based on a common abstract interface definition.
• Find Web service providers that are classified according to a known classification scheme or
identifier system.
• Issue a search for services based on a general keyword.
• Determine the security and transport protocols supported by a given Web service.
• Cache the technical information about a Web service and then update that information at run-
time.

Overview of UDDI data structures

The UDDI XML schema defines four core types of information that provide the white/yellow/green page
functions.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

28
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

These are: business entities, business services, binding templates; and information about specifications
for services (technical or tModels)

The UDDI XML schema specifies information about the business entity, e.g., a company, that offers the
service (<businessEntity>), describes the services exposed by the business (<businessService>), and captures
the binding information (<bindingTemplate>) required to use the service.

Service provider information


Partners and potential clients of an enterprise’s services that need to be able to locate information
about the services provided would normally have as a starting point a small set of facts about the service
provider.

The business entity element and business key attribute. The core XML elements for supporting
publishing and discovering information about a business – the UDDI Business Registration – are
contained in an element named <businessEntity>.

The discovery URLs element. This is an optional element and contains the URLs that point to alternate
Web addressable (via HTTP GET) discovery documents.

The name element. The name element contains the common name of the organization that a business
entity represents. A <businessEntity> may contain more than one name.

The description element. This element is a short narrative description for the business. A <businessEntity>
can contain several descriptions, e.g., in different languages.

The contacts element. This element is an optional list of contact information for the organization
The business services element. This is an optional list containing information describing logical families
of the business services that this business entity provides.

The identifier bag element. In addition to the descriptive information the UDDI registry provides
information about enterprises and their services

The category bag element. A <categoryBag> element is similar to the <identifierBag>. This element is a list of
one or more <keyedReference> structures that tag the business entity with specific classification
information, e.g., industry, product, or geographic codes.

Example – Business entity

<businessEntity businessKey="d2300-3aff-.." xmlns = “urn:uddi-org:api_v2”>


<name xml: lang="en"> Automotive Equipment Manufacturing Inc. </name>
<description xml: lang="en">
Automotive Equipment, Accessories and Supplies for European firms
</description>
<contacts>
<contact useType="Sales Contact">

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

29
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
<description xml: lang="en"> Sales Representative </ description>
<personName> Reginald Murphy </personName>
<email useType="primary"> joe.murphy@automeq.com </email>
<address useType="http">
<addressLine> http://www.medeq.com/sales/ </addressLine>
</address>
</contact>
</contacts>
<businessServices>
<!-- Business service information goes here -->
</businessServices>
<identifierBag>
<!-- DUNS Number identifier System -->
<keyedReference keyName="DUNS Number" keyValue="…" tModelKey="…"/>
</identifierBag>
<categoryBag>
<!—North American Industry Classification System (NAICS) -->
<keyedReference keyName="Automotive parts distribution" keyValue="…" tModelKey="…"/>
……
</categoryBag>
</businessEntity>

Business service
The services provided by a business entity are described in business terms using businessService
elements.
A businessEntity can have several businessServices but a businessService belongs to one businessEntity.

A businessService contains:
• a serviceKey that uniquely identifies the service and the businessEntity (not necessarily the
same as where the businessService is found)
• name: as before
• description: as before
• categoryBag: as before
• bindingTemplates: a list to all the bindingTemplates for the service with the technical
information on how to access and use the service.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

30
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

example : business service


<businessServices>
<businessService serviceKey=" ">
<name> Search the Automotive Equipment Manufacturing parts Registry </name>
<description lang="en">
Get to the Automotive Equipment Manufacturing parts Registry
</description>
<bindingTemplates>
<bindingTemplate bindingKey="..">
<description lang="en">
Use your Web Browser to search the parts registry
</description>
<accessPoint URLType="http">
http://www.automeq.com/b2b/actions/search.jsp
</accessPoint>
<tModelInstanceDetails>
<tModelInstanceInfo
tModelKey=”uddi:..”/>
<tModelInstanceDetails>
</bindingTemplate>
</bindingTemplates>
</businessService>
</businessServices>

Binding template: “green pages”


A binding template contains the technical information associated to a particular service:
• bindingKey
• serviceKey
• description
• accessPoint: the network address of the service being provided
• tModels: a list of entries corresponding to tModels associated with this particular binding
• categoryBag: additional information about the service and its binding (e.g., whether it is a test
binding, it is on production, etc).

example bindingtemplate

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

31
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
<bindingTemplate bindingKey="..">
<description lang="en">
Use your Web Browser to search the parts registry
</description>
<accessPoint URLType="http">
http://www.automeq.com/b2b/actions/search.jsp
</accessPoint>
<tModelInstanceDetails>
<tModelInstanceInfo
tModelKey=”uddi:..”/>
<tModelInstanceDetails>
</bindingTemplate>

tModel
A tModel is a generic container of information which contains technical information associated with the
use of a Web service:
• the actual interface and protocol used, including a pointer to the WSDL description;
• description of the business protocol and conversations supported by the service.

example tmodel

<tModel tModelKey="…" >


<name> RosettaNet-Org </name>
<description xml:lang="en">
Supports a process for trading partners to request and
provides quotes
</description >
<overviewDoc>
<description xml:lang="en">
This compressed file contains the specification in a word
document, the html guidelines document, and the XML schemas.
</ description>
<overviewURL>
http://www.rosettanet.org/rosettanet/Doc/0/
K96RPDQA97A1311M0304UQ4J39/3A1_RequestQuote.zip
</overviewURL>
</overviewDoc>
<categoryBag>
<keyedReference keyName="Trading quote request and
provision"
keyValue="80101704" tModelKey=" ….."/>
</categoryBag>
</tModel>

The publisher assertion structure

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

32
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
A <publisherAssertion> structure defines relationships between pairs of <businessEntity> structures. Two (or
more) related enterprises may use the <publisherAssertion> structure to publish assertions of business
relationships, which are mutually acceptable to both parties

example of publisherAssertion

<publisherAssertion>
<fromKey> FE565 … <\fromKey>
<toKey> A237B … <\toKey>
<keyedReference tModelKey="uuid:807A .. " />
keyName="subsidiary"
keyValue="parent-child">
</ keyedReference >
</publisherAssertion>

WSDL to UDDI mapping model

The service desc. in WSDL documents is complementary to the information found in UDDI
business/service entries.

These two constructs work together naturally.


• UDDI and WSDL distinguish clearly between interface and implementation.
• By decoupling a WSDL specification and registering it in UDDI, we can populate UDDI with
standard interfaces that have multiple implementations, providing a landscape of business
applications that share interfaces.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

33
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Mapping WSDL to UDDI

The UDDI API


A UDDI registry offers a standard mechanism to classify, catalogue, and manage Web services, so that
they can be discovered and consumed.

The UDDI API is an interface that accepts XML messages wrapped in SOAP envelopes

• UDDI provides application program interfaces (APIs) for access to a UDDI system:
• UDDI inquiry: to locate and find details about entries in a UDDI registry. Supports a number of
patterns (browsing, drill-down).
• UDDI publication: to publish and modify information in a UDDI registry.
• UDDI security: for access control to the UDDI registry (token based).
• UDDI subscription: for clients to subscribe to changes of information in the UDDI registry.
• UDDI replication: to perform replication of information across nodes in a UDDI registry.
• UDDI custody and ownership transfer: to change the owner (publisher) of information.

All UDDI interactions use a request/response model, in which each message requesting a service from a
UDDI registry generates some kind of response. The UDDI specifications allow two types of exchanges
with UDDI-registered sites: enquiries and publishing.

• The enquiry API is used to search and read data in a UDDI registry, while the
• publishing API is used to add, update, and delete data in a UDDI registry.

Enquiry API
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

34
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Requestors can obtain information from a UDDI registry using its enquiry interface.
Enquiries enable trading organizations to find businesses, services, or technical characteristics meeting
certain criteria.

• Browse functions search the registry based on keywords and return summary lists with overview
information (key, name, and description) about matching businesses or services.
• Find qualifiers are used to sort the results and to control the keyword matching.
o To minimize the number of requests, find queries can be nested.
• Drill-down functions fetch the specific UDDI data structures about particular entries given their
key, returned by the Browse functions.

Publishing API

o The publishing interface can be used by clients to store and update information contained in a
UDDI registry.
o The registry performs access control for all publishing functions: information about the entries
can only be edited by the owner.
o Category information and keyed references associated with the entries are validated before
accepting new information into the registry.
o Save operations allow a client to add or update information in the UDDI.

Querying the UDDI model


The sample queries described in this section are based on the enquiry API and can be issued at
design/build time or at run-time, depending on the type of application being developed.

o Finding business entities by name.


o Finding <businessEntity> entries by category.
o Finding the <tModel> for <portType> name.
o Find all <binding tModel> for PurchaseOrderPortType.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

35
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

UDDI usage model and deployment variants


Business information provider roles
Registry operators:
o organizations (operator nodes) that host and operate the UDDI business registry (UBR).
o These manage and maintain the directory information, cater for replication of business
info. and other directory-related functions.
o The registry works on a “register once, published everywhere” principle.

Standard bodies and industry consortia:


• these publish descriptions in the form of service type definitions (s).
o These s do not contain the actual service definitions, instead they have a URL that points
to the location where the service descriptions (usually in WSDL) are stored.

Service providers:
• commonly implement Web services conforming to service type definitions supported by UDDI.
o They publish information about their business and services in the UDDI.
o The published data also contains the end point of Web services

UDDI deployment possibilities


o e-marketplace UDDI: an e-marketplace, a standards body, or a consortium of organizations that
participate and compete in the industry can host this private UDDI node
o Business partner UDDI registry: a private UDDI node hosted behind one of the business
partner’s firewall and only trusted or vetted partners can access the registry
o Portal UDDI: this type of deployment is on an enterprise’s firewall and is a private UDDI node
that contains only meta-data related to the enterprise’s Web services.
o Internal UDDI: this allows applications in different departments of the organization to publish
and find services, and is useful for large organizations.

Service-oriented architectures
The challenges in automated business integration have fueled new approaches and architectures to
address the requirements of loosely coupled, standards-based, and protocol-independent distributed
computing applications culminating in the introduction of the service-oriented architecture.

What is a software architecture


Building distributed software systems involves fitting together resources and systems from diverse
organizations as well as developing implementation code

Software architecture of a computing system involves the description of the structures from which
systems are built (software components), the externally visible properties of those components, their
interrelationships as well as principles and guidelines governing their design and evolution over time.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

36
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
software architecture is the high-level structure of a software system –including distributed and service-
oriented systems – that is commonly specified in terms of functional components and
interactions/interconnections among those components. Components are identified and assigned
responsibilities that client components interact
with through “contracted” interfaces.

Important properties of software architecture include

o It is at a high-enough level of abstraction that the system can be viewed as a whole and yet it
must provide enough information to form a basis for analysis, decision making, and hence risk
reduction
o The structure must support the functionality required of the system. Thus, the dynamic
behavior of the system must be taken into account when designing the architecture.
o It must conform to the system qualities (captured in SLAs or non-functional requirements).
These likely include performance, security, interoperability, and reliability

System quality attributes


While the design of software systems concentrates on satisfying the functional requirements for a
system, the design of the software architecture for systems concentrates on the non-functional or
quality requirements of systems.

Quality requirements of systems are described in terms of quality attributes, which are those system
properties over and above the functionality of the system that determine the technical qualities of the
system.

There are two types of quality attributes

o Run-time qualities provide value to the user and have more to do with short-term competitive
differentiation
o Development-time qualities, for the most part, provide business value (as opposed to direct
value to the end user) and have to do with the long-term competitiveness of the business.

Common architectural concerns


• Meta-architecture: This is a set of architectural vision, style, principles, key communication and
control mechanisms, and concepts that results in high-level decisions that will strongly influence
the integrity and structure of the system.
• Architectural patterns: Over time, software developers distinguish patterns in the way that
systems are structured, and as these patterns become widespread they become dominant
designs. Patterns allow the architect to start with a problem and a vision for the solution, and
then find a pattern that fits that vision.
• Architectural views: Software architectures are best envisioned in terms of a number of
complementary views or models.
• System decomposition principles and good interface design: These identify the high-level
components of the system and the relationships among them. Their purpose is to direct
attention at an appropriate decomposition of the system without delving into unnecessary
details.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

37
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• Key architectural design principles: These include abstraction, separation of concerns,
postponing decisions, and simplicity, and related techniques such as interface hiding and
encapsulation.

SOA revisited
SOA is a meta-architectural style that supports loosely coupled services to enable business flexibility in
an interoperable, technologyagnostic manner.
In SOA, business-aligned services are used as the basis for constructing flexible and dynamically
reconfigurable end-to-end business processes.
SOA is focused on creating a design style, technology, and process framework that will allow enterprises
to develop, interconnect, and maintain enterprise applications and services efficiently and cost-
effectively.

Services in an SOA exhibit the following characteristics

• All functions in an SOA are defined as services


• All services are independent of each other
• Service interfaces are invokable

SOA’s loose-coupling principles


• guide planning,
• development,
• integration, and
• management of their network application

Service roles in an SOA


SOAs and Web services solutions include two well-known key roles:
• a service requestor (client) and
o Service Consumers make a request for a service in the SOA registry. Universal
Description, Discovery and Integration (UDDI) standard is used for locating a service in
the registry.
• service provider
• Service Producers register their service in the SOA registry. Web Services Description
Language (WSDL) is used to describe a service.

Reliable messaging
Unfortunately, the core SOAP specification does not provide reliability mechanisms addressing such
complex message routing requirements. Therefore, there is a clear need for more robust SOAP-based
messaging specifications to guarantee that messages are being received by their intended recipients and
that message addressing remains consistent despite the fact that messages might be routed to Web
services implemented on different platforms

Definition and scope of reliable messaging

Reliability at the level of messages is often referred to as reliable messaging

When specifying reliable messaging features there are three aspects that must be addressed equally

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

38
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

• both the sender and recipient of a message know whether or not a message was actually sent
and received, and that the message received is the same as the one sent.
• we need to make sure that the message was sent once and only once to the intended recipient
• we need to guarantee that the received messages are in the same order as they were sent

WS-ReliableMessaging

WS-ReliableMessaging provides a protocol for ensuring that unreceived and duplicate SOAP messages
can be detected and received messages can be processed in the order in which they were sent.
The WS-ReliableMessaging protocol depends upon other Web services specifications for the
identification of service endpoint addresses and policies.

The WS-ReliableMessaging standard has been developed to provide a framework for interoperability
between different reliable transport infrastructures

WS-ReliableMessaging protocol determines invariants maintained by the reliable messaging endpoints


and the directives used to track and manage the delivery of a sequence of messages.

WS-ReliableMessaging provides an interoperable protocol that a reliable messaging source and reliable
messaging destination use to provide the application source and the application destination with a
guarantee that a message that is sent will be delivered.

WS-ReliableMessaging distinguishes two important traits:


1. The reliability protocol between message handlers(sequence is maintained)
2. The reliability QoS contract(assured delivery)

There are four basic delivery assurances that endpoints provide and are supported by WS-
ReliableMessaging

• AtLeastOnce Delivery: This feature guarantees that every message sent will be delivered or an
error will be raised on at least one endpoint. Some messages may be delivered more than once.
• AtMostOnce Delivery: This feature guarantees that every message will be delivered at most
once without duplication or an error will be raised on at least one endpoint. It is possible that
some messages in a sequence may not be delivered.
• ExactlyOnce Delivery: This feature guarantees that every message sent will be delivered
without duplication or an error will be raised on at least one endpoint. This delivery assurance is
the logical AND of the two prior delivery assurances.
• InOrder Delivery: This feature enforces the delivery of a sequence of messages at the
destination, in the same order as the submission order by the sending application. This delivery
assurance says nothing about duplications or omissions.

Structure of WS-ReliableMessaging
• Sequences: The protocol uses the <Sequence> element to identify and track a group of messages
• Message numbers: This numbering scheme makes it simple to detect missing or duplicate
messages, and simplifies acknowledgement generation and processing.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

39
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• Acknowledgements: An acknowledgement is an indication that a message was successfully
transferred to its destination.

Enterprise Service Bus


The Enterprise Service Bus is an open standards-based message backbone designed to enable the
implementation, deployment, and management of SOA-based solutions with a focus on assembling,
deploying, and managing distributed service-oriented architectures.

An ESB is a set of infrastructure capabilities implemented by middleware technology that enable an SOA
and alleviate disparity problems between applications running on heterogeneous platforms and using
diverse data formats. The ESB supports service invocations, message, and event-based interactions with
appropriate service levels and manageability.

ESB distributed processing infrastructure is aware of applications and services and uses content-based
routing facilities to make informed decisions about how to communicate with them.

ESB connecting diverse applications and technologies

To successfully build and deploy a distributed SOA, there are five design/deployment and management
aspects that need to be addressed first:

• Service analysis and design: A service development methodology should be used to enable
service-oriented development and the reuse of existing applications and resources.
• Service enablement: The service development methodology should determine which discrete
application elements need to be exposed as services.
• Service orchestration: Distributed services need to be configured and orchestrated in a unified
and clearly defined distributed process.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

40
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• Service deployment: Emphasis should also be placed on the production environment that
addresses security, reliability, and scalability concerns.
• Service management: Services must be audited, maintained, and reconfigured and
corresponding changes in processes must be made without rewriting the services or underlying
application.

Key capabilities of an ESB

Dynamic connectivity capabilities: Dynamic connectivity is the ability to connect to Web services
dynamically without using a separate static API or proxy for each service.
Reliable messaging capabilities: Reliable messaging can be primarily used to ensure guaranteed
delivery of these messages to their destination and for handling events.
Topic- and content-based routing capabilities: The ESB should be equipped with routing mechanisms to
facilitate not only topic-based routing, but also more sophisticated content-based routing.
Transformation capabilities: A critical ability of the ESB is the ability to route service interactions
through a variety of transport protocols, and to transform from one protocol to another where
necessary.
Service enablement capabilities: Service enablement includes the ability to access already existing
resources such as legacy systems
Security capabilities: Generically handling and enforcing security is a key success factor for ESB
implementations. The ESB needs both to provide a security model to service consumers and to integrate
with the (potentially varied) security models of service providers.
Integration capabilities: To support SOA in a heterogeneous environment, the ESB needs to integrate
with a variety of systems that do not directly support service-style interactions.

ESB integration styles

Integration at the presentation tier. Integration at the presentation tier is concerned with how the
complete set of applications and services a given user accesses. ESB can provide one face to the users
resulting in consistent user experience, with unified information delivery while allowing underlying
applications to remain distributed.

Application connectivity. Application connectivity is an integration style concerned with all types of
connectivity that the ESB integration layer must support.

Application connectivity has to deal with the following types of integration:

1. Application integration: Application integration is concerned with building and evolving an


integration backbone capability that enables fast assembly and disassembly of various platform
and component technologies.
2. Business process integration: Process integration is concerned with the development of
automated processes that map to and provide solutions for business processes, integration of
existing applications into processes, and integrating processes with other processes.
3. Business data integration: Data integration is the process of providing consistent access to
business data in the enterprise, by all the applications that require it, in whatever form they
need it, without being restricted by the format, source, or location of the data.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

41
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
4. Integration design and development methodology: One of the requirements for the application
development environment must be that it takes into account all the styles and levels of
integration that could be implemented within the enterprise, and provides for their
development and deployment.

Integration brokers
To integrate disparate business applications one must concentrate on the characteristics and functions
of integration brokers.

Application servers
Another critical middleware infrastructure used in connection with ESBs is application servers.
Application servers offer an integrated development environment for developing and deploying
distributed Web- and non-Web-based applications and services.

Application servers typically provide Web connectivity for extending existing solutions and bring
transaction processing mechanisms to the Web.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

42
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Connectivity and translation infrastructure

There are three alternative ways an application can exchange information with the ESB include

• Application-provided Web services interface: Some applications and legacy application servers
have adopted the open standards philosophy and have included a Web services interface.
• Service wrapper as interface to adapter: In some cases the adapter may not supply the correct
protocol (JMS, for example) that the ESB expects. In this case, the adapter would be Web
services enabled.

Leveraging legacy assets

Legacy applications are critical assets of any modern enterprise as they provide access to mission-critical
business information and functionality and thus control the majority of an organization’s business
processes.

The primary focus of legacy re-engineering and transformation is enterprises, business processes, the
EAI, and how a legacy system can contribute to implementing the architecture without propagating the
weaknesses of past designs and development methods.
most fundamental form the process of re-engineering includes three basic tenets
• understanding of an existing application, resulting in one or more logical descriptions of the
application
• restructuring or transformation of those logical descriptions into new, improved logical
descriptions;
• development of the new application based on these improved logical descriptions

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

43
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Scalability issues in an ESB


For example, parallel execution of business operations and itinerary-based routing significantly
contribute to the highly distributed nature of the ESB, as there is no centralized rules engine to refer
back to for each step in the process. The use of asynchronous communications, message itineraries,
message and process definitions allow different parts of the ESB to operate independently of one
another.

This results in a decentralized model providing complete flexibility in scaling any aspect of the
integration network. Such a decentralized architecture enables independent scalability of individual
services as well as the communications infrastructure itself.

Integration patterns using an ESB


integration service can manage stateful information about a business process that spans a considerable
length of time. For example, a step in the business process may require human interaction, such as
approval of a purchase order or of a new supplier.
A business process integration pattern is the preferred solution for most ESB applications because it
offers many advantages. Its single drawback is dealing with sometimes excess process complexity.

The extended SOA


Extended SOA consists of two SOA implementations: internal and external.

Extended SOA implementation, can recognize the following services

• Foreign Services
o They represent services served by other systems of the external SOA. These services
communicate with the middleware only and they are out of scope of our
implementation.
• Middleware
o It acts as a service consumer part of external SOA implementation. The middleware is
responsible for communication between all foreign services and our External
Application Services and it is out of scope of our implementation.
• External Application Services
o They act as service providers for the middleware and as service consumers for Internal
Application Services. These services combine and connect both SOA implementations.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

44
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• Internal Application Services
o They serve core functionality of the application acting as service providers for External
Application Services and as service consumers for Basic Application Services.
• Basic Application Services
o They serve basic functionality of the application simplifying the build process of Internal
Application Services (Add, Update, Delete, etc.). They act as service providers for
Internal Application Services.

Web services development lifecycle

System development lifecycle


System development lifecycle (SDLC) is the overall process of designing and developing software
systems through a multi-step process from investigation of initial requirements through analysis, design,
implementation, and maintenance.

The simplest rendition of system development projects is the “waterfall” methodology. This
methodology usually has five identifiable phases:
analysis, design, implementation, testing, and maintenance.

A more recent software development process is the rational unified process (RUP) whose aim is to
support the analysis and design of iterative software development.

Architecture of RUP

Basic SOA model is divided into six major layers of abstraction:


domains, business processes, business services, infrastructure services, service realizations, and
operational systems.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

45
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Service-oriented design and development milestones


• Reusing existing functionality: Service-oriented solutions target reuse of existing functionality
and assets such as prepackaged application suites, specialpurpose built components,
commercial off-the-shelf (COTS) applications or legacy applications, within new applications and
policy-based computing.
• Minimizing costs of disruption: The adoption of specific “integration logic” functionality that
enables orchestration of existing, working technology in the form of services results in
minimizing the costs associated.
• Employing an incremental mode of integration: One of the key benefits of the serviceoriented
approach is that integration can be delivered on a gradual, requirements driven basis, but yet
still amount to a cohesive whole in the long term.
• Providing increased flexibility: Service-oriented solutions provide the ability to quickly and
easily evolve and adapt applications in order to meet changing business requirements and new
technologies.
• Providing scalability: making it potentially possible to process large applications more quickly
by spreading the load of processing across many servers.

Quality of service-oriented design and development

Service coupling
One way of measuring service design quality is coupling, or the degree of interdependence
between two business processes.

The objective is to minimize coupling: that is, to make (self-contained) business processes as
independent as possible by not having any knowledge of or relying on any other business
processes.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

46
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Coupling can be achieved by reducing the number of connections between services in a business
process, eliminating unnecessary relationships between them, and by reducing the number of
necessary relationships – if possible.

coupling partitioned along the following dimensions:

• Representational coupling: Business processes should not depend on specific


representational or implementation details ,Representational coupling is useful for
supporting.
o Interchangeable/replaceable services : Existing services may be swapped with
new service implementations
o Multiple service versions : Different versions of a service may work best in parts
of a business processes depending on the application’s needs.
• Identity coupling: Connection channels between services should be unaware of who is
providing the service.
• Communication protocol coupling: A sender of a message should rely only on those
effects necessary to achieve effective communication.

Service cohesion
Cohesion is the degree of the strength of functional relatedness of operations within a service.

• Functional service cohesion: A functionally cohesive business process should perform one
and only one problem-related task and contain only services necessary for that purpose.
• Communicational service cohesion: A communicationally cohesive business process is one
whose activities and services use the same input and output messages.
• Logical service cohesion: tasks of the same general category by performing a set of
independent but logically similar functions

Service granularity
Service granularity refers to the scope of functionality exposed by a service. Services may exhibit
different levels of granularity.

Functionality associated with the chosen business entity belongs within the service's functional
boundary. The larger the quantity of related functionality, the coarser the service granularity.
Conversely, services with more narrow or targeted functional contexts will tend to have a finer
grained level of service granularity.

level of service granularity is set by the service's functional context, not by the actual amount of
functionality that resides within the physically implemented service.

Overview of Web services development lifecycle

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

47
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Phases of the service-oriented design and development methodology

planning phase
The planning phase constitutes a preparatory phase that serves to streamline and organize consequent
phases in the methodology. During this phase, the project feasibility, goals, rules, and procedures are set
and requirements are gathered.

analysis phase
reviewing the business goals and objectives of an enterprise that drive the development of business processes.

• “As-is” process model analysis

“as-is” process model to allow the various stakeholders to understand the portfolio of available
applications and business processes.
o Portfolio analysis: assigning candidates and prioritized according to their technical quality
and business value.
o Cost estimation: estimate the cost of the re-engineering project
o Cost–benefit analysis: cost of re-engineering is compared to the expected maintenance cost
savings and value increases
• Business service identification
o Understanding how a business process works and how component functionality differs or can
get adjusted between applications is an important milestone when trying to identify suitable
business process candidates.
• Business service scoping
o Defining the scope of business processes helps ensure that a process does not become
monolithic and mimic an entire application.
• Business service gap analysis

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

48
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
o A gap analysis strategy may be developed in stages and results in a recommendation to do
development work, reuse, or purchase Web services.
• Business service realization analysis
o describes at a high level how a Web service usage interface could be connected to a portfolio
of existing services and service-enabled applications which are assembled to form service
orchestration specification interfaces.

The service design phase


This phase is logically succeeded by service design, during which conceptual processes and services
are transformed from abstract entities into a set of concrete service interfaces.

Service design concerns


concerns include managing service granularity, designing for service reuse, and designing for service
composability.
• Managing service and component granularity
Services analysis provides an initial granularity assessment based on the top-down logical
analysis of services functionality and scope, which can be used as a starting point for
designing concrete service interfaces.
• Designing for service reusability
designing services it is important to be able to design them for reuse so that they can
perform a given function wherever this function is required within an enterprise
• Designing for service composability
principles that guarantee that services are self-contained, modular, and support service
composability

Specifying services
• A structural specification: This focuses on defining the service types, messages, port types, and
operations.
• A behavioral specification: This entails understanding the effects and side effects of service operations
and the semantics of input and output messages.
• A policy specification: In addition to service syntax and semantics, QoS considerations must also be
addressed.

Specifying business processes

Describing the business process structure


The business process structure refers to the logical flow or progression of a business process
process encompasses the following tasks:
1. Identify, group, and describe the activities and services that together implement a
business process
2. Describe activity dependencies, conditions, or synchronization
3. Describe the implementation of the business process

Describing business roles


identify responsibilities associated with business process activities and the roles that are
responsible for performing them

Specifying service policies


WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

49
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Business constraints, Technology constraints, Run-time qualities

The service construction phase

Constructing a service: the provider perspective


1. There is an already existing implementation (service content) for the Web service, e.g., in
Java code. By using this implementation the developer can build the service definition
(WSDL document).
2. A service definition already exists in the form of a WSDL document. By using this WSDL
document the designer can build or adapt the implementation (Java) code to realize that
service.

Constructing services: the client perspective


1. A static client is created at construction time by locating the service implementation
definition for the single Web service that will be used by the service requestor.
2. A dynamic client is used when a service requestor wants to use a specific type of Web
service with a known service definition whose implementation is not known until run-time
or can change at run-time.

The service test phase


Service testing is generally characterized as a validation exercise at the physical level, ascertaining
that requirements have been met and that the deliverables are at an acceptable level and in
accordance with existing standards during the analysis, design, and construction phases of the
services lifecycle.

• Functional testing covers how well the service executes the functions it is expected to
execute
• performance testing in service-oriented environments is monitoring service on-line response
times and transaction rates under peak workload conditions
• interface testing is to ensure that any service is developed to properly interface with other
service functions outside of its surrounding process.
• assembly testing ensures that all services function properly when assembled into business
processes.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

50
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Service provisioning phase

Service governance
Enterprises that progress towards SOA development wish to ensure continuity of their business
operations, manage their security exposure, align technology implementation with business
requirements, manage liabilities and dependencies, and, in general, reduce the cost of
operations.

• IT governance is a formalization of the structured relationships, procedures, and policies


that ensure the IT functions in an organization support and are aligned to business
functions.
• SOA governance is an extension of IT governance and guiding principles which focus on
the lifecycle of services and is designed to enable enterprises to maximize business
benefits of SOA such as increased process flexibility, improved responsiveness, and
reduced IT maintenance costs.

Two different governance models are possible

Central governance: With central governance, the governing body within an enterprise has
representation from each business domain as well as from independent parties that do not have
direct responsibility for any of the service domains.

Federated governance: With federated governance each business unit has autonomous control
over how it provides the services within its own enterprise.

Service certification
This ensures that application developers work with “known quantities.” To establish that a
service possesses some desired property we need to use knowledge to predict the overall
properties that an assembled application may attain.

Service metering and rating


• Service metering model: Use of a service by a client must be metered if the service
provider requires usage-based billing.
• Service rating/billing model: Software organizations that are used to the traditional up-
front license/ongoing maintenance pricing structure for software should come up with
annuity-based pricing models for the Web services they provide.

The service deployment phase


1. Publish the service interface: Service providers publish their Web service definition in a service
registry, such as UDDI, so that service requestors can use it to determine how to bind to the
service.
2. Deploy the Web service: The run-time code for the service and any deployment metadata that is
required to run it are deployed during this step.
3. Create the service implementation definition: Service providers provide a service content
implementation definition based on how and where the service was deployed.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

51
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
4. Publish the service implementation definition: The service implementation definition contains
the definition of the network-accessible endpoint or endpoints where the Web service can be
invoked.

service execution phase


The service execution phase in the SDLC methodology deals with the execution of Web services.
This phase includes the actual binding and run-time invocation of the deployed services as well
as managing and monitoring their lifecycle.

service monitoring phase


The service monitoring phase concerns itself with service-level measurement; monitoring is the
continuous and closed loop procedure of measuring, monitoring, reporting, and improving the
QoS of systems and applications delivered by service-oriented solutions.

Unit 2 : The REST Architectural style


Introducing HTTP

Hypertext Transfer Protocol (HTTP) is the foundation of data communication for WWW. This protocol
defines how messages are formatted, transmitted, and processed over the Internet.

1. HTTP/0.9 is very primitive and supported only the GET method


2. HTTP/1.0 supported more request methods such as GET, HEAD, and POST.
3. HTTP/2 (originally named HTTP 2.0) is the next planned version. It is mainly focused on how the
data is framed and transported between the client and the server.

Understanding the HTTP request-response model

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

52
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
The user enters the following URL in the browser, http://www.example.com/index.html, and
then submits the request.

The browser establishes a connection with the server and sends a request to the server in the form of a
request method, URI, and protocol version, followed by a message containing request modifiers, client
information, and possible body content.

Uniform resource identifier

URI is a text that identifies any resource or name on the Internet. One can further classify a URI as a
Uniform Resource Locator (URL) if the text used for identifying the resource also holds the means for
accessing the resource such as HTTP or FTP

Understanding the HTTP request methods

The set of common methods for HTTP/1.1

Method Description
GET This method is used for retrieving resources from the server by using the given URI.
HEAD This method is the same as the GET request, but it only transfers the status line and the
header section without the response body.
POST This method is used for posting data to the server. The server stores the data (entity) as a
new subordinate of the resource identified by the URI. If you execute POST multiple times
on a resource, it may yield different results.
PUT This method is used for updating the resource pointed at by the URI. If the URI does not
point to an existing resource, the server can create the resource with that URI.
DELETE This method deletes the resource pointed at by the URI.
TRACE This method is used for echoing the contents of the received request. This is useful for
the debugging purpose with which the client can see what changes (if any) have been
made by the intermediate servers.
OPTIONS This method returns the HTTP methods that the server supports for the specified URI.
CONNECT This method is used for establishing a connection to the target server over HTTP.
PATCH This method is used for applying partial modifications to a resource identified by the URI.

Representing content types using HTTP header fields

Content-Type header in an HTTP request or response describes the content type for the message body.
The Accept header in the request tells the server the content types that the client is expecting in the
response body.

The Internet media types are broadly classified in to the following categories on the basis of the
primary (or initial) Content-Type header:

• text: This type indicates that the content is plain text and no special software is required to read
the contents.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

53
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• Content-Type: multipart/form-data is used for submitting forms that contain the files, non-ASCII
data, and binary data.
• the Content-Type: message/partial content type allows for large messages to be broken up into
smaller messages.
• Content-Type: image/png indicates that the body content is a .png image
• Content-Type: audio/mpeg indicates that the body content is MP3 or other MPEG audio.
• Content- Type: application/json; charset=utf-8 designates the content to be in the JavaScript
Object Notation (JSON) format

HTTP status codes

Status-Code element in a server response, is a 3-digit integer where the first digit of the Status-Code
defines the class of response and the last two digits do not have any categorization role

S.N. Code and Description


1 1xx: Informational
It means the request has been received and the process is continuing.
Message Description
100 Continue Only a part of the request has been received by the server, but as long as it
has not been rejected, the client should continue with the request.
101 Switching The server switches protocol.
Protocols
2 2xx: Success
It means the action was successfully received, understood, and accepted.
Message Description
200 OK The request is OK.
201 Created The request is complete, and a new resource is created .
202 Accepted The request is accepted for processing, but the processing is not
complete.
203 Non- The information in the entity header is from a local or third-party copy,
authoritative not from the original server.
Information
204 No Content A status code and a header are given in the response, but there is no
entity-body in the reply.
205 Reset Content The browser should clear the form used for this transaction for additional
input.
206 Partial Content The server is returning partial data of the size requested. Used in
response to a request specifying a Range header. The server must specify
the range included in the response with the Content-Rangeheader.
3 3xx: Redirection
It means further action must be taken in order to complete the request.
Message Description
300 Multiple A link list. The user can select a link and go to that location. Maximum five
Choices addresses .
301 Moved The requested page has moved to a new url .
Permanently
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

54
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
302 Found The requested page has moved temporarily to a new url .
303 See Other The requested page can be found under a different url .
304 Not Modified This is the response code to an If-Modified-Since or If-None-Matchheader,
where the URL has not been modified since the specified date.
305 Use Proxy The requested URL must be accessed through the proxy mentioned in
the Location header.
306 Unused This code was used in a previous version. It is no longer used, but the code
is reserved.
307 Temporary The requested page has moved temporarily to a new url.
Redirect
4 4xx: Client Error
It means the request contains incorrect syntax or cannot be fulfilled.
Message Description
400 Bad Request The server did not understand the request.
401 Unauthorized The requested page needs a username and a password.
402 Payment Required You can not use this code yet.
403 Forbidden Access is forbidden to the requested page.
404 Not Found The server can not find the requested page.
405 Method Not Allowed The method specified in the request is not allowed.
406 Not Acceptable The server can only generate a response that is not accepted
by the client.
407 Proxy Authentication You must authenticate with a proxy server before this request
Required can be served.
408 Request Timeout The request took longer than the server was prepared to wait.
5 5xx: Server Error
It means the server failed to fulfill an apparently valid request.
Message Description
500 Internal Server Error The request was not completed. The server met an unexpected
condition.
501 Not Implemented The request was not completed. The server did not support the
functionality required.
502 Bad Gateway The request was not completed. The server received an invalid
response from the upstream server.
503 Service Unavailable The request was not completed. The server is temporarily
overloading or down.
504 Gateway Timeout The gateway has timed out.
505 HTTP Version Not
Supported

core architectural elements of a RESTful system

generic interface to manage all interactions between a client and a server in a unified way

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

55
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
All resources (or business data) involved in the client-server interactions are dealt with by a fixed set of
operations.

Core elements that form a uniform interface for a RESTful system

• Resources and their identifiers


o RESTful resource is anything that is addressable over the Web. By addressable, we mean
resources that can be accessed and transferred between clients and servers.
o URI is a string of characters used to identify a resource over the Web
o RESTful system, the URI is not meant to change over time as it may break the contract
between a client and a server
• Representations of resources
o representation of resources is what is sent back and forth between clients and servers in
a RESTful system.
o A representation is a temporal state of the actual data located in some storage device at
the time of a request
• Generic interaction semantics for the REST resources
In a RESTful web service, resources are exchanged between the client and the server,
which represent the business entities or data.
HTTP specifies methods or actions for the resources. The most commonly used HTTP
methods or actions are POST, GET, PUT, and DELETE.

Data action HTTP equivalent


CREATE POST or PUT
READ GET
UPDATE PUT or PATCH
DELETE DELETE

HTTP GET method


o in request
o method, GET, is used to retrieve resources
o in response:
o {"departmentId":10,"departmentName":"IT","manager":"John Chen"}

HTTP POST method


o in request
o {"departmentName":"Sales","manager":"Tony Greig"}
o in response
o server sends 201 Created

HTTP PUT method


o PUT method is used to update resources.
o in request
o {"departmentId":40,"departmentName":"Sales","manager":"Tony Greig" }
o in response

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

56
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
o 204 No Content response code indicates that the server has fulfilled the request
but does not return the entity body

HTTP DELETE method


o DELETE method is used to delete the resource.
o we will delete a resource by making use of the same URI that we used
o Assume that we want to delete the Sales department from the data storage.
o in request
o http://www.packtpub.com/resources/departments/Sales.
o in resonse
o 204 No Content response code indicates that the
o server has fulfilled the request but does not return the entity body.
• Self-descriptive messages
• Hypermedia as the engine of an application state
o The principle is that the model of application changes from one state to another by
traversing the hyperlinks present in the current set of resource representations (the model).
o In a RESTful system, there is no fixed interface between the client and the server as you may
see in a conventional client-server communication model such as Common Object Request
Broker Architecture (CORBA) and Java Remote Method Invocation (Java RMI).
o With REST, the client just needs to know how to deal with the hypermedia links present in
the response body; next, the call to retrieve the appropriate resource representation is
made by using these dynamic media links.
o example

request:
http://www.packtpub.com/resources/departments/IT
response:
{"departmentId":10,
"departmentName":"IT",
"manager":"John Chen,
"links": [ {
"rel": "employees",
"href": "http://packtpub.com/resources/departments/IT/employees"
} ]"}
response:
[{"employeeId":100,
"firstName":"Steven",
"lastName":"King",
"links": [ {
"rel": "self",
"href": "http://www.packtpub.com/resources/employees/100"
}]
},
{"employeeId":101,
"firstName":"Neena",
"lastName":"Kochhar",
"links": [ {
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

57
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
"rel": "self",
"href": "http://www.packtpub.com/resources/employees/101"
}]
}]

Description and discovery of RESTful web services

WSDL is used for describing the functionality offered by a SOAP web service. For a SOAP web service,
this is a widely accepted standard and is supported by many enterprises today.

for RESTful web services, there is no such standard and you may find different metadata formats used
by various enterprises.

in general, you may see the following goals in common among all these metadata formats for RESTful
APIs, although they differ in their syntax and semantics.

o Entry points for the service


o Resource paths for accessing each resource
o HTTP methods allowed to access these resources, such as GET, POST, PUT, and DELETE
o Additional parameters that need to be supplied with these methods, such as pagination
parameters, while reading large collections
o Format types used for representing the request and response body contents such as JSON, XML,
o and TEXT
o Status codes and error messages returned by the APIs
o Human readable documentation for REST APIs, which includes the documentation of the
request methods, input and output parameters, response codes (success or error), API security,
and business logic

popular metadata formats used for describing REST APIs are Web Application Description Language
(WADL), Swagger, RESTful API Modeling Language (RAML), API Blueprint, and WSDL 2.0.

Java tools and frameworks for building RESTful web services

the REST architectural style has become very popular in the industry and many enterprises have
accepted it as the current standard for building public web APIs, particularly when scalability and
simplicity are major concerns for them.

The Java API for RESTful web services (JAX-RS) is the Java API for creating RESTful web services following
the REST architectural pattern

JAX-RS is a part of the Java Platform Enterprise Edition (Java EE) platform and is designed to be a
standard and portable solution.

(not based on JAX-RS) Java REST frameworks on the market. Some such frameworks are as follows:
• One such framework is RESTX, which is an open source Java REST framework and is primarily
focused on the server-side REST API development. This is relatively new on the market and
simplifies the REST API development.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

58
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• Spark is another framework that falls into this category. It is a Java web framework with support
for building REST APIs. Spark 2.0 is built using Java 8, leveraging all the latest improvements of
the Java language.
• Play is another framework worth mentioning in this category. It is a Java (and Scala)-based web
application framework with inherent support for building RESTful web services.

JSON message format and tools and frameworks around JSON

JSON data syntax

JSON format is represented by the following two data structures


1. An unordered collection of name-value pairs (representing an object):
• The attributes of an object and their values are represented in the name-value pair format
o the name and the value in a pair is separated by a colon (:)
o Names in an object are strings, and values may be of any of the valid JSON data
types such as number, string, Boolean, array, object, or null.
o Each name:value pair in a JSON object is separated by a comma (,).
o The entire object is enclosed in curly braces ({ }).

eg: {"departmentId":10, "departmentName":"IT", "manager":"John Chen"}

2. An ordered collection of values (representing an array):


• Arrays are enclosed in square brackets ([ ]),
• and their values are separated by a comma (,).

eg:
{"departmentName":"IT",
"employees":[
{"firstName":"John", "lastName":"Chen"},
{"firstName":"Ameya", "lastName":"Job"},
{"firstName":"Pat", "lastName":"Fay"}
],
"location":["New York", "New Delhi"]
}

Basic data types available with JSON

1. Number: {"totalWeight": 123.456}


2. String: {"firstName": "Jobinesh"}
3. Boolean: {"isValidEntry": true}
4. Array: {"fruits": ["apple", "banana", "orange"]}
5. Object: {"departmentId":10, "departmentName":"IT", "manager":"John Chen"}
6. null: {"error":null}

Processing JSON data

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

59
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
If you use Java RESTful web service frameworks, such as JAX-RS, for building RESTful web APIs, the
serialization and deserialization of the request and response messages will be taken care of by the
framework.

the role of the JSON marshalling and unmarshalling components in a typical Java RESTful web service
implementation

Two widely adopted programming models for processing JSON are as follows:

Object model:
• In this model, the entire JSON data is read into memory in a tree format.
• This tree can be traversed, analyzed, or modified with the appropriate APIs. As this approach
loads the entire content into the memory first and then starts parsing, it ends up consuming
more memory and CPU cycles.
• However, this model gives more flexibility while manipulating the content.

Streaming model:
• The term streaming is very generic in meaning and can be used in many aspects.
• This model does not read the entire JSON content into the memory to get started with parsing;
rather, it reads one element at a time.

Tools and frameworks

APIs available on the Java EE platform for processing JSON. Java EE 7 has standardized the JSON
processing APIs with Java Specification Request (JSR), that is, JSR 353 - Java API for JSON Processing.

This JSR offers portable APIs to parse, generate, transform, and query JSON data.

The JSR 353 APIs can be classified into two categories on the basis of the processing model followed by
the APIs:
• Object model API
• Streaming model API

Processing JSON with JSR 353 object model APIs

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

60
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
This category of APIs generates an in-memory tree model for JSON data and then, starts
processing it as instructed by the client. This is conceptually similar to the Document Object
Model (DOM) API for XML.

used classes in the object model API of the JSR 353


Class or interface Description
javax.json.Json This class is the main factory class for creating JSON
processing objects such as JsonReader and JsonWriter.
javax.json.JsonReader This interface reads the JSON content and generates a JSON
object or array as appropriate.
javax.json.JsonWriter This interface writes a JSON object or array to an output
source.
javax.json.JsonObjectBuilder This interface offers APIs for generating JsonObject models
from scratch.
javax.json.JsonArrayBuilder This interface offers APIs for generating JsonArray models
from scratch.
javax.json.JsonValue This interface is the superinterface representing an
immutable JSON value. The JSON value takes one of the
following forms: javax.json.JsonObject
javax.json.JsonArray
javax.json.JsonNumber
javax.json.JsonString
javax.json.JsonValue.TRUE
javax.json.JsonValue.FALSE javax.json.JsonValue.NULL

Processing JSON with JSR 353 streaming APIs

This interface offers APIs for generating JsonObject models from scratch.

This category of APIs supports the streaming model for both reading and writing the JSON
content. This model is designed to process a large amount of data in a more efficient way.
Conceptually, this model is similar to the Streaming API for XML (StAX) parser
Streaming APIs are grouped in the javax.json.stream package in the JSR specification.

used classes in the streaming API provided by the JSR 353


Class Description
javax.json.stream.JsonParser This class provides forward read-only access to JSON data
by using the pull parsing programming model.
javax.json.stream.JsonGenerator This class writes JSON to an output source as specified by
the client application. It generates the name-value pairs
for the JSON objects and values for the JSON arrays.

Jackson API for processing JSON

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

61
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Jackson is a multipurpose data processing Java library. The primary capability of this tool is the support
for processing JSON. It also has additional modules for processing the data encoded in other popular
formats such as
1. Apache Avro (a data serialization system),
2. Concise Binary Object Representation (CBOR)—a binary JSON format,
3. Smile (a binary JSON format),
4. XML,
5. comma separated values (CSV), and
6. YAML.

Jackson provides the following three alternative methods for processing JSON:

• Tree model APIs: This method provides APIs for building a tree representation of a JSON
document
• Data binding API: This method provides APIs for converting a JSON document into and from
Java objects
• Streaming API: This method provides streaming APIs for reading and writing a JSON document

Processing JSON with Jackson tree model APIs

core classes
Class Description
com.fasterxml.jackson.databind.ObjectMapper This mapper class provides the functionality
for converting between Java objects and
matching JSON representations.
com.fasterxml.jackson.databind.JsonNode This class is the base class for all JSON nodes,
which form the basis of the JSON tree model
in Jackson.

Processing JSON with Jackson data binding APIs

Jackson data binding is used to convert the JSON representation into and from Plain Old
Java Object (POJO) by using property accessors or annotations.

With this API, you can either generate generic collection classes or more specific Java
objects, such as the Employee object, for representing JSON data.

two variants available for representing JSON data.

1. Simple Jackson data binding with generalized objects

deal with highly dynamic JSON content where you may not be able to map data to a
specific Java object as the structure of the data changes dynamically.

ObjectMapper objectMapper = new ObjectMapper();


//properties will store name and value pairs read from jsonString

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

62
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Map<String, String> properties = objectMapper.readValue( jsonString, new
TypeReference<Map<String, String>>() { });

2. Full Jackson data binding with specialized objects

is well structured, you can directly map the content to a concrete Java class. A full
data binding solution fits such a scenario. For instance, you can create an Employee
class for representing the employee data presented in the JSON format as long as
the JSON content structure does not change.

ObjectMapper objectMapper = new ObjectMapper();


Employee employee = objectMapper.readValue(new File("emp.json"),
Employee.class);

Processing JSON with Jackson streaming APIs

classes in the streaming model API


Class Description
com.fasterxml.jackson.core.JsonParser This class is used for reading the JSON
content.
com.fasterxml.jackson.core .JsonGenerator This class is used for writing
the JSON content.
com.fasterxml.jackson.core.JsonFactory This is the main factory class of the Jackson
package. It is used to generate JsonParser and
JsonWriter.

Jackson streaming APIs to generate JSON

Jackson streaming APIs for writing JSON data.


Employee objects, converts them into the JSON representations, and then writes to the
OutputStream object

Eg:
OutputStream outputStream = new FileOutputStream("emp-array.json");
JsonGenerator jsonGenerator = new JsonFactory().createGenerator(outputStream,
JsonEncoding.UTF8);

jsonGenerator.writeStartArray();
List<Employee> employees = getEmployeesList();

for (Employee employee : employees) {


jsonGenerator.writeStartObject();
jsonGenerator.writeNumberField("employeeId",
employee.getEmployeeId());
jsonGenerator.writeStringField("firstName", employee.getFirstName());
jsonGenerator.writeStringField("lastName", employee.getLastName());

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

63
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
jsonGenerator.writeEndObject();
}

jsonGenerator.writeEndArray();

jsonGenerator.close();
outputStream.close();

Using the Gson API for processing JSON

Gson is an open source Java library that can be used for converting Java objects into JSON
representations and vice versa. The Gson library was originally developed by Google for its
internal use and later open sourced under the terms of Apache License 2.0.

Processing JSON with object model APIs in Gson

The main class in the Gson library that you will use for building an object model from the JSON
data is the com.google.gson.Gson class.

core Gson classes


Class Description
com.google.gson.GsonBuilder This class is useful when you need to construct a
Gson instance, overriding the default configurations
such as custom date format, pretty printing, and
custom sterilization.
com.google.gson.Gson This class is the main class for using Gson. This class
does the conversion from JSON into a Java object and
the other way round.
com.google.gson.reflect.TypeToken<T> This class is used for getting a generic type for a class.
The resulting type can be used for serializing and
deserializing JSON data.

Processing JSON with Gson streaming APIs

Gson library supports the streaming APIs to read and write the JSON representations. The
streaming APIs in Gson follow the pull parser model.

Class Description
com.google.gson.stream.JsonReader This class reads the JSON-encoded value as a
stream of tokens. Tokens are read in the same
order as they appear in the JSON document.
com.google.gson.stream.JsonWriter This class writes a JSON-encoded value to the
stream, one token at a time.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

64
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Build RESTful web services with JAX-RS APIs


refer classroom notes and recorded videos on weit cloud

The Description and Discovery of RESTful Web Services

need for a good API documentation solution in order to accelerate the adoption of their REST API
services by customers.

popular solutions available today for describing, producing, consuming, and visualizing RESTful web
services.

• Web Application Description Language


• RESTful API Modeling Language
• Swagger

Overview of the WADL structure

• Web Application Description Language (WADL) is an XML description of HTTP-based web


applications such as RESTful web services.
• WADL models the resources provided by a RESTful web service with relationships between
the resources. It also allows you to clearly represent the media types used for the request
and response contents.
• The WADL schema that you use for building a WADL file is based on the WADL specification
• It contains global information about RESTful web services, such as links to schema definition
and documentation.

summary of the elements that you see in WADL:

<resources>: This element comes as wrapper for all resources exposed by a RESTful web application.
<resource>: This element appears as a child of the resources element. This element is used for
describing a set of resources, each identified by a URI. This element can optionally have <param> to
describe the path parameters present in the request, if any.
<method>: A resource may have one or more <method> definitions. This element defines the HTTP
methods, such as GET, POST, PUT, and DELETE, available to the resource.
<request>: A <method> definition can optionally include this element that describes an input to the
resource method. A request can have one or more of the following elements as its child:
• <doc>: This element is used for documenting the parameters
• <representation>: This element specifies the Internet media type for the payload present in
the body of the request
• <param>: This element specifies the query or header parameter present in the request
<response>: This element specifies the result of invoking an HTTP method on a resource. The
optional status code present in the response describes the list of the HTTP status codes associated
with the response. A response can have one or more of the following elements as its child:
• <doc>: This element is used for documenting the <response> header parameters
• <representation>: This element describes the Internet media type for the response content
returned by the API
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

65
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• <param>: This element specifies the HTTP header parameters present in the response.

WADL example

This method returns a Department object for the department ID passed by the client
@GET
@Path("{id}")
@Produces("application/json")
public Department findDepartment(@PathParam("id") Short id)
{
//Method body
}

WADL code
<application xmlns="http://wadl.dev.java.net/2009/02">
<doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 2.10.4 2014-08-08
15:09:00"/>
<grammars/>
<resources base="http://localhost:8080/hrapp/webresources/">
<resource path="{id}">
<param xmlns:xs="http://www.w3.org/2001/XMLSchema" name="id"
style="template" type="xs:short"/>
<method id="findDepartment" name="GET">
<response>
<ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02"
xmlns="" element="department" mediaType="application/json"/>
</response>
</method>
</resource>
</resources>
</application>

• client access uri //localhost:8080/hrapp/webresources/10

RESTful API Modeling Language

• RESTful API Modeling Language (RAML) provides human-readable and machine-processable


documentation for your RESTful web services.
• It helps you to clearly document resources, methods, parameters, responses, media types,
and other HTTP constructs that form the basis for a RESTful web service.
• RAML Workgroup includes technology leaders from various software vendors such as
MulesSoft Inc., PayPal Inc., Intuit Inc., and Cisco.

An overview of the RAML structure

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

66
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
An RAML file is a text file with the recommended extension of .raml. It uses spaces as indentation;
you can use two or four spaces for indentation.

grouping the contents into different logical sections

Basic information: The basic information includes information about REST APIs, such as the API title,
version, base URI, base URI parameters, and schema definition for resources, protocols, and default
media type.

Security: You can have security scheme definitions for accessing APIs in the RAML file

Resources and nested resources: Resources are identified by their relative URI. A nested resource
(child resource) is a resource defined as a child of a parent resource.

HTTP methods: HTTP methods, such as GET, POST, PUT, and DELETE, which a client can perform on
resources.
The HTTP method may have following sections:
• Query parameters: queryParameters attribute, typically used with the HTTP GET method.
• Request data: The request payload specifies the media type and form parameters (used
with PUT and POST)
• Response: RAML defines the response types for each resource method. This includes the
HTTP status codes, descriptions, examples, or schemas.

RAML example

This method returns a Department object for the department ID passed by the client
@GET
@Path("{id}")
@Produces("application/json")
public Department findDepartment(@PathParam("id") Short id)
{
//Method body
}

The RAML file describing the preceding resource method

#%RAML 0.8
title: department resource
version: 1.0
baseUri: "http://localhost:8080/hrapp/webresources"
schemas:
- department: !include schemas/department.xsd
- department-jsonschema: !include schemas/department-jsonschema.json
/departments:
get:
/{id}:
uriParameters:
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

67
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
id:
type: integer
get:
responses:
200:
body:
application/json:
schema: department-jsonschema
example: !include examples/department.json

Swagger

Swagger offers a specification and complete framework implementation for describing,


producing, consuming, and visualizing RESTful web services.

The Swagger framework works with many of the popular programming languages, such as Java,
Scala, Clojure, Groovy, JavaScript, and .Net.

Swagger framework has the following three major components:


• Server: This component hosts the RESTful web API descriptions for the services that
clients want to use
• Client: This component uses the RESTful web API descriptions from the server to
provide an automated interfacing mechanism to invoke the REST APIs
• User interface: This part of the framework reads a description of the APIs from the
server and renders it as a web page and provides an interactive sandbox to test the APIs

overview of Swagger's structure

• the swagger 1.x file contents that describe the RESTful APIs are represented as the JSON
objects. With
• the Swagger 2.0 release, you can also use the YAML format to describe the RESTful web
APIs.

The following properties describe the basic information about the RESTful web application:
• swagger: This property specifies the Swagger version.
• info: This property provides metadata about the API.
• host: This property locates the server where APIs are hosted.
• basePath: This property is the base path for the API. This property is relative to the
value set for the host field.
• schemes: This property transfers the protocol for a RESTful web API such as HTTP and
HTTPS.

The following properties allow you to specify the default values at the application level, which
can be optionally overridden for each operation:

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

68
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• consumes: This property specifies the default Internet media types that the APIs
consume. It can be overridden at the API level.
• produces: This property specifies the default Internet media types that the APIs
produce. It can be overridden at the API level.
• securityDefinitions: This property globally defines the security schemes for the
document. These definitions can be referred from the security schemes specified for
each API.

The following properties describe the operations (REST APIs):


• paths: This property specifies the path to the API or the resources. The path must be
appended to the basePath property in order to get the full URI.
• definitions: This property specifies the input and output entity types for the operations
on the REST resources (APIs).
• parameters: This property specifies the parameter details for an operation.
• responses: This property specifies the response type for an operation.
• security: This property specifies the security schemes in order to execute this operation.
• externalDocs: This property links to the external documentation.

An overview of Swagger APIs

Swagger framework consists of five subprojects, each built with a specific purpose

• swagger-spec: This repository contains the Swagger specification and the project in
general.
• swagger-ui: This project is an interactive tool to display and execute the Swagger
specification files.
• swagger-editor: This project allows you to edit the YAML files. It is released as a part of
Swagger 2.0.
• swagger-core: This project provides the scala and java library to generate the Swagger
specifications directly from the code. It supports JAX-RS, Servlet APIs, and the Play
framework.
• swagger-codegen: This project provides a tool that can read the Swagger specification
files and generate the client and server code that consumes and produces the
specifications.

RESTful API Design Guidelines

• Naming RESTful web resources

It is recommended to use nouns to name both resources and path segments that will appear in
the resource URI. You should avoid using verbs for naming resources and resource path
segments.

use plural nouns to refer to a collection of resources. URI must look like /departments.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

69
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
read a specific department from the collection, the URI becomes /departments/{id} , should
look like /departments/10.

Resource GET POST PUT DELETE


/departments Get all Create a Bulk update on departments Delete all
departments new departmen
department ts
/departments/ Get the HR Not allowed Update the HR department Delete the
10 department with HR
id=10 departmen
t

• Implementing partial response

Partial response refers to an optimization technique offered by the RESTful web APIs to return
only the information (fields) required by the client.

In this mechanism, the client sends the required field names as the query parameters for an API
to the server, and the server trims down the default response content by removing the fields
that are not required by the client.

/employees/1234?select=firstName,lastName,email

The Jersey framework supports the partial response feature via


org.glassfish.jersey.message.filtering.SelectableEntityFilteringFeature.

To enable this feature, you just need to register SelectableEntityFilteringFeature in the


application.

• Paging resource collection

API that allows the client to specify the offset and the limit for the
resource collection as the query parameters is /departments?offset=1&limit=20.

• Using HATEOAS in response representation

Hypertext as the Engine of Application State (HATEOAS) refers to the use of hypermedia links in
the resource representations.

This architectural style lets the clients dynamically navigate to the desired resource by traversing
the hypermedia links present in the response body.

Embedded resources: This concept provides a way to embed another resource within the
current one. In the JSON format, you will use the _embedded attribute to indicate the
embedded resource.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

70
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Links: This concept provides links to associated resources. In the JSON format, you will use the
_links attribute to link resources.

• Versioning RESTful web APIs

Versioning of APIs helps you to roll out new releases without affecting the existing customer
base as you can continue to offer the old API versions for a certain period of time.

version is appended along with the URI GET /api/v1/departments HTTP/1.1

custom header to specify the API version that the client is looking for GET /api/departments
HTTP/1.1 api-version: 1.0

API implementation can read the request header via @javax.ws.rs.HeaderParam


@HeaderParam("api-version") String version)

• Caching RESTful web API results

ability to cache and reuse previously retrieved resources is essential for improving the
performance of a REST application.

HTTP Cache-Control directive defines the HTTP response caching policies. You can use it for
enabling the caching of the RESTful web API results for a specified interval.

HTTP Cache-Control Description


directive
Public In this directive, public resources can be cached by the client and all
intermediate public proxies.
private In this directive, private resources can be cached only by the client.
max-age This directive specifies how long a resource cached on the client is
valid (measured in seconds).
smax-age This property specifies the maximum age for a shared cache such as
proxy cache (for example, content delivery network).
no-cache This directive indicates that the resource should not be cached.
no-store This directive indicates that the cached resource should not be stored
on disk; however, it can be cached in-memory.
must-revalidate This directive indicates that once the cache expires, the cache must
revalidate the resource with the origin server even if the client is
willing to work on the stale resource.

• Microservice architecture style for RESTful web applications

Microservice is an architectural style for implementing a single application as a suite of small


services. Each service can be deployed and managed separately.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

71
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Services communicate with each other via synchronous protocols such as REST over HTTP or
asynchronous protocols such as messaging queue.

advantages of the microservice architecture

1. A small, modular, and easily manageable code base


2. Each service can be deployed, managed, and tuned separately
3. Improved resilience
4. modules can be redeployed without affecting the entire application

• Using Open Data Protocol with RESTful web APIs

REST is an architecture style for sending messages back and forth from the client to the server
over HTTP.
The REST architectural style does not define any standard for querying and updating data.
Open Data Protocol (OData) defines a web protocol for querying and updating data via RESTful
web APIs uniformly.
Many companies, including Microsoft, IBM, and SAP, support OData today, and it is governed by
Organization for the Advancement of Structured Information Standards (OASIS).

URI convention for OData-based REST APIs

Service root: This part identifies the root of an OData service


Resource path: This part identifies the resources exposed by an OData service
Query string options: This part identifies the query options (built-in or custom) for the resource

Reading resources

GET http://localhost:8080/hrapp/odata/Departments HTTP/1.1

reads the details of department with the given ID:

GET http://localhost:8080/hrapp/odata/Departments(10) HTTP/1.1.

Querying data

GET http://localhost:8080/hrapp/odata/Departments?$orderby=DepartmentName HTTP/1.1

Query options

Query Option Description Example


$filter This option allows the client to /Employees?$filter=FirstName eq
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

72
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
filter a collection of resources. 'Jobinesh'
$expand This option includes the specified /Departments(10)?$expand=Employees
(child) resource in line with the
retrieved resources.
$select This option includes the supplied /Departments?$select=Name,LocationI
attributes alone in the resulting d
entity.
$orderby This option sorts the query result Departments?$orderby=DepartmentNa
by one or more attributes. me desc
$top This option returns only the Departments?$top=10
specified number of items (from
the top) in the result collection.
$skip This option indicates how many Departments?$skip=10
items need to be skipped from the
top while returning the result.
$count This option indicates the total Departments/$count
number of items in the result.

Securing RESTful web services

OAuth is an open standard for authorization, used by many enterprises and service providers to
protect resources.

OAuth solves a different security problem than what HTTP basic authentication has been used
for.

OAuth protocol allows client applications to access protected resources on behalf of the
resource owner

OAuth protocol specifies a process for resource owners to authorize third-party applications to
access their server resources without sharing their credentials.

The consumer application (or consumer service) only receives an authorization token that can
be used to access data from the service provider.

Common terminologies and roles

• Client (consumer): This refers to an application (service) that tries to access protected
resource on behalf of the resource owner and with the resource owner's consent. A
client can be a business service, mobile, web, or desktop application. In the previous
example, PrintInc is the client application.
• Server (service provider): This refers to an HTTP server that understands the OAuth
protocol. It accepts and responds to requests authenticated with the OAuth protocol
from various client applications (consumers). If you relate this with the previous
example, StorageInc is the service provider.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

73
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• Protected resource: Protected resources are resources hosted on servers (the service
providers) that are access restricted. The server validates all incoming requests and
grants access to the resource as appropriate.
• Resource owner: This refers to an entity capable of granting access to a protected
resource. Mostly, it refers to an end user who owns the protected resource. In the
previous example, Jane is the resource owner.
• Consumer key and secret (client credentials): These two strings are used to identify and
authenticate the client application (the consumer) making the request.
• Request token and secret (temporary credentials): This is the temporary credential
returned by the server when the resource owner authorizes the client application to use
the resource. As the next step, the client will send this request token to the server to get
authorized. On successful authorization, the server returns an access token. The access
token is explained next.
• Access token and secret (token credentials): The server returns an access token to the
client when the client submits temporary credentials obtained from the server during
the resource grant approval by the user. The access token is a string that identifies a
client that is requesting for protected resources. Once the access token is obtained, the
client passes it along with each resource request to the server. The server can then
verify the identity of the client by checking this access token.

OAuth 1.0

Grant types in OAuth 2.0

Authorization code: The authorization code is obtained from the authentication server instead
of directly requesting it from the resource owner. In this case, the client directs the resource
owner to the authorization server. The authorization server authenticates the user, obtains
authorization, and returns the authorization code to the client. In this mode, the resource
owner's credentials are never shared with the client. This is very similar to OAuth 1.0, except
that the cryptographic signing of messages is not required in OAuth 2.0.
Implicit: The implicit grant is a simplified version of the authorization code grant type flow. In
the implicit grant flow, the client is issued an access token directly as the result of the resource
owner's authorization. This is less secure as the client is not authenticated. This is commonly
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

74
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
used for client-side devices, such as mobile, where the client credentials cannot be stored
securely.
Resource owner password credentials: The resource owner's credentials, such as username
and password, are used by the client for directly obtaining the access token during the
authorization flow. The access code is used thereafter for accessing resources. This grant type is
only used with trusted client applications. This is suitable for legacy applications that use the
HTTP Basic authentication to incrementally transition to OAuth 2.0.
Client credential: Client credentials are used directly for getting access tokens. This grant type
is used when the client is also the resources owner. This is commonly used for embedded
services and backend applications, where the client has an account (direct access rights).

OAuth 2.0

OAuth 1.0 vs OAuth 2.0

1.0 2.0
Transport Transport-Independent. Security is not Transport-Dependent. Most
delegated to HTTPS/TLS. security defenses are delegated
to HTTPS/TLS.
security Digital signatures are used to prove the These are easy for integration but
integrity and authenticity of a message. not great for security
easiness Not easy easy
flexible only handled web workflows considers non-web clients as well

Unit 3 : Developing service oriented


application with WCF
What Is Windows Communication Foundation?

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

75
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
WCF stands for Windows Communication Foundation. It is basically used to create a distributed
and interoperable Application. Interoperability is the fundamental characteristics of WCF. You
can send the data asynchronously from one end point to another.
WCF is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a
common platform for all .NET communication.

Distributed Application

It means those Applications, which do not run only on single system but can run on
multiple systems, which are connected over the network. For example, a Web Service
that can consume by different clients.

Interoperable

An application that can communicate with any other application that is built on any
platform and using any programming language is called as an interoperable application.

Difference between WCF and Web service

Features Web Service WCF

Hosting It can be hosted in IIS It can be hosted in IIS, windows


activation service, Self-hosting,
Windows service
Programming [WebService] attribute has to [ServiceContract] attribute has
be added to the class to be added to the Interface
Model [WebMethod] attribute [OperationContract] attribute
represents the method represents the method
exposed to client exposed to client
Operation One-way, Request- Response One-Way, Request-Response,
are the different operations Duplex are different type of
supported in web service operations supported in WCF
XML System.Xml.serialization name System.Runtime.Serialization
space is used for serialization namespace is used for
serialization
Encoding XML 1.0, MTOM(Message XML 1.0, MTOM, Binary,
Transmission Optimization Custom
Mechanism), DIME, Custom
Transports Can be accessed through HTTP, Can be accessed through HTTP,
TCP, Custom TCP, Named pipes, MSMQ,P2P,
Custom
Protocols Security Security, Reliable messaging,
Transactions

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

76
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Hosting It can be hosted in IIS It can be hosted in IIS, windows


activation service, Self-hosting,
Managed Windows service

Why do we need WCF?


Let's take this scenario
We have 2 clients and we need to implement a service a for them.
1. The first client is using a Java application to interact with our service, so for
interoperability this client wants messages to be in XML format and the protocol to be
HTTP.
2. The second client uses .NET, so for better performance this client wants messages
formatted in binary over TCP protocol.

Without WCF

1. To satisfy the first client requirement we end up implementing an ASMX web service,
and

2. To satisfy the second client requirement we end up implementing a remoting service

These are 2 different technologies, and have complete different programming models. So the
developers have to learn different technologies.
So to unify and bring all these technologies under one roof Microsoft has come up with a single
programming model that is called as WCF - Windows Communication Foundation.

With WCF
You implement one service and we can configure as many end points as want to support all the
client needs. To support the above 2 client requirements, we would configure 2 end points. In
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

77
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
the endpoint configuration we can specify the protocols and message formats that we want to
use.

Advantages of WCF
1. It is interoperable with respect to other services. This is in sharp contrast to .NET
Remoting in which both the client and the service must have .Net.
2. WCF services offer enhanced reliability as well as security in comparison to ASMX
(Active Server Methods) web services.
3. Implementing the security model and binding change in WCF do not require a major
change in coding. Just a few configuration changes is required to meet the constraints.
4. WCF has built-in logging mechanism whereas in other technologies, it is essential to do
the requisite coding.
5. WCF has integrated AJAX and support for JSON (JavaScript object notation).
6. It offers scalability and support for up-coming web service standards.
7. It has a default security mechanism which is extremely robust.

Fundamental Windows Communication Foundation Concepts

Message
Message is the communication unit, as it is in the form of an envelop. The transmission of the
data from the client to Service and Service to client is being done by envelop. The envelop or
message has the sections, given below-
• Header
• Body
By default Header and fault are disabled but Body is responsible for the data transmission or
data exchanging.
Header is useful to send some data from client to Server. Suppose we want to send user name
from each request but don’t want to send it by an argument, we can easily add it into message
header.

Endpoint

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

78
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Endpoint is a very essential part of WCF Application, as it describes the address of Web Service
from where a user can receive and send the message. It also specifies the communication
mechanism of how the message will be sent or received.

End point consists of three things, which are A,B,C and each of them have a question mark.
1. Address (Where?)
2. Binding (how?)
3. Contract (What?)
Endpoint = A + B+ C

Address
Address is the address of WCF Service, where the Service is hosted? It gives the exact URL of
Web Service, where the Service hosts the pattern of URL, which is-

1. Scheme://domain/[:port]/path
2. net.tcp://localhost:1234/MyService
3. http://localhost:1234/MyService

Binding
It describes the way or mechanism by which the user will communicate with Web Service. It
constitutes some binding element, which creates the structure of communication such as some
transport protocols like HTTP, TCP etc. Message format or security techniques etc.

Different Bindings supported by WCF


Binding Description
BasicHttpBinding Basic Web service communication. No security by default
WSHttpBinding Web services with WS-* support. Supports transactions
WSDualHttpBinding Web services with duplex contract and transaction support
WSFederationHttpBinding Web services with federated security. Supports transactions
MsmqIntegrationBinding Communication directly with MSMQ applications. Supports
transactions
NetMsmqBinding Communication between WCF applications by using queuing.
Supports transactions
NetNamedPipeBinding Communication between WCF applications on same computer.
Supports duplex contracts and transactions
NetPeerTcpBinding Communication between computers across peer-to-peer services.
Supports duplex contracts
NetTcpBinding Communication between WCF applications across computers.
Supports duplex contracts and transactions

Contract
Contract is the third important question. What functionality and operation is being provided by
the service is called contract. It specifies what functionality and operations are need to be
exposed to the client. It is the interface name which has all operation that need to be exposed.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

79
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

1. service contract
• Ties together multiple related operations into a single functional unit. The
contract can define service-level settings, such as the namespace of the service,
a corresponding callback contract, and other such settings. In most cases, the
contract is defined by creating an interface in the programming language of
your choice and applying the [ServiceContractAttribute]attribute to the
interface. The actual service code results by implementing the interface.
2. operation contract
• An operation contract defines the parameters and return type of an operation.
When creating an interface that defines the service contract, you signify an
operation contract by applying the [OperationContractAttribute] attribute to each
method definition that is part of the contract. The operations can be modeled as
taking a single message and returning a single message, or as taking a set of types
and returning a type. In the latter case, the system will determine the format for the
messages that need to be exchanged for that operation.
3. message contract
• Describes the format of a message. For example, it declares whether message
elements should go in headers versus the body, what level of security should be
applied to what elements of the message, and so on.
4. fault contract
• Can be associated with a service operation to denote errors that can be
returned to the caller. An operation can have zero or more faults associated
with it. These errors are SOAP faults that are modeled as exceptions in the
programming model.
5. Data contract
• The descriptions in metadata of the data types that a service uses. This enables
others to interoperate with the service. The data types can be used in any part
of a message, for example, as parameters or return types. If the service is using
only simple types, there is no need to explicitly use data contracts.
Hosting
Hosting is the important thing in WCF Application and it makes WCF Application different from
other distributed Applications. WCF supports following types of hosting-

• IIS Hosting
• Self hosting
• WAS hosting

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

80
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Windows Communication Foundation Architecture

Contracts and Descriptions


Contracts define various aspects of the message system. The data contract describes every
parameter that makes up every message that a service can create or consume. The message
parameters are defined by XML Schema definition language (XSD) documents, enabling any
system that understands XML to process the documents. The message contract defines specific
message parts using SOAP protocols, and allows finer-grained control over parts of the message,
when interoperability demands such precision. The service contract specifies the actual method
signatures of the service, and is distributed as an interface in one of the supported programming
languages, such as Visual Basic or Visual C#.

Policies and bindings stipulate the conditions required to communicate with a service. For
example, the binding must (at a minimum) specify the transport used (for example, HTTP or
TCP), and an encoding. Policies include security requirements and other conditions that must be
met to communicate with a service.

Service Runtime
The service runtime layer contains the behaviors that occur only during the actual operation of
the service, that is, the runtime behaviors of the service. Throttling controls how many

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

81
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
messages are processed, which can be varied if the demand for the service grows to a preset
limit. An error behavior specifies what occurs when an internal error occurs on the service, for
example, by controlling what information is communicated to the client. (Too much information
can give a malicious user an advantage in mounting an attack.) Metadata behavior governs how
and whether metadata is made available to the outside world. Instance behavior specifies how
many instances of the service can be run (for example, a singleton specifies only one instance to
process all messages). Transaction behavior enables the rollback of transacted operations if a
failure occurs. Dispatch behavior is the control of how a message is processed by the WCF
infrastructure.

Extensibility enables customization of runtime processes. For example, message inspection is


the facility to inspect parts of a message, and parameter filtering enables preset actions to occur
based on filters acting on message headers.

Messaging
The messaging layer is composed of channels. A channel is a component that processes a
message in some way, for example, by authenticating a message. A set of channels is also
known as a channel stack. Channels operate on messages and message headers. This is different
from the service runtime layer, which is primarily concerned about processing the contents of
message bodies.

There are two types of channels: transport channels and protocol channels.

Transport channels read and write messages from the network (or some other communication
point with the outside world). Some transports use an encoder to convert messages (which are
represented as XML Infosets) to and from the byte stream representation used by the network.
Examples of transports are HTTP, named pipes, TCP, and MSMQ. Examples of encodings are
XML and optimized binary.

Protocol channels implement message processing protocols, often by reading or writing


additional headers to the message. Examples of such protocols include WS-Security and WS-
Reliability.

The messaging layer illustrates the possible formats and exchange patterns of the data. WS-
Security is an implementation of the WS-Security specification enabling security at the message
layer. The WS-Reliable Messaging channel enables the guarantee of message delivery. The
encoders present a variety of encodings that can be used to suit the needs of the message. The
HTTP channel specifies that the HyperText Transport Protocol is used for message delivery. The
TCP channel similarly specifies the TCP protocol. The Transaction Flow channel governs
transacted message patterns. The Named Pipe channel enables interprocess communication.
The MSMQ channel enables interoperation with MSMQ applications.

Hosting and Activation


In its final form, a service is a program. Like other programs, a service must be run in an
executable. This is known as a self-hosted service.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

82
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Services can also be hosted, or run in an executable managed by an external agent, such as IIS or
Windows Activation Service (WAS). WAS enables WCF applications to be activated automatically
when deployed on a computer running WAS. Services can also be manually run as executables
(.exe files). A service can also be run automatically as a Windows service. COM+ components
can also be hosted as WCF services.

WCF and .NET Framework Client Profile

.NET Framework Client Profile is a lightweight version of the full .Net Framework designed for
clients that don’t need the entire framework. Not all of Windows Communication Foundation is
supported by the client framework.

This enables faster deployment and a smaller install package for applications that target the
.NET Framework 4 Client Profile.

WCF features supported by the .Net Framework Client Profile

The following Windows Communication Foundation features are supported by .NET Framework
Client Profile:
• All of WCF is supported except for Cardspace and web hosting.
• Remoting TCP/IP channels are supported.
• Asmx (Web Services) are not supported.

Basic WCF Programming

Step 1:- Create one WCF application in Visual Studio


Once we create any WCF service template, we will find one interface and one class which
implement the interface.
Here is our interface

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace PriceCalculator
{
// NOTE:
You can use the "Rename" command on the "Refactor" menu to
change the interface name "ICalculator" in both code and config file
together.
[ServiceContract]
public interface ICalculator
{
[OperationContract]
string Calculate(int price, int Qty);
}

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

83
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
We have placed the ServiceContract attributes over interface. It implies that this is our interface
and it’s going to expose to outer world and the function Calculate is specified as
OperationContract which means that it’s out function which will be called by external client.

Step 2:- Implement interface to class

Now, we have to implement this interface to class. Have a look on below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace PriceCalculator
{
public class Calculator : ICalculator
{
public string Calculate(int price, int Qty)
{
return Convert.ToString(price * Qty);
}
}
}
This is very simple class where we have implemented the interface. Now, the client can call this
service by using the object of this class.
Hence we have finished the server creation part. If we want to check the service we can see it in
browser. Just run the WCF application and we will find that service is running in browser, if
everything is OK.
Here is output of service application.

OK, It’s running fine . We can go to next step .


Step 3:- consume service by client.
In this step we have to consume WCF service by client. We will create one small console
application to do same. Let’s create one console application and add service reference.
Go to Add Service reference option and discover the service. We will get below screen.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

84
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

Once you press OK ,it will add proxy in our client to consume service. And we will see that the
service reference has added in our solution explorer.
Step 4:- Call to service
This is the last step of application. Here we will consume the service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Client.PriceCalculator;
namespace Client
{
class Program
{
static void Main(string[] args)
{
PriceCalculator.CalculatorClient O = new CalculatorClient();
Console.WriteLine("Price is :- " + O.Calculate(100 ,10));
Console.ReadLine();
}
}
}
The consumption part is very simple. Just we have created the object of service class and like
normal function invocation we are calling service method.
The output is here.

Web Service QoS

The major requirements for supporting QoS in Web services are as follows:

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

85
TYBSC-CS SEM 5 (WEB SERVICES) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

• Availability: Availability is the quality aspect of whether the Web service is present
or ready for immediate use. Availability represents the probability that a service is
available. Larger values represent that the service is always ready to use while
smaller values indicate unpredictability of whether the service will be available at a
particular time. Also associated with availability is time-to-repair (TTR). TTR
represents the time it takes to repair a service that has failed. Ideally smaller values
of TTR are desirable.
• Accessibility: Accessibility is the quality aspect of a service that represents the
degree it is capable of serving a Web service request. It may be expressed as a
probability measure denoting the success rate or chance of a successful service
instantiation at a point in time. There could be situations when a Web service is
available but not accessible. High accessibility of Web services can be achieved by
building highly scalable systems. Scalability refers to the ability to consistently serve
the requests despite variations in the volume of requests.
• Integrity: Integrity is the quality aspect of how the Web service maintains the
correctness of the interaction in respect to the source. Proper execution of Web
service transactions will provide the correctness of interaction. A transaction refers
to a sequence of activities to be treated as a single unit of work. All the activities
have to be completed to make the transaction successful. When a transaction does
not complete, all the changes made are rolled back.
• Performance: Performance is the quality aspect of Web service, which is measured
in terms of throughput and latency. Higher throughput and lower latency values
represent good performance of a Web service. Throughput represents the number
of Web service requests served at a given time period. Latency is the round-trip time
between sending a request and receiving the response.
• Reliability: Reliability is the quality aspect of a Web service that represents the
degree of being capable of maintaining the service and service quality. The number
of failures per month or year represents a measure of reliability of a Web service. In
another sense, reliability refers to the assured and ordered delivery for messages
being sent and received by service requestors and service providers.
• Regulatory: Regulatory is the quality aspect of the Web service in conformance with
the rules, the law, compliance with standards, and the established service level
agreement. Web services use a lot of standards such as SOAP, UDDI, and WSDL.
Strict adherence to correct versions of standards (for example, SOAP version 1.2) by
service providers is necessary for proper invocation of Web services by service
requestors.
• Security: Security is the quality aspect of the Web service of providing confidentiality
and non-repudiation by authenticating the parties involved, encrypting messages,
and providing access control. Security has added importance because Web service
invocation occurs over the public Internet. The service provider can have different
approaches and levels of providing security depending on the service requestor.

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in

86

You might also like