You are on page 1of 142

WebServices

Workshop

Ionut David &


Sorin Nita
December 2013

Agenda

What is XML and XSD


What is a Web Service
What is SOAP
What is WSDL
What is JSON
What is REST
What is WADL
Tools
2

What is XML
XML stands for eXtensible Markup Language.
XML was designed to transport and store data, as HTML was designed to display data.
XML tags are not predefined. You must define your own tags.
XML does not do anything, XML its just a framework.
XML is the most common tool for data transmissions between all sorts of applications.
<?xml version="1.0" encoding="ISO-8859-15"?>
<class_list>
<student>
<name>Robert</name>
<grade>A+</grade>
</student>
<student>
<name>Lenard</name>
<grade>A-</grade>
</student>
</class_list>
3

XML Tree Structure


The first line is the XML declaration. It defines the XML version (1.0) and the encoding used (ISO8859-1 = Latin-1/West European character set).

The next line describes the root element of the document (like saying: "this document is a note").
The next 4 lines describe 4 child elements of the root (to, from, heading, and body).
And finally the last line defines the end of the root element
<?xml version="1.0" encoding="ISO-88591?>
<note>
<to>Sam</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

XML Tree Structure


XML documents must contain a root element. This element is "the parent" of all other elements.
All elements can have sub elements (child elements).
Children on the same level are called siblings (brothers or sisters).
All elements can have text content and attributes (just like in HTML).

XML Syntax Rules


The syntax rules of XML are very simple and logical.

All elements must have a closing tag.

<p>This is a paragraph</p>

XML tags are case sensitive, opening and closing tags must be written with the same case

<Message>This is incorrect</message>
<message>This is correct</message>

All XML elements must be properly nested within each other.

<b><i>This text is incorrect</b></i>


<b><i>This text is correct</i></b>

In XML, the attribute values must always be quoted.

<note date="12/11/2007">

XML Naming Rules


XML elements must follow these naming rules:

Names can contain letters, numbers, and other characters


Names cannot start with a number or punctuation character

Names cannot start with the letters xml (or XML, or Xml, etc)
Names cannot contain spaces

Any name can be used, no words are reserved.


Avoid using the following characters: - (line) . (dot) or : (colon)

XML Namespaces
In XML, element names are defined by the developer. This often results in a conflict when trying
to mix XML documents from different XML applications.
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>

<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>

Name conflicts in XML can easily be avoided using a name prefix.


<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>

<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>

XML Namespaces
When using prefixes in XML, a so-called namespace for the prefix must be defined.
The namespace is defined by the xmlns attribute in the start tag of an element.
The namespace declaration has the following syntax. xmlns:prefix="URI".
Namespaces can be declared in the elements where they are used or in the XML root element.
<root xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furniture">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
9

XML Namespaces
A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet Resource.
Defining a default namespace for an element saves us from using prefixes in all the child
elements.

It has the following syntax: xmlns=namespaceURI


This XML carries HTML table information:

<table
xmlns="http://www.w3.org/TR/html4/">
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
This XML carries information about a piece of furniture:
<table xmlns="http://www.w3schools.com/furniture">
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
10

Quiz time
Time to test the XML knowledge

11

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>
12

XSD features
An XML Schema:

defines elements and attributes that can appear in a document


defines which elements are child elements
defines the order and the number of child elements
defines whether an element is empty or can include text
defines data types for elements and attributes

defines default and fixed values for elements and attributes

13

XSD Reference
This XML document has a reference to an XML Schema:
<?xml version="1.0"?>
<note
xmlns="http://www.w3schools.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3schools.com note.xsd">
<to>Sam</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

The following fragment: xmlns=http://www.w3schools.com specifies the default namespace


declaration.

This fragment: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance indicates the XML Schema


Instance namespace

Last fragments is the schemaLocation attribute The first value is the namespace to use. The second value
is the location of the XML schema to use for that namespace:
xsi:schemaLocation="http://www.w3schools.com note.xsd
14

XSD <schema> Element


The <schema> element is the root element of every XML Schema.
The <schema> element may contain some attributes. A schema declaration often looks something
like this:

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

15

XSD <schema> Element


The following fragment: xmlns:xs=http://www.w3.org/2001/XMLSchema indicates that the
elements and data types used in the schema come from http://www.w3.org/2001/XMLSchema
namespace .

This fragment: targetNamespace="http://www.w3schools.com indicates that the elements


defined by this schema come from http://www.w3schools.com

This fragment: xmlns="http://www.w3schools.com indicates the default namespace.


This fragment: elementFormDefault=qualified indicates that any elements used by the XML
instance document which were declares in this schema must be namespace qualified
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">
...
</xs:schema>
16

XSD Simple Element


A simple element is an XML element that contains only text. It cannot contain any other elements
or attributes.

The text can be of many different types. It can be one of the types included in the XML Schema
definition (boolean, string, date, etc.), or it can be a custom type that you can define yourself.

The syntax for defining a simple element is:


<xs:element name=xxx type=yyy/>

Where xxx is the name of the element and yyy is the data type of the element.
XML Schema has a lot of built-in data types. The most common types are: (xs:string, xs:decimal,
xs:integer, xs:boolean, xs:date, xs:time)
<xs:element name="lastname" type="xs:string"/>
<xs:element name="age" type="xs:integer"/>
<xs:element name="dateborn" type="xs:date"/>

17

XSD Simple Element Values


Simple elements may have a default value OR a fixed value specified.
A default value is automatically assigned to the element when no other value is specified.
In the following example the default value is "red":
<xs:element name="color" type="xs:string" default="red"/>

A fixed value is also automatically assigned to the element, and you cannot specify another value.
In the following example the fixed value is "red":
<xs:element name="color" type="xs:string" fixed="red"/>

18

XSD Attributes
All attributes are declared as simple types.
Simple elements cannot have attributes. If an element has attributes, it is considered to be of a
complex type.

The syntax for defining an attribute is:


<xs:attribute name=xxx" type=yyy"/>

Where xxx is the name of the attribute and yyy is the data type of the attribute.
XML Schema has a lot of built-in data types. The most common types are: (xs:string, xs:decimal,
xs:integer, xs:boolean, xs:date, xs:time)

Here is an example:
<xs:attribute name="lang" type="xs:string"/>

19

XSD Attributes Values


Attributes may have a default value OR a fixed value specified.
A default value is automatically assigned to the attribute when no other value is specified.
In the following example the default value is "EN":
<xs:attribute name="lang" type="xs:string" default="EN"/>

A fixed value is also automatically assigned to the attribute, and you cannot specify another value.
In the following example the fixed value is "EN":
<xs:attribute name="lang" type="xs:string" fixed="EN"/>

Attributes are optional by default. To specify that the attribute is required, use the "use" attribute:
<xs:attribute name="lang" type="xs:string" use="required"/>

When an XML element or attribute has a data type defined, it puts restrictions on the element's
or attribute's content.

If an XML element is of type "xs:date" and contains a string like "Hello World", the element will
not validate.
20

XSD Restrictions/Facets
With XML Schemas, you can also add your own restrictions to your XML elements and attributes.
These restrictions are called facet.

The following example defines an element called "age" with a restriction. The value of age cannot
be lower than 0 or greater than 120:
<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="120"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

A value that is outside of 0-120 will not be validated.

21

XSD Restrictions/Facets
To limit the content of an XML element to a set of acceptable values, we would use the
enumeration constraint.

<xs:element name="car">
<xs:element name="car"
<xs:simpleType>
type="carType"/>
<xs:restriction
<xs:simpleType
base="xs:string">
name="carType">
<xs:enumeration
<xs:restriction
value="Audi"/>
base="xs:string">
<xs:enumeration
<xs:enumeration
value="Golf"/>
value="Audi"/>
<xs:enumeration
<xs:enumeration
value="BMW"/>
value="Golf"/>
</xs:restriction>
<xs:enumeration
In</xs:simpleType>
right side case the type "carType" can be used byvalue="BMW"/>
other elements because it is not a part of the
</xs:element>
</xs:restriction>
"car" element, its a new custom type that weve created.
</xs:simpleType>

22

XSD Restrictions on content


The example below defines an element called "letter" with a restriction. The only acceptable value
is ONE of the LOWERCASE letters from a to z:
<xs:restriction base="xs:string">
<xs:pattern value="[a-z]"/>
</xs:restriction>

The next example defines an element called "initials" with a restriction. The only acceptable value
is THREE of the UPPERCASE letters from a to z:
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z][A-Z][A-Z]"/>
</xs:restriction>

The next example also defines an element called "initials" with a restriction. The only acceptable
value is THREE of the LOWERCASE OR UPPERCASE letters from a to z:
<xs:restriction base="xs:string">
<xs:pattern value="[a-zA-Z][a-zA-Z][a-zA-Z]"/>
</xs:restriction>

23

XSD Restrictions on format


The next example defines an element called "choice" with a restriction. The only acceptable value
is ONE of the following letters: x, y, OR z:
<xs:restriction base="xs:string">
<xs:pattern value="[xyz]"/>
</xs:restriction>

The next example defines an element called digits" with a restriction. The only acceptable value
is FIVE digits in a sequence, and each digit must be in a range from 0 to 9:
<xs:restriction base="xs:integer">
<xs:pattern value="[0-9][0-9][0-9][0-9][0-9]"/>
</xs:restriction>

The example below defines an element called word" with a restriction. The acceptable value is
zero or more occurrences of lowercase letters from a to z:
<xs:restriction base="xs:string">
<xs:pattern value="([a-z])*"/>
</xs:restriction>

24

XSD Restrictions on format


The next example also defines an element called "letter" with a restriction. The acceptable value
is one or more pairs of letters, each pair consisting of a lower case letter followed by an upper

case letter:
<xs:restriction base="xs:string">
<xs:pattern value="([a-z][A-Z])+"/>
</xs:restriction>

The next example defines an element called "gender" with a restriction. The only acceptable value
is male OR female:
<xs:restriction base="xs:string">
<xs:pattern value="male|female"/>
</xs:restriction>

The next example defines an element called "password" with a restriction. There must be exactly
eight characters in a row and those characters must be lowercase or uppercase letters from a to z,
or a number from 0 to 9:
<xs:restriction base="xs:string">
<xs:pattern value="[a-zA-Z0-9]{8}"/>
</xs:restriction>
25

XSD Restrictions on whitespaces


This example defines an element called "address" with a restriction. The whiteSpace constraint is
set to "preserve", which means that the XML processor WILL NOT remove any white space:
<xs:restriction base="xs:string">
<xs:whiteSpace value="preserve"/>
</xs:restriction>

The whiteSpace constraint is set to "replace", which means that the XML processor WILL REPLACE
all white space characters (line feeds, tabs, spaces, and carriage returns) with spaces:
<xs:restriction base="xs:string">
<xs:whiteSpace value="replace"/>
</xs:restriction>

The whiteSpace constraint is set to "collapse", which means that the XML processor WILL
REMOVE all white space characters (line feeds, tabs, spaces, carriage returns are replaced with
spaces, leading and trailing spaces are removed, and multiple spaces are reduced to a single

space)

<xs:restriction base="xs:string">
<xs:whiteSpace value=collapse"/>
</xs:restriction>
26

XSD Restrictions on length


To limit the length of a value in an element, we would use the length, maxLength, and minLength
constraints.

This example defines an element called "password" with a restriction. The value must be exactly
eight characters:

<xs:restriction base="xs:string">
<xs:length value="8"/>
</xs:restriction>

This example defines another element called "password" with a restriction. The value must be
minimum five characters and maximum eight characters:
<xs:restriction base="xs:string">
<xs:minLength value="5"/>
<xs:maxLength value="8"/>
</xs:restriction>

There are also other constrain types for Datatypes like: fractionDigits, totalDigits, maxExclusive,
maxInclusive and so on.
27

XSD Complex element


A complex element is an XML element that contains other elements and/or attributes.
There are four kinds of complex elements:

empty elements
elements that contain only other elements
elements that contain only text
elements that contain both other elements and text

Each of these elements may contain attributes as well.

28

XSD Complex element


A complex XML element, "product", which is empty:
<product pid="1345"/>

A complex XML element, "employee", which contains only other elements:


<employee>
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>

A complex XML element, "food", which contains only text:


<food type="dessert">Ice cream</food>

A complex XML element, "description", which contains both elements and text:
<description>
It happened on <date lang="norwegian">03.03.99</date> ....
</description>

29

XSD Complex element


We can define a complex element in an XSD in two ways:
The employee element can be declares directly by naming the element, like this:
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

If you use the method described above, several elements can refer to the same complex type, like this:
<xs:element name="employee"
type="personinfo"/>
<xs:element name="student"
type="personinfo"/>
<xs:element name="member"
type="personinfo"/>
30

XSD Complex element


You can also base a complex element on an existing complex element and add some elements,
like this:
<xs:element name="employee" type="fullpersoninfo"/>
<xs:complexType name="personinfo">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="fullpersoninfo">
<xs:complexContent>
<xs:extension base="personinfo">
<xs:sequence>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
31

XSD Empty Complex element


An empty XML element:
<product prodid="1345" />

The "product" element above has no content at all. To define a type with no content, we must
define a type that allows elements in its content, but we do not actually declare any elements, like
this:

<xs:element name="product">
<xs:complexType>
<xs:complexContent>
<xs:restriction base="xs:integer">
<xs:attribute name="prodid"
type="xs:positiveInteger"/>
</xs:restriction>
</xs:complexContent>
</xs:complexType>
</xs:element>
In the example above, we define a complex type with a complex content. The complexContent
element signals that we intend to restrict or extend the content model of a complex type, and the
restriction of integer declares one attribute but does not introduce any element content.
32

XSD Empty Complex element


It is possible to declare the "product" element more compactly, like this:
<xs:element name="product">
<xs:complexType>
<xs:attribute name="prodid" type="xs:positiveInteger"/>
</xs:complexType>
</xs:element>

Or you can give the complexType element a name, and let the "product" element have a type
attribute that refers to the name of the complexType (if you use this method, several elements
can refer to the same complex type):
<xs:element name="product" type="prodtype"/>
<xs:complexType name="prodtype">
<xs:attribute name="prodid" type="xs:positiveInteger"/>
</xs:complexType>

33

XSD Complex Types with Elements Only


You can define the "person" element in a schema, like this:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

Notice the <xs:sequence> tag. It means that the elements defined ("firstname" and "lastname") must
appear in that order inside a "person" element.

Or you can give the complexType element a name, and let the "person" element have a type attribute
that refers to the name of the complexType (if you use this method, several elements can refer to the
same complex type):

34

XSD Complex Types with Text Only


This type contains only simple content (text and attributes), therefore we add a simpleContent
element around the content. When using simple content, you must define an extension OR a
restriction within the simpleContent element:

The following example declares a complexType, "shoesize". The content is defined as an integer
value, and the "shoesize" element also contains an attribute named "country":
<xs:element name="shoesize">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:integer">
<xs:attribute name="country" type="xs:string" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>

35

XSD Complex Types with Mixed Content

The following schema declares the "letter" element that contain attributes, elements, and text:
<xs:element name="letter">
<xs:complexType mixed="true">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="orderid" type="xs:positiveInteger"/>
<xs:element name="shipdate" type="xs:date"/>
</xs:sequence>
</xs:complexType>
</xs:element>

We could also give the complexType element a name, and let the "letter" element have a type
attribute that refers to the name of the complexType (if you use this method, several elements
can refer to the same complex type):
<xs:element name="letter" type="lettertype"/>
<xs:complexType name="lettertype" mixed="true">
..
..
36

XSD Indicators
We can control HOW elements are to be used in documents with indicators.
There are seven indicators:

Order indicators:

All

Choice

Sequence

Occurrence indicators:

maxOccurs

minOccurs

Group indicators:

Group name

attributeGroup name

37

XSD Order Indicators


Order indicators are used to define the order of the elements.
The <all> indicator specifies that the child elements can appear in any order, and that each child
element must occur only once:
<xs:element name="person">
<xs:complexType>
<xs:all>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:all>
</xs:complexType>
</xs:element>

When using the <all> indicator you can set the <minOccurs> indicator to 0 or 1 and the
<maxOccurs> indicator can only be set to 1 (the <minOccurs> and <maxOccurs> are described
later).

38

XSD Order Indicators


The <choice> indicator specifies that either one child element or another can occur:
<xs:element name="person">
<xs:complexType>
<xs:choice>
<xs:element name="employee" type="employee"/>
<xs:element name="member" type="member"/>
</xs:choice>
</xs:complexType>
</xs:element>

The <sequence> indicator specifies that the child elements must appear in a specific order:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

39

XSD Occurrence Indicators


Occurrence indicators are used to define how often an element can occur.
The <maxOccurs> indicator specifies the maximum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" maxOccurs="10"/>
</xs:sequence>
</xs:complexType>
</xs:element>

The <minOccurs> indicator specifies the minimum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string"
maxOccurs="10" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
40

XSD Group Indicators


Group indicators are used to define related sets of elements.
The following example defines a group named "persongroup", that defines a group of elements
that must occur in an exact sequence:
<xs:group name="persongroup">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="birthday" type="xs:date"/>
</xs:sequence>
</xs:group>

Attribute groups are defined with the attributeGroup declaration, like this:
<xs:attributeGroup name="groupname">
...
</xs:attributeGroup>

41

XSD The <any> Element


The <any> element enables us to extend the XML document with elements not specified by the
schema.

The following example is a fragment from an XML schema called "family.xsd". It shows a
declaration for the "person" element. By using the <any> element we can extend (after
<lastname>) the content of "person" with any element:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:any minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>

The <any> and <anyAttribute> elements are used to make EXTENSIBLE documents! They allow
documents to contain additional elements that are not declared in the main XML schema.

42

XSD The <anyAttribute> Element


The <anyAttribute> element enables us to extend the XML document with attributes not specified
by the schema.

The following example is a fragment from an XML schema called "family.xsd". It shows a
declaration for the "person" element. By using the <anyAttribute> element we can add any
number of attributes to the "person" element
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
<xs:anyAttribute/>
</xs:complexType>
</xs:element>

43

XSD String Data Types

String data types are used for values that contains character strings.
The string data type can contain characters, line feeds, carriage returns, and tab characters.
The following is an example of a string declaration in a schema:
<xs:element name="customer" type="xs:string"/>

An element in your document might look like this:


<customer>John Smith</customer>

The normalizedString data type also contains characters, but the XML processor will remove line
feeds, carriage returns, and tab characters.

The token data type also contains characters, but the XML processor will remove line feeds,
carriage returns, tabs, leading and trailing spaces, and multiple spaces.
<xs:element name="customer" type="xs:normalizedString"/>
<xs:element name="customer" type="xs:token"/>

44

XSD String Data Types

Other data types below derive from the String data type.

ENTITIES, ENTITY, ID, IDREF, IDREFS


Language, Name, NCName
NMTOKEN, NMTOKENS
Qname

Restrictions that can be used with String data types:

enumeration
length
maxLength
minLength

pattern (NMTOKENS, IDREFS, and ENTITIES cannot use this constraint)


whiteSpace
45

XSD Date and Time Data Types

The date data type is used to specify a date.


The date is specified in the following form "YYYY-MM-DD.
<xs:element name="start" type="xs:date"/>

To specify a time zone, you can either enter a date in UTC time by adding a "Z" behind the date or
you can specify an offset from the UTC time by adding a positive or negative time behind the date

The time is specified in the following form "hh:mm:ss"


<xs:element name="start" type="xs:time"/>

The dateTime is specified in the following form "YYYY-MM-DDThh:mm:ss.


<xs:element name="startdate" type="xs:dateTime"/>

The dateTime is specified in the following form "YYYY-MM-DDThh:mm:ss.


<xs:element name="startdate" type="xs:dateTime"/>

46

XSD Date and Time Data Types


Duration data type is used to specify a time interval in the following form "PnYnMnDTnHnMnS

P indicates the period (required)


T indicates the start of a time section

<xs:element name="period" type="xs:duration"/>

Other date and time date types used:

gDay, gMonth, gMonthDay, gYear, gYearMonth

Restrictions that can be used with Date data types:

enumeration

maxExclusive
maxInclusive
minExclusive
minInclusive
pattern
whiteSpace
47

XSD Numeric Data Types

The decimal data type is used to specify a numeric value (maximum of 18 digits).
<xs:element name="prize" type="xs:decimal"/>

The integer data type is used to specify a numeric value without a fractional component.
<xs:element name="prize" type="xs:integer"/>

Data types below derive from the Decimal data type and can be used:

Byte
Int
Long
negativeInteger, nonNegativeInteger, nonPositiveInteger, positiveInteger

Short
unsignedLong, unsignedInt, unsignedShort, unsignedByte

Restrictions that can be used with Numeric data types


48

XSD Miscellaneous Data Types


Other miscellaneous data types are boolean, base64Binary, hexBinary, float, double, anyURI,
QName, and NOTATION

The boolean data type is used to specify a true or false value.


<xs:attribute name="disabled" type="xs:boolean"/>

Binary data types are used to express binary-formatted data: base64Binary or hexBinary.
<xs:element name="blobsrc" type="xs:hexBinary"/>

The anyURI data type is used to specify a URI.

<xs:attribute name="src" type="xs:anyURI"/>

Restrictions that can be used with the other data types:

enumeration (a Boolean data type cannot use this constraint)


length (a Boolean data type cannot use this constraint)
maxLength (a Boolean data type cannot use this constraint)
minLength (a Boolean data type cannot use this constraint)

pattern
whiteSpace
49

XSD Schema Business application

One of the best applications for the XSD schemas is Business rules
Define the entities upon which you write business rules

Before you write business rules, you must first set up the model on which they rely. You define this model as a
business object model (BOM).

For example a simple purchase order:


Need to purchase an electric Lawnmower and a baby monitor from a merchant site
The price for the mower is $148.95
The price for the baby monitor is $39.98
The billing should be done to Robert Smith with address: 8 Oak Avenue, 95819 Old Town, PA, USA
The shipping should be done to Alice Smith with address: 123 Maple Street, 90952 Mill Valley, CA,

USA

50

XSD Schema Business appliance


<?xml version="1.0"?>
<purchaseOrder orderDate="1999-10-20">
<comment>Hurry, my lawn is going wild!</comment>
<shipTo country="US">
<name>Alice Smith</name>
<street>123 Maple Street</street>
<city>Mill Valley</city>
<state>CA</state>
<zip>90952</zip>
</shipTo>
<billTo country="US">
<name>Robert Smith</name>
<street>8 Oak Avenue</street>
<city>Old Town</city>
<state>PA</state>
<zip>95819</zip>
</billTo>
<items>
<item partNum="872-AA">
<productName>Lawnmower</productName>
<quantity>1</quantity>
<USPrice>148.95</USPrice>
<comment>Confirm this is electric</comment>
</item>
<item partNum="926-AA">
<productName>Baby Monitor</productName>
<quantity>1</quantity>
<USPrice>39.98</USPrice>
<shipDate>1999-05-21</shipDate>
</item>
</items>
</purchaseOrder>

51

XSD Schema Business application

Implement a physical model upon which the rules execute


The BOM must be mapped to a physical data model. This data model is called an
execution object model (XOM)

Every BOM element used in a rule must have a corresponding XOM implementation, but it does not have to be a simple
one-to-one mapping. You can create more complex BOM to XOM mappings, such as combining information from multiple
XOM properties into one BOM element.

You can implement the XOM as a Java object model or as an XML schema (XSD).

JAVA:

Comment Class
Comment is a public interface that extends javax.xml.bind.Element.
Content in instantiations of this class binds to the XML schema element named comment.

The getValue() and setValue() methods are used to get and set strings representing XML comment elements in the Java
content tree.

Items Class
The class provides public interfaces for Items and ItemType.
Content in instantiations of this class binds to the XML ComplexTypes Items and its child element ItemType.
Item provides the getItem() method.

ItemType provides setter and getter methods for each child object: PartNum, Comment, USPrice, ProductName, ShipDate,
Quantity
52

XSD Schema Business appliance

PurchaseOrder Class
PurchaseOrder is a public interface that extends javax.xml.bind.Element and
PurchaseOrderType.
Content in instantiations of this class binds to the XML schema element named
purchaseOrder.

PurchaseOrderType Class
Content in instantiations of this class binds to the XML schema child element named
PurchaseOrderType.
PurchaseOrderType is a public interface that provides setter and getter methods for each child
object: Items, OrderDate, Comment, BillTo, ShipTo

USAddress Class
Content in instantiations of this class binds to the XML schema element named USAddress.
USAddress is a public interface that provides setter and getter methods for each child object:
State, Zip, Country, City, Street, Name

53

XSD Schema Business appliance

XSD Schema corresponding to provided basic purchase order XML.

The mapping of business objects to schema objects with their according restrictions

Business rule: The maximum quantity of ordered items in a simple order should be an integer value not greater
than 100.
maps to
<xsd:element name="quantity">
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:maxExclusive value="100"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
Business rule: The stock identifier for the product should contain only alphanumeric values and have a form of 3
digits 2 upper case letters.
maps to
<xsd:simpleType name="SKU">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{3}-[A-Z]{2}"/>
</xsd:restriction>
</xsd:simpleType>
54

XSD Schema Business appliance

XSD Schema corresponding to provided basic purchase order XML.


Business rule: The address should contain the following details: name of the recipient, street, city, state (all string
based) and zip code (a decimal value) and for USA the country should be implicitly set
maps to
<xsd:complexType name="USAddress">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="street" type="xsd:string"/>
<xsd:element name="city" type="xsd:string"/>
<xsd:element name="state" type="xsd:string"/>
<xsd:element name="zip" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
</xsd:complexType>

55

XSD Schema Business appliance

The complete schema with all the elements

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="purchaseOrder" type="PurchaseOrderType"/>
<xsd:element name="comment" type="xsd:string"/>
<xsd:complexType name="PurchaseOrderType">
<xsd:sequence>
<xsd:element name="shipTo" type="USAddress"/>
<xsd:element name="billTo" type="USAddress"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="items" type="Items"/>
</xsd:sequence>
<xsd:attribute name="orderDate" type="xsd:date"/>
</xsd:complexType>
<xsd:complexType name="USAddress">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="street" type="xsd:string"/>
<xsd:element name="city" type="xsd:string"/>
<xsd:element name="state" type="xsd:string"/>
<xsd:element name="zip" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
</xsd:complexType>

56

XSD Schema Business appliance


<xsd:complexType name="Items">
<xsd:sequence>
<xsd:element name="item" minOccurs="1" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="productName" type="xsd:string"/>
<xsd:element name="quantity">
<xsd:simpleType>
<xsd:restriction base="xsd:positiveInteger">
<xsd:maxExclusive value="100"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="USPrice" type="xsd:decimal"/>
<xsd:element ref="comment" minOccurs="0"/>
<xsd:element name="shipDate" type="xsd:date" minOccurs="0"/>
</xsd:sequence>
<xsd:attribute name="partNum" type="SKU" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>

57

XSD Schema Business appliance


<!-- Stock Keeping Unit, a code for identifying products -->
<xsd:simpleType name="SKU">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{3}-[A-Z]{2}"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>

58

END of PART 1

59

What is a Web Service

A Web Service is a method of communication between two electronic devices over the World Wide Web.
A Web Service is a software function provided at a network address over the web or the cloud, it is a service
that is "always on.

A Web Service can convert your applications into Web-applications

A Web Service is a XML-based information exchange system that use the Internet for direct application-toapplication interaction.

60

Web Service components


The basic Web services platform is XML + HTTP.
All the standard Web Services works using following components

SOAP (Simple Object Access Protocol)


UDDI (Universal Description, Discovery and Integration)
WSDL (Web Services Description Language)

61

What is SOAP
It is a simple XML-based protocol to let applications exchange information over HTTP.
SOAP is a protocol for accessing a Web Service.
SOAP stands for Simple Object Access Protocol
SOAP is platform independent
SOAP is language independent

62

SOAP Building Blocks


A SOAP message is an ordinary XML document containing the following elements:

An Envelope element that identifies the XML document as a SOAP message


A Header element that contains header information
A Body element that contains call and response information
A Fault element containing errors and status information

63

SOAP Syntax Rules


Here are some important syntax rules:

A SOAP message MUST be encoded using XML


A SOAP message MUST use the SOAP Envelope namespace
A SOAP message MUST use the SOAP Encoding namespace
A SOAP message must NOT contain a DTD reference
A SOAP message must NOT contain XML Processing Instructions

64

SOAP Message example


<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Header>
...
</soap:Header>
<soap:Body>
...
<soap:Fault>
...
</soap:Fault>
</soap:Body>
</soap:Envelope>

65

SOAP Envelope Element


The required SOAP Envelope element is the root element of a SOAP message. This element
defines the XML document as a SOAP message:
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
...
Message information goes here
...
</soap:Envelope>

The xmlns:soap namespace in the example above it should always have the value of:
"http://www.w3.org/2001/12/soap-envelope". The namespace defines the Envelope as a SOAP
Envelope.

The encodingStyle attribute is used to define the data types used in the document. This attribute
may appear on any SOAP element, and applies to the element's contents and all child elements.
66

SOAP Header Element


The optional SOAP Header element contains application-specific information (like
authentication, payment, etc) about the SOAP message.

If the Header element is present, it must be the first child element of the Envelope element.
<soap:Header>
<m:Trans xmlns:m="http://www.w3schools.com/transaction/"
soap:mustUnderstand="1">234
</m:Trans>
</soap:Header>

The example above contains a header with a "Trans" element, a "mustUnderstand" attribute
with a value of 1, and a value of 234.

SOAP defines three attributes in the default namespace. These attributes are: mustUnderstand,
actor, and encodingStyle.

The attributes defined in the SOAP Header defines how a recipient should process the SOAP
message.
67

SOAP Header Attributes


The SOAP mustUnderstand attribute can be used to indicate whether a header entry is
mandatory or optional for the recipient to process.

If you add mustUnderstand="1" to a child element of the Header element it indicates that the
receiver processing the Header must recognize the element. If the receiver does not recognize
the element it will fail when processing the Header.

A SOAP message may travel from a sender to a receiver by passing different endpoints along the
message path. However, not all parts of a SOAP message may be intended for the ultimate
endpoint, instead, it may be intended for one or more of the endpoints on the message path.

The SOAP actor attribute is used to address the Header element to a specific endpoint.
The encodingStyle attribute is used to define the data types used in the document. This attribute
may appear on any SOAP element, and it will apply to that element's contents and all child

elements.

A SOAP message has no default encoding.


68

SOAP Body Element


The required SOAP Body element contains the actual SOAP message intended for the ultimate
endpoint of the message.

Immediate child elements of the SOAP Body element may be namespace-qualified.


<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body>
<m:GetPriceResponse xmlns:m="http://www.w3schools.com/prices">
<m:Price>1.90</m:Price>
</m:GetPriceResponse>
</soap:Body>
</soap:Envelope>

69

SOAP Fault Element


The SOAP Fault element holds errors and status information for a SOAP message.
The optional SOAP Fault element is used to indicate error messages.
If a Fault element is present, it must appear as a child element of the Body element. A Fault
element can only appear once in a SOAP message.

The SOAP Fault element has the following sub elements:


Sub Element

Description

<faultcode>

A code for identifying the fault

<faultstring>

A human readable explanation of the fault

<faultactor>

Information about who caused the fault to


happen

<detail>

Holds application specific error information


related to the Body element

70

SOAP Fault Element


The faultcode values defined below must be used in the faultcode element when describing
faults:

Error

Description

VersionMismatch Found an invalid namespace for the SOAP


Envelope element
MustUnderstand

An immediate child element of the Header


element, with the mustUnderstand attribute set
to "1", was not understood

Client

The message was incorrectly formed or


contained incorrect information

Server

There was a problem with the server so the


message could not proceed

71

SOAP Example
In the example below, a GetStockPrice request is sent to a server. The request has a StockName
parameter, and a Price parameter that will be returned in the response. The namespace for the
function is defined in http://www.example.org/stock

A SOAP Request:
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPrice>
<m:StockName>IBM</m:StockName>
</m:GetStockPrice>
</soap:Body>
</soap:Envelope>
72

SOAP Example
A SOAP Response:
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPriceResponse>
<m:Price>34.5</m:Price>
</m:GetStockPriceResponse>
</soap:Body>
</soap:Envelope>

73

What is WSDL
WSDL stands for Web Services Description Language
WSDL is an XML based protocol for information exchange in decentralized and distributed
environments.

WSDL is a language for describing how to interface with XML-based services.


WSDL is an XML language used to describe and locate web services

74

WSDL Elements
WSDL breaks down Web services into three specific, identifiable elements that can be combined
or reused once defined.

Following are the elements of WSDL document. Within these elements are further sub elements
or parts:

Definitions
Data Types
Message

Operation
Port Type
Binding
Port
Service

75

WSDL example
<definitions>
<types>
definition of types........
</types>
<message>
definition of a message....
</message>
<portType>
<operation>
definition of a operation.......
</operation>
</portType>

<binding>
definition of a binding....
</binding>
<service>
definition of a service....
</service>
</definitions>
76

WSDL example
<definitions name="HelloService"
targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<message name="SayHelloRequest">
<part name="firstName" type="xsd:string"/>
</message>
<message name="SayHelloResponse">
<part name="greeting" type="xsd:string"/>
</message>
<portType name="Hello_PortType">
<operation name="sayHello">
<input message="tns:SayHelloRequest"/>
<output message="tns:SayHelloResponse"/>
</operation>
</portType>

77

WSDL example
<binding name="Hello_Binding" type="tns:Hello_PortType">
<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="sayHello">
<soap:operation soapAction="sayHello"/>
<input>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</output>
</operation>
</binding>
<service name="Hello_Service">
<documentation>WSDL File for HelloService</documentation>
<port binding="tns:Hello_Binding" name="Hello_Port">
<soap:address
location="http://www.examples.com/SayHello/">
</port>
</service>
</definitions>

78

WSDL Definition Element


The <definition> element must be the root element of all WSDL documents. It defines the name
of the web service.

Here is the example piece of code from last session which uses definition element.
<definitions name="HelloService"

targetNamespace="http://www.examples.com/wsdl/HelloService.
wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
................................................
</definitions>
The namespace specification does not require that the document actually exist at the given
location. The important point is that you specify a value that is unique, different from all other
namespaces that are defined

79

WSDL Types Element


A Web service needs to define its inputs and outputs and how they are mapped into and out of
services. WSDL <types> element take care of defining the data types that are used by the web
service. Types are XML documents or document parts.
<types>
<schema
targetNamespace="http://example.com/stockquote.xsd"
xmlns="http://www.w3.org/2000/10/XMLSchema">
<element name="TradePriceRequest">
<complexType>
<all>
<element name="tickerSymbol" type="string"/>
</all>
</complexType>
</element>
<element name="TradePrice">
<complexType>
<all>
<element name="price" type="float"/>
</all>
</complexType>
</element>
</schema>
</types>
80

WSDL Message Element


The <message> element describes the data being exchanged between the Web service providers
and consumers.

Each message contains zero or more <part> parameters, one for each parameter of the Web
Service's function.

Each <part> parameter associates with a concrete type defined in the <types> container
element.
<message name="SayHelloRequest">
<part name="firstName"
type="xsd:string"/>
</message>
<message name="SayHelloResponse">
<part name="greeting"
type="xsd:string"/>
</message>
81

WSDL portType Element


The <portType> element combines multiple message elements to form a complete oneway or
round-trip operation.

For example, a <portType> can combine one request and one response message into a single
request/response operation. This is most commonly used in SOAP services. A portType can
define multiple operations.

<portType name="Hello_PortType">
<operation name="sayHello">
<input
message="tns:SayHelloRequest"/>
<output
message="tns:SayHelloResponse"/>
</operation>
</portType>

82

WSDL portType Element


WSDL has four transmission primitives that an endpoint can support:

One-way. The endpoint receives a message.


Request-response. The endpoint receives a message, and sends a correlated message.
Solicit-response. The endpoint sends a message, and receives a correlated message.
Notification. The endpoint sends a message.

83

WSDL Binding Element


The <binding> element provides specific details on how a portType operation will actually be
transmitted over the wire.

The bindings can be made available via multiple transports, including HTTP GET, HTTP POST, or
SOAP.

The bindings provide concrete information on what protocol is being used to transfer
portType operations

The bindings provide information where the service is located.


You can specify multiple bindings for a single portType.
For SOAP protocol, the binding is <soap:binding>, and the transport is SOAP messages on top of
HTTP protocol.

The binding element has two attributes - the name attribute and the type attribute.
<binding name="Hello_Binding" type="tns:Hello_PortType">

84

WSDL Binding Element


Here is the piece of code from Example section:
<binding name="Hello_Binding" type="tns:Hello_PortType">
<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="sayHello">
<soap:operation soapAction="sayHello"/>
<input>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:helloservice"
use="encoded"/>
</output>
</operation>
</binding>

85

WSDL Ports Element


A <port> element defines an individual endpoint by specifying a single address for a binding.
The port element has two attributes - the name attribute and the binding attribute.
A port MUST NOT specify more than one address.
A port MUST NOT specify any binding information other than address information.
<service name="Hello_Service">
<documentation>WSDL File for
HelloService</documentation>
<port binding="tns:Hello_Binding" name="Hello_Port">
<soap:address
location="http://www.examples.com/SayHello/">
</port>
</service>

86

WSDL Service Element


The <service> element defines the ports supported by the Web service. For each of the
supported protocols, there is one port element. The service element is a collection of ports.

The service element includes a documentation element to provide human-readable


documentation.

The name attribute provides a unique name among all services defined within in the enclosing
WSDL document.

Here is a piece of code from Example:


<service name="Hello_Service">
<documentation>WSDL File for
HelloService</documentation>
<port binding="tns:Hello_Binding" name="Hello_Port">
<soap:address
location="http://www.examples.com/SayHello/">
</port>
</service>

87

WSDL Summary
WSDL is an XML format for describing network services as a set of endpoints operating on
messages containing either document-oriented or procedure-oriented information.

A WSDL document is simply a set of definitions.


A WSDL is composed from several elements, each one with a specific role.

88

What is JSON
JSON stands for JavaScript Object Notation
JSON is a text format that is completely language independent but uses conventions that are
familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl,
Python, and many others.

JSON is smaller than XML, and faster and easier to parse.


The following example is an array of 3 employee records (objects):
{
"employees": [
{ "firstName":"John" , "lastName":"Doe"
},
{ "firstName":"Anna" ,
"lastName":"Smith" },
{ "firstName":"Peter" ,
"lastName":"Jones" }
]
}

89

JSON Structure
JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record,


struct, dictionary, hash table, keyed list, or associative array.

An ordered list of values. In most languages, this is realized as an array, vector, list, or
sequence.

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends
with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated

by , (comma).

{ "firstName":"John" , "lastName":"Doe"
},

90

JSON Structure
An array is an ordered collection of values. An array begins with [ (left bracket) and ends
with ] (right bracket). Values are separated by , (comma).

A value can be a string in double quotes, or a number, or true or false or null, or an object or
an array. These structures can be nested.

{
"employees": [
{ "firstName":"John" , "lastName":"Doe"
},
{ "firstName":"Anna" ,
"lastName":"Smith" },
{ "firstName":"Peter" ,
"lastName":"Jones" }
]
}

91

JSON vs XML
Below is a direct comparison between JSON and XML structures.
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },

{ "firstName":"Peter" , "lastName":"Jones" }
]
}

<employees>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employees>
<employees>
<firstName>Anna</firstName>
<lastName>Smith</lastName>
</employees>
<employees>
<firstName>Peter</firstName>
<lastName>Jones</lastName>
</employees>
92

JSON vs XML
Simple corresponding conversion patterns between XML and JSON.
Patter
n

XML

JSON

Access

<tag/>

"tag": null

o.tag

<tag>text</tag>

"tag": "text"

o.tag

<tag name="value" />

"tag":{"@name": "value"}

o.tag["@name"
]

<tag
name="value">text</tag>

"tag": { "@name": "value",


"#text": "text" }

o.tag["@name"
] o.tag["#text"]

<tag> <a>text</a>
<b>text</b> </tag>

"tag": { "a": "text", "b":


"text" }

o.tag.a o.tag.b

<tag> <a>text</a>
<a>text</a> </tag>

"tag": { "a": ["text", "text"] }

o.tag.a[0]
o.tag.a[1]

<tag> text <a>text</a>


</tag>

"tag": { "#text": "text", "a":


"text" }

o.tag["#text"]
o.tag.a

93

What is REST

Is an architecture style for designing networked applications focused on a system's


resources (including how resource states are addressed and transferred)

REST stands for Representational State Transfer


REST relies on a stateless, client-server, cacheable communications protocol (HTTP is
used)

REST is platform independent


REST is language independent

94

REST as Lightweight Web Services

REST is a lightweight alternative to mechanisms like RPC (Remote Procedure Calls)


and Web Services (SOAP, WSDL, etc.)

REST uses HTTP uniform interface (POST, GET, PUT, DELETE) for all four CRUD
(Create/Read/Update/Delete) operations

E.g. GET to retrieve (read) simple information

GET /employees/John HTTP/1.1

Host: myserver.com

Accept: application/xml

A REST Web Service can be very intuitive (easy to guess, self-documenting) when
addressing resources by exposing directory structure-like URIs

95

REST as Lightweight Web Services

Examples of CRUD operations made on a RESTful API

Create with HTTP POST

Output

POST /employee HTTP/1.1

A new employee entry is created with


firstName = John and lastName = Doe

Host: myserver.com
Content-Type:application/xml
<?xml version="1.0"?>
<employee>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employee>

Read with HTTP GET

GET /employee/John HTTP/1.1


Host: myserver.com
Content-Type: application/xml

Reads the employee entry


<?xml version="1.0"?>
<employee>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employee>

96

REST as Lightweight Web Services

Examples of CRUD operations made on a RESTful API

Update over HTTP PUT

PUT /employee/John HTTP/1.1


Host: myserver.com

Output

Updates the John Doe employee with


firstName to be Bob => the new entry will
be

Content-Type: application/xml
<?xml version="1.0"?>

<?xml version="1.0"?>

<employee>

<employee>

<firstName>Bob</firstName>

<firstName>Bob</firstName>

</employee>

<lastName>Doe</lastName>

Delete with HTTP DELETE

DELETE /employee HTTP/1.1


Host: myserver.com
Content-Type:application/xml

</employee>

Deletes the John Doe employee

<?xml version="1.0"?>
<employee>
<firstName>John</firstName>
<lastName>Doe</lastName>
</employee>
97

REST vs SOAP

REST

The RESTful Web services are completely stateless. This can be tested by restarting the server and
checking if the interactions are able to survive.

Restful services provide a good caching infrastructure over HTTP GET method (for most servers).
This can improve the performance, if the data the Web service returns is not altered frequently

and not dynamic in nature.

The service producer and service consumer need to have a common understanding of the context
as well as the content being passed along as there is no standard set of rules to describe the REST
Web services interface.

REST is particularly useful for restricted-profile devices such as mobile and PDAs for which the
overhead of additional parameters like headers and other SOAP elements are less.

REST services are easy to integrate with the existing websites and are exposed with XML so the
HTML pages can consume the same with ease. There is hardly any need to refactor the existing
website architecture. This makes developers more productive and comfortable as they will not
have to rewrite everything from scratch and just need to add on the existing functionality.

REST-based implementation is simple compared to SOAP.


98

REST vs SOAP

SOAP

The Web Services Description Language (WSDL) contains and describes the common
set of rules to define the messages, bindings, operations and location of the Web
service. WSDL is a sort of formal contract to define the interface that the Web service
offers.

SOAP requires less plumbing code than REST services design (e.g. transactions,
security, coordination, addressing, trust, etc.). Most real-world applications are not
simple and support complex operations, which require conversational state and
contextual information to be maintained. With the SOAP approach, developers need
not worry about writing this plumbing code into the application layer themselves.

SOAP Web services (such as JAX-WS) are useful in handling asynchronous processing
and invocation.

SOAP supports several protocols and technologies, including WSDL, XSDs, SOAP, WSAddressing
99

What is WADL
WADL stands for Web Application Description Language
WADL is a machine-readable XML description of HTTP-based (typically REST) web applications
WADL is intended to simplify the reuse of web services that are based on the existing HTTP
architecture of the Web

WADL is the REST equivalent of SOAP's WSDL, which can also be used to describe REST web
services

WADL was submitted to W3 consortium for standardization but is not yet recognized, nor widely
supported

WADL
100

WADL Elements

WSDL The service is described using a set of resource elements.

Each resource contains param elements to describe the inputs, and method elements which
describe the request and response of a resource

The request element specifies how to represent the input, what types are required and any

specific HTTP headers that are required

The response describes the representation of the service's response, as well as any fault
information, to deal with errors.

101

WADL application element

The application element forms the root of a WADL description and contains the following:

Zero or more doc elements


An optional grammars element
Zero or more resources elements
Zero or more of the following:

resource_type elements

method elements

representation elements

param elements

102

WADL documentation element (doc)

Each WADL-defined element can have one or more child doc elements that can be used
to document that element. The doc element has the following attributes:

xml:lang Defines the language for the title attribute value and the contents of the doc
element. If an element contains more than one doc element then they MUST have

distinct values for their xml:lang attribute.

title A short plain text description of the element being documented, the value
SHOULD be suitable for use as a title for the contained documentation. The doc
element has mixed content and may contain text and zero or more child elements that
form the body of the documentation. It is RECOMMENDED that the child elements be
members of the text, list or table modules of XHTML

103

WADL grammars element

The grammars element acts as a container for definitions of the format of data
exchanged during execution of the protocol described by the WADL document. Such
definitions may be included inline or by reference using the include element

It is permissible to include multiple definitions of a particular format: such definitions are


assumed to be equivalent and consumers of a WADL description are free to choose
amongst the alternatives or even combine them if they support that capability.

Include

The include element allows the definitions of one or more data format descriptions to be
included by reference. The href attribute provides a URI for the referenced definitions and is of
type xsd:anyURI. Use of the include element is logically equivalent to in-lining the referenced
document within the WADL grammars element.

104

WADL resource element

A resource element contains the following child elements:


Zero or more doc elements
Zero or more param elements with one of the following values for its style attribute:

Template, Query, Matrix , Header

Zero or more method elements


Zero or more resource elements that describe sub-resources

105

WADL method element

A method element describes the input to and output from an HTTP protocol method that
may be applied to a resource. A method element can either be a method definition or a
reference to a method defined elsewhere.

Method Reference

A method reference element is a child of a resource element that has an href attribute whose type is
xsd:anyURI. The value of the href attribute is a cross reference (see section 2.1 ) to a method definition
element. A method reference element MUST NOT have any other WADL-defined attributes or contain any
WADL-defined child elements.

106

WADL method element

Method Definition

A method definition element is a child of a resource or application element and has the following attributes:
name - Indicates the HTTP method used.
id - An identifier for the method, required for globally defined methods, not allowed on
locally embedded methods. Methods are identified by an XML ID and are referred to using
a URI reference.
It is permissible to have multiple child method elements that have the same value of the name
attribute for a given resource; such siblings represent distinct variations of the same HTTP method

and will typically have different input data.


A method element has the following child elements:
doc - Zero or more doc elements
request - Describes the input to the method as a collection of parameters and an optional resource

representation
response - Zero or more response elements that describe the possible outputs of the method

107

WADL Example (Yahoo News Search)


<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://wadl.dev.java.net/2009/02 wadl.xsd"
xmlns:tns="urn:yahoo:yn"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:yn="urn:yahoo:yn"
xmlns:ya="urn:yahoo:api"
xmlns="http://wadl.dev.java.net/2009/02">
<grammars>
<include href="NewsSearchResponse.xsd"/>
<include href="Error.xsd"/>
</grammars>
<resources base="http://api.search.yahoo.com/NewsSearchService/V1/">
<resource path="newsSearch">
<method name="GET" id="search">
<request>
<param name="appid" type="xsd:string" style="query" required="true"/>
<param name="query" type="xsd:string" style="query" required="true"/>
<param name="type" style="query" default="all">
<option value="all"/>
<option value="any"/>
<option value="phrase"/>
</param>

108

WADL Example (Yahoo News Search)


<param name="results" style="query" type="xsd:int" default="10"/>
<param name="start" style="query" type="xsd:int" default="1"/>
<param name="sort" style="query" default="rank">
<option value="rank"/>
<option value="date"/>
</param>
<param name="language" style="query" type="xsd:string"/>
</request>
<response status="200">
<representation mediaType="application/xml" element="yn:ResultSet"/>
</response>
<response status="400">
<representation mediaType="application/xml" element="ya:Error"/>
</response>
</method>
</resource>
</resources>
</application>

109

Testing with SoapUI

Create a SoapUI Project

Right click on the project node and select New SoapUI Project.

110

Functional Testing

In the New SoapUI Project dialog enter a project name (i.e. Country_info) and click OK.

Right click on the project node and select Add WSDL.

111

Functional Testing

The Add WSDL dialog is now open

Enter http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL.
Click OK.

112

Functional Testing

Now see that the WSDL was successfully added to the


project by seeing the operations in the Web Service in
the navigatorEnter

113

Functional Testing

Create a request from your WSDL

Click on the plus sign next to the web service in the navigator to expand.

Double click on the request.

You now have to enter your data manually in the code editor as shown below. Replace ? with RO (without
quotes)

114

Functional Testing

Run a request to the Web Service

Click on the green arrow head sign to submit the request.

115

Functional Testing

Receive response

On the right side of the window the response will be displayed.

116

Functional Testing

Run an invalid request to the Web Service.

Introduce a wrong country code (like ZZ).


Click on the green arrow head sign to submit the request.

The response of the Web Service will indicate that the country was not found.
After seeing the result, correct the input data.

117

Functional Testing

Create a Test Case from a request.

In the request editor, select Add This Request to TestCase.

118

Functional Testing

Next step:

Adding a request to a TestCase will open the Create TestSuite dialog box. Enter a name for your TestSuite
and click OK.

After clicking OK, you will be asked to create a TestCase. In the Create TestCase dialog, enter a name for your
TestCase and click OK.

119

Functional Testing

Next step:

The dialog box Add Request to TestCase will appear. Click OK.

120

Functional Testing

Final step:

SoapUI will now generate a TestSuite and TestCase for you while the request will be added as a TestRequest.
Below is a copy of the request that appears in the interface. A TestCase editor will also open with your new
TestRequest.

The next step is to validate the response in your test by adding an Assertion.

121

Functional Testing

Add an Assertion to the test:

Now that we've created and run our first test, we are going to add a validation of the response. In SoapUI,
this is called adding an assertion.

Examples of assertions that is possible in SoapUI are:

Schema Compliance
Simple Contains
Simple Not Contains
SOAP Faults
Response SLA
XPath Match
XQuery Match
WS Security Status
WS-Addressing Request/Response Assertion
Script Assertion
122

Functional Testing

Close all windows you have open in SoapUI before starting:

Double Click on your Test Request as shown below. This will open the request editor.

After clicking OK, you will be asked to create a TestCase. In the Create TestCase dialog, enter a name for your
TestCase and click OK.

123

Functional Testing

Next step:

Select Response SLA from the Add Assertion menu.

In the Configure Response SLA Assertion dialog box, write 500 and click OK. This will validate that the
response of the SLA is under 500.

124

Functional Testing

Next step:

Now that you've added the assertion, you are going to run the request to validate the response. If all
assertions are successful, the SOAP icon should turn green in three places as shown below.

125

Functional Testing

Validate response with XPath Match:

Select XPath Match from the Add Assertion menu.

126

Functional Testing

Validate response with XPath Match:

In the XPath Match Configuration press Declare button and write below //m:CapitalCityResult

Click Select from current and you should see the word Bucharest appearing in the Expected Results field.
Click Save

127

Functional Testing

Final step:

Now that you've added a new assertion, you are going to run the test again. If all assertions are successful,
the SOAP icon should turn green in three places as shown below.

128

Service Mocking

Service Mocking, or simulation, is the practice of creating a facsimile environment that works similar to the
environment youre facsimileing.

When to use it: You should use mocks when you cant use the real thing
Advantages:

You can create tests in advance.


Teams can work in parallel.
You can create proof of concepts or demos.
You can isolate systems.
You can write test for resource not accessible.
Mock can be delivered to the customer.

Disadvantages:

You have to do Double work.


Deployment constraints.
Its not live is it?

129

Service Mocking

Start a new SoapUI project using the following wsdl:


http://www.webservicex.net/CurrencyConvertor.asmx?WSDL

Click OK button.

130

Service Mocking

Right-click on one of the SOAP interfaces and select Generate MockService.

131

Service Mocking

In the dialog Generate Mock Service you can specify the local port/path for the service you're creating but for
the moment just click OK

132

Service Mocking

Enter the name of your Mock Service in the Name dialog and click OK. For example: Mock convertor

After creating the MockService, you should get a MockService with one operation and one request.

As you can see, the Icons are Grey and inactive. This is an indication that the MockService is not yet running. We
have successfully created our first MockService.

133

Service Mocking

Now, double click on the MockService to see the MockService editor. In the editor we can see a list of all
operations for the service, as well as a request and response log which logs all incoming requests that have
been handled by the MockService.

Double Click on the Conversion Rate Operation to see the MockResponses we have in the MockService

134

Service Mocking

As you can see we do only have one, Let's edit it, double click on it to open the Response Editor

The MockResponse editor is very similar to the standard SoapUI Request editor , but instead of requests, we'll
edit responses. The Incoming Request view is still very useful; it shows the last received request to the
operation which is useful for debugging client calls, including attachments and HTTP headers.

Edit the ConversionRateResult to be something else than the default empty value "?. For example: 2.5

135

Service Mocking

First we must start the MockService. Click the Start button in the MockService editor, the green arrow head ,
this will start the service on the configured port and path

To the Top Right of the Editor you should see that it's running, and the port it's responding on. The play Button
is greyed out and if you would like to stop the MockService, just click the stop button.

136

Service Mocking

Now in the MockResponse editor, Click the Button Create Request.

This will prompt you to open one of the existing requests for its operation in your project.

You will also need to give it a name.

137

Service Mocking

When you open the request, SoapUI will automatically change its endpoint to the endpoint of the locally
running MockService instead of the endpoint that the WSDL is using. Submit the opened request by clicking the
Run Button

As you can see the MockService returned the values we entered earlier as the response.

138

Service Mocking

Let's continue by making the created MockResponse a bit more dynamic by changing the dispatch and
by Groovy scripting.

First well create a second MockResponse.

Give it a Groovy Name

139

Service Mocking

Let's write a script for the response. Click the Script tab in the Response and enter the following Groovy Script,
context.setProperty( "rate", Math.random() )
It will look like this:

This script sets a property called rate to a random number. As you might have noticed we do not use the
property rate anywhere, so let's add it.
140

Service Mocking

In the ConversionRateResult element enter the following: ${rate}


This is called a Property expansion and it's a very powerful feature in SoapUI. By inserting a property expansion
in any element you can then fill the element programmatically. Basically it tells SoapUI to use the current value

of property rate.

Now that we have written a script and the random results will be inserted into the response.

141

The End

Thank You

142

You might also like