Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 170

Lesson 1

Web 2.0 An Introduction


1.1 Lesson Objectives
The concept of Web 2.0 is a new definition of the Web and the internet, that aims to
enhance creativity, information sharing and user collaboration. This lesson
introduces
the key characteristics of Web 2.0. Important developments in web technology such
as
the SaaS (Software as a service) model and multiple delivery channels are also
discussed in this lesson. The lesson also provides an explanation of internet based
folksonomies and social networking.

1.2 What is Web 2.0?

Web 2.0 is a term that describes the trend in the use of World Wide Web technology
and web design that aims to enhance creativity, information sharing, and, most
notably,
collaboration among users. These concepts have led to the development and
evolution
of web-based communities and hosted services, such as social-networking sites,
wikis,
blogs, and folksonomies.
Web 2.0 is the business revolution in the computer industry caused by the move
to the Internet as platform, and an attempt to understand the rules for success on
that
new platform.

Fig 1.2 Evolution of the Web

1.2.1 Types of Web 2.0 applications


Level-3 applications These are the most "Web 2.0"-oriented applications and only
exist on the Internet. Level-3 applications derive their effectiveness from interhuman
connections and from the network effects that Web 2.0 makes possible. These
applications grow in effectiveness as people make more use of them. Examples
include
eBay, Craigslist, Wikipedia, del.icio.us, Skype, dodgeball, and AdSense.
Level-2 applications - These can operate offline but gain advantages from going
online.
An example of a Level-2 application is Flickr, which benefits from its shared
photodatabase
and from its community-generated tag database.
Level-1 applications These can operate offline but gain features online. Examples
include Google Docs & Spreadsheets and iTunes music store.
Level-0 applications These work both offline and online. The examples are
MapQuest,
Yahoo! Local, and Google Maps (mapping-applications using contributions from
users to
advantage could rank as "level 2").

Figure 1.2.1 Features of Web 2.0

1.2.2 Characteristics of Web 2.0


Rich user experience
User participation
Dynamic content
Metadata
Web standards and scalability
Openness
Freedom
Collective intelligence by way of user participation

1.3 Folksonomies and Web 2.0


Folksonomy is the practice and method of collaboratively creating and managing
tags to annotate and categorize content. Folksonomy is also known as collaborative
tagging, social classification, social indexing, and social tagging. In contrast to
traditional
subject indexing, metadata is generated not only by experts but also by creators
and
consumers of the content. Usually, freely chosen keywords are used instead of a

controlled vocabulary. The term Folksonomy is a blend of the words folk and
taxonomy. Hence, a folksonomy is a user-generated taxonomy.
Folksonomies became popular on the Web around 2004 with social software
applications such as social bookmarking or annotating photographs. Websites that
support tagging and the principle of folksonomy are referred to in the context of
Web
2.0 because participation is very easy and tagging data is used in new ways to find
information. For example, tag clouds are frequently used to visualize the most used
tags
of a folksonomy. The term folksonomy is also used to denote only the set of tags
that
are created in social tagging.
Typically, folksonomies are Internet-based, although they are also used in
other
contexts. Folksonomic tagging is intended to make a body of information
increasingly
easy to search, discover, and navigate over time. A well-developed folksonomy is
ideally
accessible as a shared vocabulary that is both originated by, and familiar to, its
primary
users. Two widely cited examples of websites using folksonomic tagging are Flickr
and
del.icio.us, although it has been suggested that Flickr is not a good example of
folksonomy.
As folksonomies develop in Internet-mediated social environments, users can
(generally) discover who created a given folksonomy tag, and see the other tags
that
this person created. In this way, folksonomy users often discover the tag sets of
another
user who tends to interpret and tag content in a way that makes sense to them. The
result is often an immediate and rewarding gain in the user's capacity to find related
content (a practice known as "pivot browsing).
Folksonomy creation and searching tools are not part of the underlying World
Wide Web protocols. Folksonomies arise in Web-based communities where
provisions
are made at the site level for creating and using tags. These communities are
established to enable Web users to label and share user-generated content, such as
photographs, or to collaboratively label existing content, such as Web sites, books,
works in the scientific and scholarly literatures, and blog entries.

Figure 1.3 Folksonomies

1.4 Software as a service


Software as a service (SaaS, typically pronounced 'Sass') is a model of software
deployment where an application is hosted as a service provided to customers
across
the Internet.
SaaS eliminates the need to install and run the application on the
customer's
own computer. As a result, SaaS eases the customer's burden of software
maintenance,
operation, and support. Conversely, customers relinquish control over software
versions
or changing requirements; moreover, costs to use the service become a continuous
expense, rather than a single expense at time of purchase. Using SaaS can also
reduce
the expense of software purchases, through less costly, on-demand pricing. From
the
software vendor's standpoint, SaaS has the attraction of providing stronger
protection of
its intellectual property and establishing an ongoing revenue stream. The SaaS
software
vendor may host the application on its own web server, or this function may be
handled
by a third-party application service provider (ASP). This way, end users may reduce
their
investment on server hardware too.

1.4.1 History
The concept of "software as a service" started to circulate prior to 1999 and was
considered to be "gaining acceptance in the marketplace" in Bennett et al., 1999
paper
on "Service Based Software".
Whilst the term "software as a service" was in common use, the CamelCase

acronym "SaaS" was not coined until several years later in a white paper called
"Strategic Backgrounder: Software as a Service" by the Software & Information
Industry's eBusiness Division published in Feb. 2001, but written in fall of 2000
according to internal Association records.

1.4.2 Philosophy of SaaS


As a term, SaaS is generally associated with business software and is typically
thought of as a low-cost way for businesses to obtain the same benefits of
commercially
licensed, internally operated software without the associated complexity and high
initial
cost. Consumer-oriented web-native software is generally known as Web 2.0 and not
as
SaaS. Many types of software are well suited to the SaaS model, where customers
may
have little interest or capability in software deployment, but do have substantial
computing needs. Application areas such as Customer relationship management
(CRM),
video conferencing, human resources, IT service management, accounting, web
analytics, web content management and e-mail are some of the initial markets
showing
SaaS success.
The distinction between SaaS and earlier applications delivered over the
Internet is that SaaS solutions were developed specifically to leverage web
technologies
such as the browser, thereby making them web-native. The data design and
architecture of SaaS applications are specifically built with a 'multi-tenant' backend,
thus
enabling multiple customers or users to access a shared data model. This further
differentiates SaaS from client/server or 'ASP' (Application Service Provider)
solutions in
that SaaS providers are leveraging enormous economies of scale in the deployment,
management, support and through the Software Development Lifecycle.

1.4.3 Key characteristics of


software delivered by SaaS
The key characteristics of SaaS software, according to IDC, include:

Network-based access to, and management of, commercially available


software
activities that are managed from central locations rather than at each
customer's
Site.
Enabling customers to access applications remotely via the Web application
delivery that typically is closer to a one-to-many model (single instance,
multitenant
architecture) than to a one-to-one model, including architecture, pricing,
partnering, and management characteristics.
Centralized feature updating, which eliminates the need for downloadable
patches and upgrades.
SaaS applications are generally priced on a per-user basis, sometimes with a
relatively small minimum number of users and often with additional fees for
extra
bandwidth and storage. SaaS revenue streams to the vendor are therefore
lower
initially than traditional software license fees, but are also recurring, and
therefore viewed as more predictable, much like maintenance fees for licensed
software.

1.4.4 SaaS Implementation


According to Microsoft, SaaS architectures generally can be classified as belonging
to
one of four "maturity levels," whose key attributes are configurability, multi-tenant
efficiency, and scalability. Each level is distinguished from the previous one by the
addition of one of those three attributes:
Level 1 - Ad-Hoc/Custom: At the first level of maturity, each customer has its own
customized version of the hosted application and runs its own instance of the
application
on the host's servers. Migrating a traditional non-networked or client-server
application
to this level of SaaS typically requires the least development effort and reduces
operating costs by consolidating server hardware and administration.
Level 2 - Configurable: The second maturity level provides greater program
flexibility
through configurable metadata, so that many customers can use separate instances
of

the same application code. This allows the vendor to meet the different needs of
each
customer through detailed configuration options, while simplifying maintenance and
updating of a common code base.
Level 3 - Configurable, Multi-Tenant-Efficient: The third maturity level adds
multitenancy
to the second level, so that a single program instance serves all customers. This
approach enables more efficient use of server resources without any apparent
difference
to the end user, but ultimately is limited in its scalability.
Level 4 - Scalable, Configurable, Multi-Tenant-Efficient: At the fourth and final SaaS
maturity level, scalability is added through a multitier architecture supporting a
loadbalanced
farm of identical application instances, running on a variable number of
servers. The system's capacity can be increased or decreased to match demand by
adding or removing servers, without the need for any further alteration of
application
software architecture.
Virtualization also may be used in SaaS architectures, either in addition to
multitenancy,
or in place of it. One of the principal benefits of virtualization is that it can
increase the system's capacity without additional programming. On the other hand,
a
considerable amount of programming may be required to construct a more efficient,
multi-tenant application. Combining multi-tenancy and virtualization provides still
greater
flexibility to tune the system for optimal performance. In addition to full operating
system-level virtualization, other virtualization techniques applied to SaaS include
application virtualization and virtual appliances.
Various types of software components and frameworks may be employed in the
development of SaaS applications. These tools can reduce the time to market and
cost
of converting a traditional on-premise software product or building and deploying a
new
SaaS solution. Examples include components for subscription management, grid
computing software, web application frameworks, and complete SaaS platform
products.

1.5 Multiple Delivery Channels


(Voice-VOXML and ANT(HTML))

1.5.1 What is VoiceXML?


VoiceXML is a Web-based markup language for representing human computer
dialogs using audio output devices (computer-synthesized and/or recorded) and
audio
input device (voice and/or keypad tones).

1.5.2 Architectural Model

Figure 1.5.2 VoiceXML Architectural Model


Document Server:
process request form a client,ex. a web server.
VoiceXML Interpreter: process VoiceXML documents and conduct the dialog.
VoiceXML Interpreter Context: acquire VoiceXML documents, detect and
answer
calls.

Implementation Platform : controlled by VoiceXML Interpreter Context and

VoiceXML
Interpreter;generate events in response to user actions and system
events;require: audio output(TTS, audio files),audio input (SR,audio record, DTMF).

1.5.3 Voice applications

Information retrieval
Electronic transactions
Telephone services Call centers
Voice e-mail
Voice Access Control Voice Recognition

1.5.4 VoiceXML History

Figure 1.5.4 VoiceXML History

1.5.5 Usage
Many commercial VoiceXML applications have been deployed, processing millions
of telephone calls per day. These applications include: order inquiry, package
tracking,
driving directions, emergency notification, wake-up, flight tracking, voice access to
email, customer relationship management, prescription refilling, audio
newsmagazines,
voice dialing, real-estate information and national directory assistance applications.
VoiceXML has tags that instruct the voice browser to provide speech synthesis,
automatic speech recognition, dialog management, and audio playback. The
following is
an example of a VoiceXML document:

<vxmlversion="2.0"xmlns="http://www.w3.org/2001/vxml">
<form>
<block>
<prompt>
Helloworld!
</prompt>
</block>
</form>
</vxml>

When interpreted by a VoiceXML interpreter this will output "Hello world" with
synthesized speech.
Typically, HTTP is used as the transport protocol for fetching VoiceXML pages.
Some applications may use static VoiceXML pages, while others rely on dynamic
VoiceXML page generation using an application server like Tomcat, Weblogic, IIS, or
WebSphere. In a well-designed web application, the voice interface and the visual
interface share the same back-end business logic.

1.6 Social networking


A social network is a social structure made of nodes (which are generally individuals
or organizations) that are tied by one or more specific types of interdependency,
such as
values, visions, ideas, financial exchange, friendship, kinship, dislike, conflict or
trade.
The resulting structures are often very complex.

Figure 1.6 Social networking

A social network is a description of the social structure between actors, mostly


individuals or organizations. It indicates the ways in which they are connected
through
various social familiarities ranging from casual acquaintance to close familiar
bonds.
Social network analysis views social relationships in terms of nodes and ties. Nodes
are the individual actors within the networks, and ties are the relationships between
the
actors. There can be many kinds of ties between the nodes. Research in a number
of
academic fields has shown that social networks operate on many levels, from
families up
to the level of nations, and play a critical role in determining the way problems are
solved, organizations are run, and the degree to which individuals succeed in
achieving
their goals.
In its simplest form, a social network is a map of all of the relevant ties between the
nodes being studied. The network can also be used to determine the social capital
of
individual actors. These concepts are often displayed in a social network diagram,
where
nodes are the points and ties are the lines.

1.7 Summary
The advent of Web 2.0 has led to the development and evolution of web-based
communities and hosted services, such as social-networking sites, wikis, blogs,
and folksonomies. There are four kinds of Web 2.0 applications.
Websites that support tagging and the principle of folksonomy became popular
around 2004. Such websites are referred to in the context of Web 2.0 because
participation is very easy and tagging data is used in new ways to find
information.
Creation of web services standards such as XML has enabled the web to
transform into platform for building services. This phenomenon known as Web
2.0 provides the rich environment for SaaS (Software As A Service) providers to
succeed.
The emergence of Web 2.0 has led to the creation of a new generation of web
applications built around web services.

VoiceXML is becoming the standard language used for developing interactive


voice enabled applications.

Lesson 2
Programming web clients
2.1 Lesson Objectives
The Web 2.0 architecture offers new ways for major client side technologies to work
together.
This lesson first explores the technologies used to create Web 2.0 applications. This
includes a
detailed look at JavaScript and CSS (Cascading Style Sheets). Next, the lesson
provides an
explanation of the XML (eXtensible Markup Language) , XML Schema datatypes and
XSLT
constructs using easy to understand examples. The lesson also provides an
understanding of
SAX and DOM parsers.

2.2 Client side programming


Client side programs are the programs on the World Wide Web (or simply Web) that
are
executed client-side i.e. on the users browser, whereas the server side programs on
the Web
are executed on the server machine which hosts that particular web application.
Client side programs provide dynamic behavior to the client by executing a program
on the
browser. The most common purpose of client side programs is to verify the user
data i.e.
whether the user entered appropriate data or not and to ensure whether the user
filled
mandatory fields or not. The most common tools used for client side programming
are scripting

languages like JavaScript, VBScript, Jscript, etc.

2.3 An overview of Javascript


JavaScript was developed by Brendan Eich at Netscape. JavaScript was first
introduced and
deployed in the Netscape browser version 2.0B3 in December 1995. Like any other
scripting
language Javascript is also a light-weight programming language, even though it
provides
several features, few of the features are as follows:
A Great Programming Tool for HTML.
Professional Web designers are undoubtedly adept in using HTML and proficient in
website
design but not necessarily skillful in computer programming. JavaScript is a
programming tool
for such a situation. JavaScript is a powerful scripting language that helps HTML
designers to
effectively and interactively design websites and web pages in a very simple and
efficient way.
Simple to learn.
JavaScript is not a complex language like procedural and OO languages. It has
simple
rules and procedures that make it easier to learn for programmers. Because of its
simplicity it
became popular client-side scripting language.
Handles dynamic effects.
JavaScript has features to achieve dynamic effects in web pages. Using the features
available in JavaScript, the designer can decide to have dynamically placed text at
run
time.
Browser detection.
This feature detects client browser. This feature of JavaScript helps to achieve
independent
platforms. JavaScript can detect the type and version of browser the visitor is using
and
programmatically switch the page to show customized pages designed for different
browsers.
By using browser detection feature of JavaScript, the designer gets better control
over the
browser.
Saves time.
JavaScript has the feature of validating data submitted by the client at the client
side itself. This
helps in saving the processing time of the server because there is no need to
transfer form data

from client to server several times.


DOM.
Client side JavaScript is embedded into HTML; this embedded JavaScript is used
along with
DOM (Document Object Model) for control over the browser by means of objects.
Interpreted language
Javascript is an interpreted language, meaning that it can be executed without any
compilation.
Structured programming
JavaScript supports almost all the structured programming features/syntax.

2.4 Javascript objects


Javascript is an Object-Oriented Programming language. Similar to any other OOP
language,
javascript also provides built-in objects and also enables the programmer to define
his/her own
objects. Here in the following sections we will discuss few built-in Javascript objects.

2.4.1 String
The String object is used to manipulate a string literal. The properties and methods
of String
objects are shown below.

String object properties


Property

Description

Constructor

A reference to the function that created the object

Length
Prototype

Returns the number of characters in a string


Allows you to add properties and methods to the
object

String object methods

Method
anchor()
big()

Description
Creates an HTML anchor
Displays a string in a big font

blink()
bold()
charAt()
charCodeAt()

Displays a blinking string


Displays a string in bold
Returns the character at a specified position
Returns the Unicode of the character at a specified
position
Joins two or more strings
Displays a string as teletype text
Displays a string in a specified color
Displays a string in a specified size
Takes the specified Unicode values and returns a
string
Returns the position of the first occurrence of a
specified string value in a string
Displays a string in italic
Returns the position of the last occurrence of a
specified string value, searching backwards from
the specified position in a string
Displays a string as a hyperlink
Searches for a specified value in a string
Replaces some characters with some other
characters in a string
Searches a string for a specified value
Extracts a part of a string and returns the extracted
part in a new string
Displays a string in a small font
Splits a string into an array of strings
Displays a string with a strikethrough
Displays a string as subscript
Extracts a specified number of characters in a
string, from a start index
Extracts the characters in a string between two
specified indices
Displays a string as superscript
Displays a string in lowercase letters
Displays a string in uppercase letters
Represents the source code of an object
Returns the primitive value of a String object

concat()
fixed()
fontcolor()
fontsize()
fromCharCode()
indexOf()
italics()
lastIndexOf()

link()
match()
replace()
search()
slice()
small()
split()
strike()
sub()
substr()
substring()
sup()
toLowerCase()
toUpperCase()
toSource()
valueOf()

Example 1: The following example prints the length of a given string.


<html>
<body>
33++<script type="text/javascript">
var txt="Good Morning";
document.write(Length of the string=+txt.length);
</script>
</body>
</html>
Running the above code will print Length of the string=10. (Type the code in an
HTML
document and then render it using any web browser).
Example 2: The following example replaces the string Morning with
Evening.
<html>
<body>
<script type="text/javascript">
var str="Good Morning";
document.write(str.replace(/Morning/,"Evening"));
</script>
</body>
</html>
Running the above code will print Good Evening. (Type the code in an HTML
document and
then render it using any web browser).

2.4.2 Date:
The Date object is used to work with data and time. The properties and methods of
Date Object
are shown below.

Date object properties


Property

Description

Constructor
Prototype

A reference to the function that created the object


Allows you to add properties and methods to the
object

Date object methods

Method
Date()
getDate()
getDay()
getMonth()
getFullYear()
getYear()

getHours()
getMinutes()
getSeconds()
getMilliseconds()
getTime()
getTimezoneOffset()
getUTCDate()

getUTCDay()

getUTCMonth()

getUTCFullYear()

getUTCHours()

Description
Returns today's date and time
Returns the day of the month from a Date object (from 131)
Returns the day of the week from a Date object (from 0-6)
Returns the month from a Date object (from 0-11)
Returns the year, as a four-digit number, from a Date
object
Returns the year, as a two-digit or a three/four-digit
number,
depending on the browser. Use getFullYear() instead !!
Returns the hour of a Date object (from 0-23)
Returns the minutes of a Date object (from 0-59)
Returns the seconds of a Date object (from 0-59)
Returns the milliseconds of a Date object (from 0-999)
Returns the number of milliseconds since midnight Jan 1,
1970
Returns the difference in minutes between local time and
GreenwichMean Time (GMT)
Returns the day of the month from a Date object
according to
universal time (from 1-31)
Returns the day of the week from a Date object
according to
universal time (from 0-6)
Returns the month from a Date object according to
universal
time9 (from 0-11)
Returns the four-digit year from a Date object according
to
universal time
Returns the hour of a Date object according to universal
time

getUTCMinutes()

getUTCSeconds()

getUTCMilliseconds()

parse()

setDate()
setMonth()
setFullYear()
setYear()
setHours()
setMinutes()
setSeconds()
setMilliseconds()
setTime()

setUTCDate()

setUTCMonth()

setUTCFullYear()

setUTCHours()

setUTCMinutes()

setUTCSeconds()

setUTCMilliseconds()

(from 0-23)
Returns the minutes of a Date object according to
universal time
(from 0-59)
Returns the seconds of a Date object according to
universal time
(from 0-59)
Returns the milliseconds of a Date object according to
universal
time(from 0999)
Takes a date string and returns the number of
milliseconds since
midnight of January 1, 1970
Sets the day of the month in a Date object (from 1-31)
Sets the month in a Date object (from 0-11)
Sets the year in a Date object (four digits)
Sets the year in the Date object (two or four digits). Use
setFullYear() instead
Sets the hour in a Date object (from 0-23)
Set the minutes in a Date object (from 0-59)
Sets the seconds in a Date object (from 0-59)
Sets the milliseconds in a Date object (from 0-999)
Calculates a date and time by adding or subtracting a
specified
number of milliseconds to/from midnight January 1,
1970
Sets the day of the month in a Date object according to
universal
time (from 1-31)
Sets the month in a Date object according to universal
time
(from 0-11)
Sets the year in a Date object according to universal
time
(four digits)
Sets the hour in a Date object according to universal
time
(from 0-23)
Set the minutes in a Date object according to universal
time
(from 0-59)
Set the seconds in a Date object according to universal
time
(from 0-59)
Sets the milliseconds in a Date object according to

universal
time (from 0-999)
Represents the source code of an object
Converts a Date object to a string
Converts a Date object, according to Greenwich time,
to a
string. Use to UTCString() instead !!
Converts a Date object, according to universal time, to a
string
Converts a Date object, according to local time, to a
string
Takes a date and returns the number of milliseconds
since
midnight of January 1, 1970 according to universal time
Returns the primitive value of a Date object

toSource()
toString()
toGMTString()

toUTCString()
toLocaleString()
UTC()

valueOf()

2.4.3 Array
The Array Object is a collection of multiple values. The properties and methods of
Array object
are shown below.

Array object properties


Property
Constructor
Length
prototype

Description
A reference to the function that created the object
Sets or returns the number of elements in an array
Allows you to add properties and methods to the object

Array object methods


Method
concat()
join()
pop()
push()

reverse()
shift()
slice()
sort()

Description
Joins two or more arrays and returns the result
Puts all the elements of an array into a string. The elements are
separated by a specified delimiter
Removes and returns the last element of an array
Adds one or more elements to the end of an array and returns the
new
length
Reverses the order of the elements in an array
Removes and returns the first element of an array
Returns selected elements from an existing array
Sorts the elements of an array

splice()
toSource()
toString()
unshift()

valueOf()

Removes and adds new elements to an array


Represents the source code of an object
Converts an array to a string and returns the result
Adds one or more elements to the beginning of an array and
returns the
new length
Returns the primitive value of an Array object

2.4.4 Boolean
The Boolean object is a wrapper for a Boolean value (true, false). The properties and
methods
of Boolean object are shown below.

Boolean object properties


Property
Constructor
prototype

Description
A reference to the function that created the object
Allows you to add properties and methods to the object

Boolean object methods


Method
toSource()
toString()
valueOf()

Description
Represents the source code of an object
Converts a Boolean value to a string and returns the result
Returns the primitive value of a Boolean object

2.4.5 Math
The Math object enables the programmer to perform several mathematical
operations. The
properties and methods of the Math Object are as under.

Math object properties


Property
Constructor
E
LN2
LN10
LOG2E
LOG10E
PI

Description
A reference to the function that created the object
Returns Euler's constant (approx. 2.718)
Returns the natural logarithm of 2 (approx. 0.693)
Returns the natural logarithm of 10 (approx. 2.302)
Returns the base-2 logarithm of E (approx. 1.414)
Returns the base-10 logarithm of E (approx. 0.434)
Returns PI (approx. 3.14159)

Prototype
SQRT1_2
SQRT2

Allows you to add properties and methods to the object


Returns the square root of 1/2 (approx. 0.707)
Returns the square root of 2 (approx. 1.414)

Math object methods


Method
abs(x)
acos(x)
asin(x)
atan(x)

atan2(y,x)

ceil(x)
cos(x)
exp(x)
floor(x)

log(x)
max(x,y)
min(x,y)
pow(x,y)
random()
round(x)
sin(x)
sqrt(x)
tan(x)
toSource()
valueOf()

Description
Returns the absolute value of a number
Returns the arccosine of a number
Returns the arcsine of a number
Returns the arctangent of x as a numeric value between -PI/2
and PI/2
radians
Returns the angle theta of an (x,y) point as a numeric value
between
PI and PI radians
Returns the value of a number rounded upwards to the
nearest integer
Returns the cosine of a number
Returns the value of Ex
Returns the value of a number rounded downwards to the
nearest
integer
Returns the natural logarithm (base E) of a number
Returns the number with the highest value of x and y
Returns the number with the lowest value of x and y
Returns the value of x to the power of y
Returns a random number between 0 and 1
Rounds a number to the nearest integer
Returns the sine of a number
Returns the square root of a number
Returns the tangent of an angle
Represents the source code of an object
Returns the primitive value of a Math object

2.5 Regular Expressions


JavaScript 1.2 and later versions has built-in support for regular expressions. Most
web
browsers support JavaScript 1.2. If you use JavaScript to validate user input on a
web page at
the client side, using JavaScript's regular expression support will reduce the amount
of code you need to write. The following sections will help you to understand/learn
what is a Regular

expression, how to define regular expressions, methods of the regular expression


object, etc.

2.5.1 What is a regular expression?


A Regular Expression is a pattern that enables you to describe the type of string you
want to
search inside some text or in other words the regular expression object is used to
store the
search pattern.

2.5.2 How to define a regular expression?


Several constructs are used to define/construct a regular expression. Some of these
contructs
are discussed in the following sections.
Character classes
Construct
[abc]
[^abc]
[a-zA-Z]
[a-d[m-p]]
[a-z&&[def]]
[a-z&&[^bc]]
[a-z&&[^m-p]]

Matches
a, b, or c (simple class)
Any character except a, b, or c (negation)
a through z or A through Z, inclusive (range)
a through d, or m through p: [a-dm-p] (union)
d, e, or f (intersection)
a through z, except for b and c: [ad-z]
(subtraction)
a through z, and not m through p: [a-lq-z]
(subtraction)

Predefined character classes


Construct
\d
\D
\s
\S
\w
\W
Boundary matchers

Matches
A digit: [0-9]
A non-digit: [^0-9]
A whitespace character: [ \t\n\x0B\f\r]
A non-whitespace character: [^\s]
A word character: [a-zA-Z_0-9]
A non-word character: [^\w]

Character
^
$
\b
\B
\A
\G
\Z
\z

Matches
The beginning of a line
The end of a line
A word boundary
A non-word boundary
The beginning of the input
The end of the previous match
The end of the input but for the final
terminator, if any
The end of the input

Regular Expression Object Methods


Method
compile
exec

test
search

match

replace
split

Description
Change the regular expression (what to search
for)
Search a string for a specified value. Returns the
found
value and remembers the position
Search a string for a specified value. Returns true
or false
Search a string for a specified value. Returns the
position
of the value
Search a string for a specified value. Returns an array of
the found
value(s)
Replace characters with other characters
Split a string into an array of strings

Example 1: The following example makes use of a regular expression object.


Running the code
will replace the string Dollar with Rupee.
<HTML>
<script type="text/javascript">
var str = "A Dollar saved is a Dollar earned";
var search_string=new RegExp("Dollar");
var result = str.replace(search_string, "Rupee");
document.write(result);
</script>
</HTML>

2.6 Cascading Style Sheets(CSS)

2.6.1 Introduction to CSS


CSS stands for Cascading Style Sheets. CSS is an extension to basic HTML that
allows you to
style your web pages. An example of a style change would be to make words italic.
In standard
HTML you would use the <i> tag like so:
<i>HelloWorld</i>
There is nothing wrong in the above usage, but if you want to change all the
italicized
paragraphs to bold, you would have to go to every paragraph in the document and
change the
<i> tag to <b>.
Another disadvantage can be found in this example: say you wanted to make the
above text
italic, make the font style Arial and change its color to blue; you would need a lot of
code
wrapped around the text:
<fontcolor="blue"face="Arial"><i>HelloWorld</i></font>
This is verbose and contributes to making you HTML messy. With CSS, you can
create a custom
style elsewhere and set all its properties, give it a unique name and then tag your
HTML to
apply these stylistic properties:
<pclass="myNewStyle">MyCSSstyledtext</p>
And in between the <head></head> tags at the top of your web page you would
insert this
CSS code that defines the style we just applied:

<styletype="text/css">
<!
.myNewStyle{
fontfamily:Arial;
fontstyle:italic;
color:#0000FF;
}
>
</style>

In the above example the css code is directly embedded into the page itself. This is
fine for
smaller projects or in situations where the styles being defined will only be used in a
single
page. There are many times when the styles will be applied to many pages and it
would be a
hassle to have to copy and paste your CSS code into each page.
Besides the fact that the pages will get cluttered with the same CSS code, you also
find
yourself having to edit each of these pages if you want to make a style change. Like
with
JavaScript, you can define/create your CSS styles in a separate file and then link it
to the page
you want to apply the code to:
<linkhref="myStyleSheet.css"rel="stylesheet"type="text/css">
The above line of code links the external style sheet called myStyleSheet.css to
the HTML
document. Place this code in between the <head> </head> tags in your web page.

2.6.2 Creating a linked external CSS and other


examples
To create an external style sheet all you need to do is create a simple text document
and then
change the file extension from type .txt to .css. CSS files are just specially formatted
text files,
and much in the same way HTML pages are. There is nothing special or different in
the file
itself, rather it is the contents of the file that make an HTML document and a CSS
page what
they are.
When working with an external CSS document, there are a couple of points to
remember:
1. You dont add these tags in the CSS page itself as you would if you embedded the
CSS code
in your HTML:
<styletype="text/css">
</style>
Since the CSS link in your web page says that you are linking to a CSS page, you
dont need to
declare (in the external CSS file) that the code in the CSS page is CSS. That is what
the above
tags do. Instead you would just add your CSS code directly to the page like so:
.style1{

fontfamily:Arial;
fontstyle:italic;
color:#0000FF;
}
.style2{
fontfamily:Verdana;
fontstyle:bold;
color:#00FF00;
}
.style3{
fontfamily:Calibri;
fontstyle:italic;
color:#FF0000;
}
In the above example I have created a series CSS classes that can be applied to any
HTML tag
like so:
<pclass="style1">MyCSSstyledtextcomeshere</p>
Or
<h2class=style2>MyCSSstyledtextcomeshere</h2>
You will notice that in the above example I applied a CSS style to a <h2> tag.
Normally this tag
sets the size of the text that it wraps to a size that is preset in the browser (ex: 10
pixels).
When you apply a CSS class to it, the CSS code overrides the default size that you
would
normally get with an <h2> tag in favor of the size specified in the CSS class. So now
you can
see that CSS can override default HTML tag behavior!
In the above examples, I have CSS code where I define my CSS classes and then
apply them
to various elements in the page. Another way to apply CSS is to globally redefine an
HTML tag
to look a certain way:
h1{fontfamily:Garamond,"TimesNewRoman",serif;fontsize:200%;}
What this CSS code does is set the font style and size of all <h1> tags in one shot.
Now you
dont have to apply a CSS class as we did before to any <h1> tags since they are
automatically
all affected by the CSS style rules.
Here is another example of where I give the whole page bigger margins.
body{marginleft:15%;marginright:15%;}

As you can see, you can redefine any tag and change the way it looks! This can be
very
powerful:
div{
background:rgb(204,204,255);
padding:0.5em;
border:1pxsolid#000000;
}
The above CSS code sets that any <div></div> tag will now have a background
color of
rgb(204,204,255) and have a padding of 0.5em and a thin 1 pixel border that is
solid black.
A few things to explain about the above:
Color in CSS can be expressed in a few ways:
In Hex -> for example: #000000 this is black and this: #FF0000 is red
In rgb -> rgb(204,204,255) is a light purple blue color
With named colors like: red or blue
If you are not familiar/comfortable with hex color, you can write the last example as
below:
div{
background:green;
padding:0.5em;
border:1pxsolid#FF0000;
}
So instead of rgb(204,204,255) , I just specified green. By using RGB and Hex
color, you can
really get the exact color you want easily when you know your codes. Luckily many
tools (like
Dreamweaver) provide easy to use color pickers for you so you dont need to
know/remember
the values for the code.
In this last example I will show you the super cool CSS code that allows you to
create link rollover affects without images:
a:link{color:rgb(0,0,153)}
a:visited{color:rgb(153,0,153)}
a:hover{color:rgb(0,96,255)}
a:active{color:rgb(255,0,102)}

The above CSS will cause your links to change color when someone hovers their
mouse pointer
over it, instant rollovers with no images! One important note with the above code, is
that the
style declarations be in the right order: "link-visited-hover-active", otherwise it may
break it in
some browsers.
CSS is very powerful and allows you to do things that you cant do with standard
HTML. It is
supported nicely now in all the modern browsers and is a must learn tool for web
designers.
The above examples are just a small sample of what you can do with CSS, but it
should be
more than enough for you to start styling your pages nicely.

2.7 Overview of XML


2.7.1 What is XML?
XML stands for eXtensible Markup Language. XML is used to store data or
information. In XML,
data is "marked up" with tags, similar to HTML tags. This data might be intended to
be by read
by people or by machines. It can be highly structured data such as data typically
stored in
databases or spreadsheets, or loosely structured data, such as data stored in letters
or
manuals.

2.7.2 Advantages of XML


Initially XML received a lot of excitement, which has now died down some. This is
not because
XML is not as useful, but rather because it does not provide the glaze those other
technologies,
such as HTML do. When you write an HTML document, you see a nicely formatted
page in a
browser - instant gratification. When you write an XML document, you see an XML
document not so exciting. However, with a little more effort, you can make that XML document
glaze!

Some of the major benefits of XML are:


XML holds data - XML stores data in a structure way. Applications can then use this
data to do
several things.
XML separates structure from formatting - One of the difficulties with HTML
documents, word
processor documents (like WordStar, etc.) spreadsheets, and other forms of
documents is that
they mix structure with formatting. This makes it difficult to manage content and
design,
because the two are intermingled. As an example, in HTML, there is a <u> tag used
for
underlining text. Very often, it is used for emphasis, but it also might be used to
mark a book
title. It would be very difficult to write an application that searched through such a
document
for book titles. In XML, the book titles could be placed in <book_title> tags and the
emphasized
text could be place in <em> tags. The XML document does not specify how the
content of
either tag should be displayed. Rather, the formatting is left up to an external
stylesheet. Even
though the book titles and emphasized text might appear the same, it would be
relatively
straight forward to write an application that finds all the book titles. It would simply
look for
text in <book_title> tags. It also becomes much easier to reformat a document; for
example, to
change all emphasized text to be italicized rather than underlined, but leave book
titles
underlined.
XML promotes data sharing - Very often, applications that hold data in different
structures must
share data with one another. It can be very difficult for a developer to map the
different data
structures to each other. XML can serve as a go between. Each application's data
structure is
mapped to an agreed-upon XML structure. Then all the applications share data in
this XML
format. Each application only has to know two structures, its own and the XML
structure, to be
able to share data with many other applications.
XML is Human-Readable - XML documents can be read by people. Perhaps this
doesn't sound
so exciting, but compare it to data stored in a database. It is not easy to browse
through a
database and read different segments of it as you would a text file.

XML is free - XML doesn't cost anything to use. It can be written with a simple text
editor or
one of the many freely available XML authoring tools, such as XML Notepad. In
addition, many
web development tools, such as Dreamweaver.

2.7.3 Uses of XML


Configuration files (deployment descriptors) for servlets, EJBs
Make files for Ant
Content Management - Almost all of the leading content management systems
use XML
in one way or another. A typical use would be to store a company's marketing
content in
one or more XML documents. These XML documents could then be transformed
for
output on the Web, as Word documents, as PowerPoint slides, in plain text, and
even in
audio format. The content can also easily be shared with partners who can then
output
the content in their own formats. Storing the content in XML makes it much
easier to
manage content for two reasons. Content changes, additions, and deletions are
made in
a central location and the changes will cascade out to all formats of
presentation. There
is no need to be concerned about keeping the Word documents in sync with the
website, because the content itself is managed in one place and then
transformed for
each output medium. Formatting changes are made in a central location. To
illustrate,
suppose a company had many marketing web pages, all of which were produced
from
XML content being transformed to HTML. The format for all of these pages
could be
controlled from a single XSLT and a sitewide formatting change could be made
modifying that XSLT.
Webservices -XML Web services are small applications or pieces of applications
that are
made accessible on the Internet using open standards based on XML. Web
services
generally consist of three components:SOAP - an XML-based protocol used to
transfer
Web services over the Internet. WSDL (Web Services Description Language) - an
XMLbased language for describing a Web service and how to call it. UDDI
(Universal
Discovery Description and Integration) - the yellow pages of Web services. UDDI

directory entries are XML documents that describe the Web services a group
offers. This
is how people find available Web services.
RSS Feeds - RDF (Resource Description Framework) is a framework for writing
XMLbased languages to describe information on the Web (e.g, web pages). RSS (RDF
Site
Summary) is an implementation of this framework; it is a language that adheres
to RDF
and is used to describe web content. Website publishers can use RSS to make
content
available as a "feed", so that web users can access some of their content without
actually visiting their site. Often, RSS is used to provide summaries with links to
the
company's website for additional information.

2.7.4 DTD
DTD stands for Document Type Declaration or DocType Declaration. The DTD has
three roles.
It specifies the name of the document element
It may point to an external Document Type Definition (DTD)
It may contain an internal DTD.
The DOCTYPE Declaration shown below simply states that the document element of
the XML
document is emp.
<!DOCTYPEemp>
If a DOCTYPE Declaration points to an external DTD, it must either specify that the
DTD is on
the same system as the XML document itself or that it is in some public location. To
do so, it
uses the keywords SYSTEM and PUBLIC. It then points to the location of the DTD
using a
relative Uniform Resource Indicator (URI) or an absolute URI. Here are a couple of
examples.
Syntax
<!DTDisonthesamesystemastheXMLdocument>

<!DOCTYPEempSYSTEM"dtds/emp.dtd">
Syntax
<!DTDispubliclyavailable>
<!DOCTYPEempPUBLIC"//r6i//DTDEmp1.0//EN"
"http://www.r6i.com/emp/DTD/emp.dtd">
As shown in the second declaration above, public identifiers are divided into three
parts:
An organization (e.g, r6i)
A name for the DTD (e.g, Emp 1.0)
A language (e.g, EN for English)
Here is an example DTD (purchase.dtd) that defines the data type of purchase.xml
document.
Purchase.dtd
<?xmlversion="1.0"?>
<!ELEMENTPURCHASEORDERS(PURCHASEORDER)*>
<!ELEMENTPURCHASEORDER
(PONO?,PODATE,VENDORNAME,EXPECTEDDD,POAMOUNT,LINEITEM+)>
<!ATTLISTPURCHASEORDERZONECDATA#REQUIREDCATEGORY(BOOKS|TOYS)
"TOYS">
<!ELEMENTPONO(#PCDATA)>
<!ENTITYCOPYRIGHT"2001TELEPARADIGM">
<!ELEMENTPODATE(#PCDATA)>
<!ELEMENTVENDORNAME(#PCDATA)>
<!ELEMENTEXPECTEDDD(#PCDATA)>
<!ELEMENTPOAMOUNT(#PCDATA)>
<!ELEMENTLINEITEM(ITEMNAME,ITEMCODE,QTY,ITEMPRICE)>
<!ELEMENTITEMNAME(#PCDATA)>
<!ELEMENTITEMCODE(#PCDATA)>
<!ELEMENTQTY(#PCDATA)>
<!ELEMENTITEMPRICE(#PCDATA)>
Purchase.xml
<?xmlversion="1.0"?>
<!DOCTYPEPURCHASEORDERSSYSTEM"purchase.dtd">
<PURCHASEORDERS>
<PURCHASEORDERZONE="SOUTH"CATEGORY="TOYS">
<PONO>8001</PONO>
<PODATE>12JAN2007</PODATE>
<VENDORNAME>RMK&CO;</VENDORNAME>
<EXPECTEDDD>14MAR2008</EXPECTEDDD>
<POAMOUNT>12000</POAMOUNT>
<LINEITEM>
<ITEMNAME>COLGATE</ITEMNAME>
<ITEMCODE>1234</ITEMCODE>

<QTY>234</QTY>
<ITEMPRICE>2345</ITEMPRICE>
</LINEITEM>
</PURCHASEORDER>
</PURCHASEORDERS>

2.7.4.1 Limitations of DTD

Content is limited to textual


Difficult to put in repetition constraints
DTD does not use XML syntax
DTD does not say the following
_ What the root element of the document is
_ How many of instances of each kind of element appear in the document
_ What the character data inside the elements looks like
_ The semantic meaning of an element
_ A DTD never says anything about the length, structure, meaning,
allowed
values, or other aspects of the text content of an element

2.7.5 XML Schema


Motivations of XML Schema:
Provide more powerful and flexible schema language than DTD
Represent SML Document syntax in XML language (XML tools can be readily used)
Support non-textual data types
Handle complex syntax
Derived types, complex types can be defined

2.7.6 XML Schema Datatypes


Predefined Simple Types - String, CDATA, token, byte, unsignedByte, binary, integer,
positiveInteger, negativeInteger, nonNegativeInteger, nonPositiveInteger, int,
unsignedInt,
long, unsignedLong, short, unsignedShort, decimal, float, double, boolean, time,
timeInstant,
timePeriod, timeDuration, date, month, year, century, recurringDay, recurringDate,
recurringDuration, Name, Qname, NCName, uriReference, language, ID, IDREF,
IDREFS,
ENTITY, ENTITIES, NOTATION, NMTOKEN, NMTOKENS.

Derived Simple Types - XML Schema supports derived simple types. The following
are examples of derived simple types.
Example 1 - Numeric Range
<xsd:simpleType name="myInteger">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="10000"/>
<xsd:maxInclusive value="99999"/>
</xsd:restriction>
</xsd:simpleType>
Example 2 - Regular Expression
<xsd:simpleType name="RMK">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{3}-[A-Z]{2}"/>
</xsd:restriction>
</xsd:simpleType>
Example 3 - Enumeration
<xsd:simpleType name="State">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="AP"/>
<xsd:enumeration value="MP"/>
<xsd:enumeration value="UP"/>
<!-- and so on ... -->
</xsd:restriction>
</xsd:simpleType>
Complex Types - Complex Types are defined using complexType element, complex
type will
contain element declarations, element references, attribute declarations, etc.
Example:
<xsd:complexType name="PostalAddress" >
<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="pin" type="xsd:decimal" />
</xsd:sequence>
<xsd:attribute name="country" type="xsd:NMTOKEN" use="fixed" value="INDIA"/>
</xsd:complexType
Here is an example XSD (blood_report.xsd) for blood_report.xml document.
blood_report.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="Blood_Report" type="Blood_ReportType"/>
<xsd:complexType name="Blood_ReportType">
<xsd:sequence>

<xsd:element name="PatientInfo" type="PatientInfoType"/>


<xsd:element name="BloodSampleInfo" type="BloodSampleInfoType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="PatientInfoType">
<xsd:sequence>
<xsd:element name="IdNo" type="xsd:integer"/>
<xsd:element name="pname" type="xsd:string"/>
<xsd:element name="Ref_Dr" type="xsd:string"/>
<xsd:element name="Date" type="xsd:date"/>
<xsd:element name="age" type="ageType"/>
<xsd:element name="state" type="stateType"/>
<xsd:element name="phone" type="phoneType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="phoneType">
<xsd:restriction base="xsd:integer">
<xsd:pattern value="\d{10}"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="ageType">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="1"/>
<xsd:maxInclusive value="99"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="stateType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="male"/>
<xsd:enumeration value="female"/>
<xsd:enumeration value="child"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:complexType name="BloodSampleInfoType">
<xsd:sequence>
<xsd:element name="Haemoglobin" type="xsd:integer"/>
<xsd:element name="RBC" type="xsd:decimal"/>
<xsd:element name="WBC" type="WBCType"/>
<xsd:element name="ESR" type="ESRType"/>
<xsd:element name="PCV" type="PCVType"/>
<xsd:element name="PlateletCount" type="PCType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="WBCType">
<xsd:sequence>
<xsd:element name="Neutrophils" type="xsd:integer"/>
<xsd:element name="Eosinophils" type="xsd:integer"/>
<xsd:element name="Lymphocytes" type="xsd:integer"/>
<xsd:element name="Monocytes" type="xsd:integer"/>
<xsd:element name="Basophils" type="xsd:decimal"/>

</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="ESRType">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="0"/>
<xsd:maxInclusive value="15"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="PCVType">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="36"/>
<xsd:maxInclusive value="54"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="PCType">
<xsd:restriction base="xsd:integer">
<xsd:minInclusive value="150000"/>
<xsd:maxInclusive value="450000"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
blood_report.xml
<?xml version="1.0"?>
<Blood_Report xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation='blood_report.xsd'>
<PatientInfo>
<IdNo>342</IdNo>
<pname>DeepakLalwani</pname>
<Ref_Dr>Dr. Rayapudi MuraliKrishna</Ref_Dr>
<Date>2005-07-22</Date>
<age>24</age>
<state>male</state>
<phone>9440411033</phone>
</PatientInfo>
<BloodSampleInfo>
<Haemoglobin>15</Haemoglobin>
<RBC>5.0</RBC>
<WBC>
<Neutrophils>50</Neutrophils>
<Eosinophils>3</Eosinophils>
<Lymphocytes>30</Lymphocytes>
<Monocytes>5</Monocytes>
<Basophils>0.4</Basophils>
</WBC>
<ESR>12</ESR>
<PCV>44</PCV>
<PlateletCount>250000</PlateletCount>
</BloodSampleInfo>
</Blood_Report>

2.7.7 XSLT
XSLT stands for eXtensible Stylesheet Language Transformation. XSLT transforms
XML
document into another XML, XHTML, WML, HTML or Text. XSLT is used in the two
following
areas:
Presentation Oriented Publishing (POP) e.g. Browsers and Editors
Message Oriented Middleware (MOM) e.g. Machine-to-Machine data exchange

2.7.7.1 XSLT in Presentation Oriented


Publishing
We know that XML document separates content from presentation. Transformations
can be
used to style XML documents; a common styling technique presents XML in HTML
format. XSLT
Processor (XSLT processor is built-in almost all recent browsers, web-servers and
application
servers) is a program that reads an XSLT style sheet and input XML document and
then
converts the input document into an output document according to the instructions
given in the
stylesheet. The following diagram shows how the XML document is rendered to
HTML
document.

Figure 2.7.7.1a XSLT in Message Oriented Middleware

XSLT in Message Oriented Middleware is important for ecommerce, B2B, and


dynamic content
generation.

Figure 2.7.7.1b XSLT Stylesheet Language constructs


XSLT Stylesheet is nothing but an XML document. The root element is either
stylesheet or
transform, both are defined in standard XSLT namespace
http://www.w3.org/XSL/Transform.
Stylesheet language uses several constructs in order to process the XML documents
according
to the requirements. The following section explains the language constructs.
People.xml
<?xmlversion="1.0"?>
<people>
<personborn="1879"died="1955">
<name>
<first_name>Albert</first_name>
<last_name>Einstein</last_name>
</name>
<profession>Physicist</profession>
<profession>mathematician</profession>
<profession>Teacher</profession>
</person>
<personborn="1642"died="1679">
<name>
<first_name>Sir</first_name>

<middle_initial>Isaac</middle_initial>
<last_name>Newton</last_name>
</name>
<profession>Scientist</profession>
<hobby>Playingthebongoes</hobby>
</person>
</people>

2.7.7.2 Templates
Templates control which output is created from which input. Template syntax
< xsl:template> </xsl:template>. The match attribute contains an Xpath
expression, where
as Xpath expression identifies input node set it matches.
For each node in the node set, the template contents (things between xsl:template
tags) are
instantiated are inserted into the output tree.
Example
<?xmlversion="1.0"?>
<xsl:stylesheetversion="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:templatematch=people">
</xsl:template>
</xsl:stylesheet>

2.7.7.3 xsl:value-of
xsl:value-of element extracts the string value of an element or an attribute and
writes it to
output, select attribute containing XPath expression identifies an element or an
attribute, if it is
a node set, in which case, the string value of node is taken.
Example
<?xmlversion="1.0"?>
<xsl:stylesheetversion="1.0
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:templatematch="person">
<p>
<xsl:valueofselect="name"/>
</p>
</xsl:template>
</xsl:stylesheet>

If we apply this style sheet on People.xml document, it will print the below output:
<p>
Albert
Einstein
</p>
<p>
Sir
Isaac
Newton
</p>

2.7.7.4 xsl:apply-templates
Usually as the XSLT processor reads (traverses) the input XML document
sequentially from top
to bottom, templates are activated in the order they match elements encountered,
template for
a parent will be activated before the children. The order of the traversal can be
changed by
apply-templates.

It can specify which element or elements should be processed next


It can specify an element or elements should be processed in the middle of
processing
element
It can prevent particular elements from being processed
Xsl:apply-templates lets you make your choice of processing order explicit.
The select attribute contains XPath expression telling the XSLT processor
which nodes
to process in the input tree. The apply-template with no select attribute
means all
elements relative to the current element should be matched.
Example
<?xmlversion="1.0"?>
<xsl:stylesheetversion="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:templatematch="person">
<xsl:applytemplatesselect="name"/>
</xsl:template>

<xsl:templatematch="name">
<xsl:valueofselect="last_name"/>,
<xsl:valueofselect="first_name"/>
</xsl:template>
</xsl:stylesheet>
If we apply this style sheet on People.xml document, it will print the below output:
Einstein
Albert
Newton
Sir

2.7.7.5 xsl:for-each
xsl:for-each iterates through a node set.
Example
<?xmlversion="1.0"?>
<xsl:stylesheetversion="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:templatematch="people">
<xsl:foreachselect="person">
<xsl:valueofselect="name"/>
<xsl:valueofselect="@born"/>
</xsl:foreach>
</xsl:template>
</xsl:stylesheet>
If we apply this style sheet on People.xml document, it will print the below output:
Albert
Einstein
1879
Sir
Isaac
Newton
1642

2.7.7.6 xsl:if

Using xsl:if we can check content for certain values. In order to test the content the
test
attribute is required and it will either be true or false.
Syntax: <xsl:if test=criteria></xsl:if>
Example
<?xmlversion="1.0"?>
<xsl:stylesheetversion="1.0"
bxmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:templatematch="people">
<xsl:foreachselect="person">
<xsl:valueofselect="name"/>
<xsl:iftest="@born=1879">
Diedin
<xsl:valueofselect="@died"/>
</xsl:if>
</xsl:foreach>
</xsl:template>
</xsl:stylesheet>
If we apply this style sheet on People.xml document, it will print the below output:
Albert
Einstein
Diedin
1955
Sir
Isaac
Newton

2.7.7.7 xsl:choose
Using xsl:choose also we can select content. The test attribute works in the same
fashion as
in xsl:if.
Example
<?xmlversion="1.0"?>

<xsl:stylesheetversion="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:templatematch="people">
<xsl:foreachselect="person">
<xsl:valueofselect="name"/>
<xsl:choose>
<xsl:whentest="@born='1879'">
Diedin<xsl:valueofselect="@died"/>
</xsl:when>
<xsl:otherwise>
Didnotdiein1955
</xsl:otherwise>
</xsl:choose>
</xsl:foreach>
</xsl:template>
</xsl:stylesheet>
If we apply this style sheet on People.xml document, it will print the below output:
AlbertEinstein
Diedin1955
SirIsaacNewton
Didnotdiein1955

2.7.7.8 xsl:sort
XSLT provides a nice way to sort documents by elements contents.
Syntax: <xsl:sortselect=selection></xsl:sort>
Example (This example sorts data by name in default order (ascending order))
<?xmlversion="1.0"?>
<xsl:stylesheetversion="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:templatematch="people">
<xsl:applytemplates>
<xsl:sortselect="name"/>
</xsl:applytemplates>
</xsl:template>
</xsl:stylesheet>
If we apply this style sheet on People.xml document, it will print the below output:
Albert
Einstein

Physicist
Mathematician
Teacher
Sir
Isaac
Newton
Scientist
Playingthebongos
Example (This example sorts data by name in descending order)
<?xmlversion="1.0"?>
<xsl:stylesheetversion="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:templatematch="people">
<xsl:applytemplates>
<xsl:sortselect="name"order=descending/>
</xsl:applytemplates>
</xsl:template>
</xsl:stylesheet>

If we apply this style sheet on People.xml document, it will print the below output:
Sir
Isaac
Newton
Scientist
Playingthebongoes
Albert
Einstein
Physicist
Mathematician
Teacher

2.7.8 SAX Parser


Simple API for XML (SAX) is an event-driven, serial-access mechanism for accessing
XML

documents. This protocol is frequently used by servlets and network-oriented


programs that
need to transmit and receive XML documents, because it's the fastest and least
memoryintensive mechanism that is currently available for dealing with XML documents,
other than
StAX.
In a nutshell, SAX is oriented towards state independent processing, where the
handling of an
element does not depend on the elements that came before. StAX, on the other
hand, is
oriented towards state dependent processing.
Setting up a program to use SAX requires a bit more work than setting up to use the
Document
Object Model (DOM) (DOM is another parser, we will discuss DOM in next section).
SAX is an
event-driven model (you provide the callback methods, and the parser invokes
them as it reads
the XML data), and that makes it harder to visualize. Finally, you can't "back up" to
an earlier
part of the document, or rearrange it, any more than you can back up a serial data
stream or
rearrange characters you have read from that stream.
For those reasons, developers who are writing a user-oriented application that
displays an XML
document and possibly modifies it will want to use the DOM mechanism. However,
even if you
plan to build DOM applications exclusively, there are several important reasons for
familiarizing
yourself with the SAX model:
Same Error Handling: The same kinds of exceptions are generated by the SAX and
DOM APIs,
so the error handling code is virtually identical.
Handling Validation Errors: By default, the specifications require that validation
errors are
ignored. If you want to throw an exception in the event of a validation error (and
you probably
do), then you need to understand how SAX error handling works.
Converting Existing Data: There is a mechanism you can use to convert an existing
data set to
XML. However, taking advantage of that mechanism requires an understanding of
the SAX
model.

When to Use SAX?


It is helpful to understand the SAX event model when you want to convert existing
data to XML.
As you'll see in Generating XML from an Arbitrary Data Structure, the key to the
conversion
process is to modify an existing application to deliver SAX events as it reads the
data.
SAX is fast and efficient, but its event model makes it most useful for such stateindependent
filtering. For example, a SAX parser calls one method in your application when an
element tag is encountered and calls a different method when text is found. If the
processing you're doing is
state-independent (meaning that it does not depend on the elements have come
before), then
SAX works fine.
On the other hand, for state-dependent processing, where the program needs to do
one thing
with the data under element A but something different with the data under element
B, then a
pull parser such as the Streaming API for XML (StAX) would be a better choice. With
a pull
parser, you get the next node, whatever it happens to be, at any point in the code
that you ask
for it. So it's easy to vary the way you process text (for example), because you can
process it
multiple places in the program.
SAX requires much less memory than DOM, because SAX does not construct an
internal
representation (tree structure) of the XML data, as a DOM does. Instead, SAX simply
sends data to the application as it is read; your application can then do whatever it
wants to do with the
data it sees.
Pull parsers and the SAX API both act like a serial I/O stream. You see the data as it
streams in,
but you can't go back to an earlier position or leap ahead to a different position. In
general,
such parsers work well when you simply want to read data and have the application
act on it.
But when you need to modify an XML structure--especially when you need to modify
it
interactively--an in-memory structure makes more sense. DOM is one such model.
However,
although DOM provides many powerful capabilities for large-scale documents (like
books and

articles), it also requires a lot of complex coding. The details of that process are
highlighted in
When to Use DOM.
Example
The following java program parses the cdcatalg.xml and stores the data in a Oracle
table.
Cdcatalog.xml
<?xmlversion="1.0"encoding="ISO88591"?>
<?xmlstylesheettype="text/xsl"href="C:\Documentsand
Settings\genesis\Desktop\test.xsl"?>
<catalog>
<cdmedia="dvd">
<title>EmpireBurlesque</title>
<artist>BobDylan</artist>
<country>USA</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
<cdmedia="cd">
<title>Hideyourheart</title>
<artist>BonnieTyler</artist>
<country>UK</country>
<company>CBSRecords</company>
<price>9.90</price>
<year>1988</year>
</cd>
<cdmedia="cd">
<title>GreatestHits</title>
<artist>DollyParton</artist>
<country>USA</country>
<company>RCA</company>
<price>9.90</price>
<year>1982</year>
</cd>
<cdmedia="dvd">
<title>Stillgottheblues</title>
<artist>GaryMoore</artist>
<country>UK</country>
<company>Virginrecords</company>
<price>10.20</price>
<year>1990</year>
</cd>
<cdmedia="cd">
<title>Eros</title>
<artist>ErosRamazzotti</artist>
<country>EU</country>

<company>BMG</company>
<price>9.90</price>
<year>1997</year>
</cd>
<cdmedia="dvd">
<title>Onenightonly</title>
<artist>BeeGees</artist>
<country>UK</country>
<company>Polydor</company>
<price>10.90</price>
<year>1998</year>
</cd>
<cdmedia="cd">
<title>SylviasMother</title>
<artist>Dr.Hook</artist>
<country>UK</country>
<company>CBS</company>
<price>8.10</price>
<year>1973</year>
</cd>
<cdmedia="cd">
<title>MaggieMay</title>
<artist>RodStewart</artist>
<country>UK</country>
<company>Pickwick</company>
<price>8.50</price>
<year>1990</year>
</cd>
<cdmedia="dvd">
<title>Romanza</title>
<artist>AndreaBocelli</artist>
<country>EU</country>
<company>Polydor</company>
<price>10.80</price>
<year>1996</year>
</cd>
<cdmedia="cd">
<title>Whenamanlovesawoman</title>
<artist>PercySledge</artist>
<country>USA</country>
<company>Atlantic</company>
<price>8.70</price>
<year>1987</year>
</cd>
<cdmedia="cd">
<title>Blackangel</title>
<artist>SavageRose</artist>
<country>EU</country>
<company>Mega</company>

<price>10.90</price>
<year>1995</year>
</cd>
<cdmedia="dvd">
<title>1999GrammyNominees</title>
<artist>Many</artist>
<country>USA</country>
<company>Grammy</company>
<price>10.20</price>
<year>1999</year>
</cd>
<cdmedia="cd">
<title>Forthegoodtimes</title>
<artist>KennyRogers</artist>
<country>UK</country>
<company>MucikMaster</company>
<price>8.70</price>
<year>1995</year>
</cd>
<cdmedia="dvd">
<title>BigWilliestyle</title>
<artist>WillSmith</artist>
<country>USA</country>
<company>Columbia</company>
<price>9.90</price>
<year>1997</year>
</cd>
<cdmedia="cd">
<title>TupeloHoney</title>
<artist>VanMorrison</artist>
<country>UK</country>
<company>Polydor</company>
<price>8.20</price>
<year>1971</year>
</cd>
<cdmedia="dvd">
<title>Soulsville</title>
<artist>JornHoel</artist>
<country>Norway</country>
<company>WEA</company>
<price>7.90</price>
<year>1996</year>
</cd>
<cdmedia="cd">
<title>Theverybestof</title>
<artist>CatStevens</artist>
<country>UK</country>
<company>Island</company>
<price>8.90</price>

<year>1990</year>
</cd>
<cdmedia="cd">
<title>Stop</title>
<artist>SamBrown</artist>
<country>UK</country>
<company>AandM</company>
<price>8.90</price>
<year>1988</year>
</cd>
<cdmedia="dvd">
<title>BridgeofSpies</title>
<artist>T`Pau</artist>
<country>UK</country>
<company>Siren</company>
<price>7.90</price>
<year>1987</year>
</cd>
<cdmedia="cd">
<title>PrivateDancer</title>
<artist>TinaTurner</artist>
<country>UK</country>
<company>Capitol</company>
<price>8.90</price>
<year>1983</year>
</cd>
<cdmedia="cd">
<title>Midtomnatten</title>
<artist>KimLarsen</artist>
<country>EU</country>
<company>Medley</company>
<price>7.80</price>
<year>1983</year>
</cd>
<cdmedia="dvd">
<title>PavarottiGalaConcert</title>
<artist>LucianoPavarotti</artist>
<country>UK</country>
<company>DECCA</company>
<price>9.90</price>
<year>1991</year>
</cd>
<cdmedia="cd">
<title>Thedockofthebay</title>
<artist>OtisRedding</artist>
<country>USA</country>
<company>Atlantic</company>
<price>7.90</price>
<year>1987</year>

</cd>
<cdmedia="cd">
<title>Picturebook</title>
<artist>SimplyRed</artist>
<country>EU</country>
<company>Elektra</company>
<price>7.20</price>
<year>1985</year>
</cd>
<cdmedia="dvd">
<title>Red</title>
<artist>TheCommunards</artist>
<country>UK</country>
<company>London</company>
<price>7.80</price>
<year>1987</year>
</cd>
<cdmedia="cd">
<title>Unchainmyheart</title>
<artist>JoeCocker</artist>
<country>USA</country>
<company>EMI</company>
<price>8.20</price>
<year>1987</year>
</cd>
</catalog>

Cdcatalog.java
importorg.xml.sax.*;
importorg.xml.sax.helpers.DefaultHandler;
importjavax.xml.parsers.*;
importjava.sql.*;
importjava.util.*;
importjava.io.*;
publicclassCdCatalogextendsDefaultHandler{
Statementstmt;
Connectioncon;
intflag=0;
Stringinsertstring;
publicstaticvoidmain(String[]args){

if(args.length!=1){
System.out.println("usage:cmdfilename");
System.exit(1);
}else{
try{
SAXParserFactory
factory=SAXParserFactory.newInstance();
SAXParsersaxparser=factory.newSAXParser();
saxparser.parse(newFile(args[0]),new
CdCatalog());
}catch(Exceptione){
e.getMessage();
}
}
}
publicvoidstartDocument()throwsSAXException{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521
:orcl","scott","tiger");
stmt=con.createStatement();
}
catch(Exceptione4){
e4.getMessage();
}
}
publicvoidendDocument()throwsSAXException{
try{
con.close();
}catch(Exceptione2)
{
e2.getMessage();
}
}
publicvoidstartElement(Stringuri,StringlocalName,String
qName,Attributesattributes)throwsSAXException{
if(qName.equals("title")){
System.out.println("title");
flag=1;
}elseif(qName.equals("artist")){
System.out.println("artist");
flag=2;
}elseif(qName.equals("country")){
System.out.println("country");
flag=3;
}elseif(qName.equals("company")){
System.out.println("company");
flag=4;
}elseif(qName.equals("price")){

System.out.println("price");
flag=5;
}elseif(qName.equals("year")){
System.out.println("year");
flag=6;
}
}
publicvoidcharacters(char[]ch,intstart,intlength)throws
SAXException{
Stringstr=newString(ch,start,length);
if(flag==1){
insertstring="'"+str+"',";
flag=0;
}elseif(flag==2){
insertstring=insertstring+"'"+str+"',";
flag=0;
}elseif(flag==3){
insertstring=insertstring+"'"+str+"',";
flag=0;
}elseif(flag==4){
insertstring=insertstring+"'"+str+"',";
flag=0;
}elseif(flag==5){
insertstring=insertstring+"'"+str+"',";
flag=0;
}elseif(flag==6){
try{
insertstring=insertstring+"'"+str+"'";
Strings="insertintocatalogsax
values("+insertstring+")";
System.out.println(">"+s);
stmt.executeUpdate(s);
insertstring="";
flag=0;
}catch(Exceptione1){
e1.getMessage();
}
}
}
}

2.7.9 DOM Parser


DOM is a standard defined by the W3C, just like XML, DOM was not designed
specifically for
Java technology (unlike SAX), DOM is cross-platform and cross-language.
DOM Characteristics

DOM Access XML document as a tree structure composed of mostly element nodes
and text
nodes. We can walk the DOM tree back and forth.
DOM Tree and Nodes
In DOM XML document is represented as a tree, a tree is made of nodes, there are
12 different
node types, and nodes may contain other nodes.
Node Types
Document node
Document Fragment node
Element node
Attribute node
Text node
Comment node
Processing instruction node
Document type node
Entity node
Entity reference node
CDATA section node
Notation node

DOM Tree Hierarchy


A document node contains one element node (root element node) and one or more
processing
instruction nodes. An element node may contain other element nodes, one or more
text nodes
and one or more attribute nodes. An attribute node contains a text node.
E.g. the following java program uses DOM parser to enhance the price of each CD
element of
cdcatalg.xml (refer previous section) and stores in new xml file named out.xml.
PriceEnhancer.java
importjavax.xml.parsers.*;
importorg.w3c.dom.*;
importjava.io.*;
importjavax.xml.transform.dom.DOMSource;
importjavax.xml.transform.stream.StreamResult;
importjavax.xml.transform.*;
classPriceEnhancer{
publicstaticvoidmain(String[]args){
try{

DocumentBuilderFactory
dbf=DocumentBuilderFactory.newInstance();
DocumentBuilderdb=dbf.newDocumentBuilder();
Documentdoc=db.parse(newFile(args[0]));
NodeListpnl=doc.getElementsByTagName("price");
for(inti=0;i<pnl.getLength();i++){
Nodepn=pnl.item(i);
Nodecn=pn.getFirstChild();
Strings=(String)cn.getNodeValue();
floatf=Float.parseFloat(s);
f=f+5;
Textt=doc.createTextNode(f+"");
pn.replaceChild(t,cn);
}
TransformerFactorytf=TransformerFactory.newInstance();
Transformert1=tf.newTransformer();
Sourceinput=newDOMSource(doc);
Resultoutput=newStreamResult(new
FileOutputStream("out.xml"));
t1.transform(input,output);
}catch(Exceptione){
e.printStackTrace();
}
}
}

2.8 Summary
Technologies used to build client side applications include JavaScript, CSS and
XML.
JavaScript is a lightweight programming language with many useful features.
XML stands for eXtensible Markup Language. XML is used to store data or
information.
In XML, data is "marked up" with tags, similar to HTML tags. XML is used for
multiple
purposes including configuration files, make files for the ANT tool, content
management,
web services and RSS feeds.
An XML document separates content from presentation. Transformations can be
used
to style XML documents. XSLT is a common styling technique that presents
XML in
HTML format. An XSLT Processor is a program that reads an XSLT style sheet
and input
XML document and then converts the input document into an output document
according to the instructions given in the stylesheet.

Simple API for XML (SAX) is an event-driven, serial-access mechanism for


accessing XML
documents. DOM is a standard defined by the W3C, just like XML. Unlike SAX
DOM was
not designed specifically for Java technology, DOM is cross-platform and crosslanguage.

Lesson 3

Web Services
3.1 Lesson Objectives
The term Web Services is used to describe a standardized way of integrating web
applications
using the XML, SOAP, WSDL and UDDI standard over an internet protocol. This
lesson provides
an explanation of web services, the web services stack and the concept of Service
oriented
architecture. Important terms such as SOAP, WSDL, UDDI are also discussed in this
lesson.
Finally, the lesson and provides an example that describes the steps involved in
writing,
deploying and running web service.

3.2 Web Services


Web Services is a technology that can change the future of computing and ecommerce. Web
Services is a distributed computing technology that offers interaction and
collaboration among
vendors and customers, with the vision of providing ubiquitous computing.
One of key definitions of Web Services is: "Web Services are loosely coupled
software
components delivered over Internet-standard technologies." Some of the early
products in Web
Services started appearing in 1997 when Sun announced its Jini platform and
Hewlett-Packard

its e-speak. After that, many big players such as IBM and Microsoft joined this race.
The Web
Services arena picked up steam after the big players roped in and several small
players also
joined hands for what was perceived as the next Internet wave.
Two of the key problems solved by Web Services over earlier distributed systems
such as
CORBA, DCOM, RPC, and so forth were:
Interoperability: Earlier distributed systems suffered from interoperability issues
because
each vendor implemented its own on-wire format for distributed object messaging.
By using
XML as an on-wire standard, the two camps of Java/J2EE and .NET/C# now could
speak to
each other.
Firewall traversal: Collaboration across corporations was an issue because
distributed
systems such as CORBA and DCOM used non-standard ports. Web Services use
HTTP as a
transport protocol and most of the firewalls allow access though port 80 (for HTTP),
leading to
easier and dynamic collaboration. The dynamic nature of Web Services interaction
offers several exciting services for the users

3.2.1 The Web Services Stack


The Web Services model follows the publish , find, and bind paradigm. In the first
step, a service
provider publishes a Web Service in a Web Service registry. Secondly, a client who is
looking for a service to meet their requirement searches in a registry. The client
then chooses a service
based on its preferences. The client then downloads the service description and
binds with that
to invoke and use the service.

One of the primary concerns of Web-based programmers was how to transmit data
in an
interoperable manner. At the bottom-most layer is the XML standard that addresses
this. SOAP
(Simple Object Access Protocol) is an XML-based mechanism for messaging and RPC
(Remote
Procedure Calls). It addresses the fundamental problem of firewall traversal in RPC
systems by
using HTTP as the transport. SOAP is the protocol used for invoking the service.

3.2.2 What is a Web Service?


Web services constitute a distributed computer architecture made up of many
different

computers trying to communicate over the network to form one system. They
consist of a set of
standards that allow developers to implement distributed applications - using
radically different
tools provided by many different vendors - to create applications that use a
combination of
software modules called from systems in disparate departments or from other
companies.
A Web service contains some number of classes, interfaces, enumerations and
structures that
provide black box functionality to remote clients. Web services typically define
business objects
that execute a unit of work (e.g., perform a calculation, read a data source, etc.) for
the
consumer and wait for the next request. Web service consumer does not necessarily
need to be
a browser-based client. Console-based and Windows Forms-based clients can
consume a Web
service. In each case, the client indirectly interacts with the Web service through an
intervening
proxy. The proxy looks and feels like the real remote type and exposes the same set
of
methods. Under the hood, the the proxy code really forwards the request to the Web
service
using standard HTTP or optionally SOAP messages.

3.2.3 Why Web Services?


Here are the benefits of using Web Services:
Exposing the function on to network: A Web service is a unit of managed code
that can be
remotely invoked using HTTP, that is, it can be activated using HTTP requests. So,
Web
Services allows you to expose the functionality of your existing code over the
network. Once it
is exposed on the network, other application can use the functionality of your
program.
Connecting Different Applications: Web Services allows different applications to
talk to each
other and share data and services among themselves. Other applications can also
use the
services of the web services. For example VB or .NET application can talk to java
web services
and vice versa. So, Web services is used to make the application platform and
technology

independent.
Standardized Protocol: Web Services uses standardized industry standard
protocol for the
communication. All the four layers (Service Transport, XML Messaging, Service
Description and
Service Discovery layers) uses the well defined protocol in the Web Services
protocol stack. This standardization of protocol stack gives the business many
advantages like wide range of
choices, reduction in the cost due to competition and increase in the quality.
Low Cost of communication: Web Services uses SOAP over HTTP protocol for the
communication, so you can use your existing low cost internet for implementing
Web Services.
This solution is much less costly compared to proprietary solutions like EDI/B2B.
Support for Other communication means: Beside SOAP over HTTP, Web Services can
also be
implemented on other reliable transport mechanisms. So, it gives flexibility use the
communication means of your requirement and choice. For example Web Services
can also be
implemented using ftp protocol (Web services over FTP).
Loosely Coupled Applications: Web Services are self-describing software
modules which
encapsulates discrete functionality. Web Services are accessible via standard
Internet
communication protocols like XML and SOAP. These Web Services can be developed
in any
technologies (like c++, Java, .NET, PHP, Perl etc.) and any application or Web
Services can
access these services. So, the Web Services are loosely coupled application and can
be used by applications developed in any technologies. For example, I have heard of
people developing
Web Services using Java technologies and using the Web Services in VB or .NET
applications.
Web Services Sharing: These days due to complexness of the business,
organizations are using different technologies like EAI, EDI, B2B, Portals etc. for
distributing computing. Web Services supports all these technologies, thus helping
the business to use existing investments in other technologies.
Web Services are Self Describing: Web Services are self describing applications,
which reduces the software development time. This helps the other business
partners to quickly develop application and start doing business. This helps
business to save time and money by cutting development time.
Automatic Discovery: Web Services automatic discovery mechanism helps the
business to easy find the Service Providers. This also helps your customer to find

your services easily. With the help of Web Services your business can also increase
revenue by exposing their own Web
Services available to others.
Business Opportunity: Web Services has opened the door to new business
opportunities by
making it easy to connect with partners.

3.2.4 What is Service-Oriented Architecture?


Service Oriented Architecture or SOA for short is a new architecture for the
development of
loosely coupled distributed applications. In fact service-oriented architecture is
collection of
many services in the network. These services communicate with each other and the
communications involves data exchange & even service coordination. Earlier SOA
was based on the DCOM or Object Request Brokers (ORBs). Nowadays SOA is based
on the Web Services. Broadly SOA can be classified into two terms: Services and
Connections.
Services:
A service is a function or some processing logic or business processing that is welldefined, selfcontained, and does not depend on the context or state of other
services. Example of Services is Loan Processing Services, which can be selfcontained unit for process the
Loan Applications. Other example may be Weather Services, which can be used to
get the
weather information. Any application on the network can use the service of the
Weather Service
to get the weather information.
Connections:
Connections means the link connecting these self-contained distributed services
with each
other, it enable client to Services communications. In case of Web services SOAP
over HTTP is
used to communicate the between services.
The following figure is a typical example of the service-oriented architecture. It
shows how a
service consumer sends a service request to a service provider. After accepting the
request,
service provider sends a message to the service consumer. In this case a service
provider can
also be a service consumer.

KEY POINTS:
Web Services can convert your applications into Web-applications.
Web Services can be used by other applications.
The basic Web Services platform is XML + HTTP.
Before you continue you should have a basic understanding of the following:
HTML
XML
The HTTP protocol is the most used Internet protocol.
XML provides a language which can be used between different platforms and
programming
languages and still express complex messages and functions.

3.2.5 An Overview of Web Services


Web services are application components
Web services communicate using open protocols
Web services are self-contained and self-describing
Web services can be discovered using UDDI
Web services can be used by other applications
XML is the basis for Web services
Web services platform elements
SOAP (Simple Object Access Protocol)
UDDI (Universal Description, Discovery and Integration)
WSDL (Web Services Description Language)

3.3 What Is an XML Web Service?

XML Web services are the fundamental building blocks in the move to distributed
computing on
the Internet. Open standards and the focus on communication and collaboration
among people
and applications have created an environment where XML Web services are
becoming the
platform for application integration. Applications are constructed using multiple XML
Web
services from various sources that work together regardless of where they reside or
how they
were implemented.
XML makes it possible for developers to expose valuable resources in a highly
interoperable
fashion, where a resource is any type of application or data store used within an
organization.
The XML Web services architecture defines a standard mechanism for making
resources
available via XML messaging. Being able to access a resource by simply
transmitting XML
messages over standard protocols like TCP, HTTP, or SMTP greatly lowers the bar for
potential
consumers. The term "Web service" typically refers to the piece of code
implementing the XML
interface to a resource, which may otherwise be difficult to access

messages

service

resource
s
This architecture makes it possible for any consumer with XML support to integrate
with Web
service applications.
There are probably as many definitions of XML Web Service as there are companies
building

them, but almost all definitions have these things in common:


XML Web Services expose useful functionality to Web users through a standard Web
protocol.
In most cases, the protocol used is SOAP.
XML Web services provide a way to describe their interfaces in enough detail to
allow a user to
build a client application to talk to them. This description is usually provided in an
XML
document called a Web Services Description Language (WSDL) document.
XML Web services are registered so that potential users can find them easily. This is
done with
Universal Discovery Description and Integration (UDDI).

3.3.1 SOAP
Soap is the communications protocol for XML Web services. When SOAP is described
as a
communications protocol, most people think of DCOM or CORBA and start asking
things like,
"How does SOAP do object activation?" or "What naming service does SOAP use?"
While a
SOAP implementation will probably include these things, the SOAP standard doesn't
specify
them. SOAP is a specification that defines the XML format for messages.
There are other parts of the SOAP specification that describe how to represent
program data as
XML and how to use SOAP to do Remote Procedure Calls.
Most current implementations of SOAP support RPC applications because
programmers who are used to doing COM or CORBA applications understand the
RPC style. SOAP also supports
document style applications where the SOAP message is just a wrapper around an
XML
document. Document-style SOAP applications are very flexible and many new XML
Web services take advantage of this flexibility to build services that would be
difficult to implement using RPC.
A major source of confusion when getting started with SOAP is the difference
between the
SOAP specification and the many implementations of the SOAP specification. Most
people who
use SOAP don't write SOAP messages directly but use a SOAP toolkit to create and
parse the
SOAP messages. These toolkits generally translate function calls from some kind of
language to a SOAP message. For example, the Microsoft SOAP Toolkit 2.0 translates

COM function calls to SOAP and the Apache Toolkit translates JAVA function calls to
SOAP.
One of the first questions newcomers to SOAP ask is how does SOAP deal with
security. Early in its development, SOAP was seen as an HTTP-based protocol so the
assumption was made that HTTP security would be adequate for SOAP. When SOAP
expanded to become a more general purpose
protocol running on top of a number of transports, security became a bigger issue.
For
example, HTTP provides several ways to authenticate which user is making a SOAP
call, but
how does that identity get propagated when the message is routed from HTTP to an
SMTP
transport? SOAP was designed as a building-block protocol, so fortunately, there are
already
specifications in the works to build on SOAP to provide additional security features
for Web
services. The WS-Security specification defines a complete encryption system.
AN OVERVIEW OF SOAP
The basic Web services platform is XML plus HTTP.
SOAP stands for Simple Object Access Protocol
SOAP is a communication protocol
SOAP is for communication between applications
SOAP is a format for sending messages
SOAP is designed to communicate via Internet
SOAP is platform independent
SOAP is language independent
SOAP is based on XML
SOAP is simple and extensible
SOAP allows you to get around firewalls
SOAP will be developed as a W3C standard

3.3.2 UDDI
Universal Discovery Description and Integration is the yellow pages of Web
services.A UDDI
directory entry is an XML file that describes a business and the services it offers.
There are
three parts to an entry in the UDDI directory. The "white pages" describe the
company offering
the service: name, address, contacts, etc. The "yellow pages" include industrial
categories
based on standard taxonomies.
The "green pages" describe the interface to the service in enough detail for
someone to write

an application to use the Web service. The way services are defined is through a
UDDI
document called a Type Model or tModel. In many cases, the tModel contains a
WSDL file that
describes a SOAP interface to an XML Web service,.The UDDI directory also includes
several
ways to search for the services you need to build your applications. For example,
you can
search for providers of a service in a specified geographic location or for business of
a specified
type. The UDDI directory will then supply information, contacts, links, and technical
data to
allow you to evaluate which services meet your requirements.
OVERVIEW OF UDDI
UDDI is a directory service where businesses can register and search for Web
services.
UDDI is a directory for storing information about web services
UDDI is a directory of web service interfaces described by WSDL
UDDI communicates via SOAP
UDDI is built into the Microsoft .NET platform

3.3.3 WSDL
WSDL (often pronounced whiz-dull) stands for Web Services Description Language.
For our
purposes, we can say that a WSDL file is an XML document that describes a set of
SOAP
messages and how the messages are exchanged. In other words, WSDL is to SOAP
what IDL is to CORBA or COM.
Since WSDL is XML, it is readable and editable but in most cases, it is
generated and consumed by software. Since WSDL is a machine-readable language
(e.g., it's
just an XML file), tools and infrastructure can be easily built around it. Today
developers can
use WSDL definitions to generate code that knows precisely how to interact with the
Web
service it describes.
The notation that a WSDL file uses to describe message formats is based
on the XML Schema standard which means it is both programming-language neutral
and
standards-based which makes it suitable for describing XML Web services interfaces
that are
accessible from a wide variety of platforms and programming languages. In addition
to
describing message contents, WSDL defines where the service is available and what
communications protocol is used to talk to the service.

This means that the WSDL file defines


everything required to write a program to work with an XML Web service
WSDL plays an important role in the overall Web services architecture since it
describes the
complete contract for application communication (similar to the role of IDL in the
DCOM
architecture). Although other techniques exist for describing Web services, the WS-I
Basic
Profile Version 1.0 mandates the use of WSDL and XML Schema (see Figure 4) for
describing
Web services. This helps ensure interoperability at the service description layer.
UDDI
WSDL
XSD
SOAP

XML 1.0 + NAME SPACES

Service
Discovery
Service
Description

Messaging

OVERVIEW OF WSDL
WSDL is an XML-based language for describing Web services and how to access
them.
WSDL stands for Web Services Description Language
WSDL is written in XML
WSDL is an XML document
WSDL is used to describe Web services
WSDL is also used to locate Web services

3.3.4 A Sample Application


<!WSDLdefinitionstructure>
<definitions
name="MathService"
targetNamespace="http://example.org/math/"
xmlns="http://schemas.xmlsoap.org/wsdl/"
>
<!abstractdefinitions>
<types>...
<message>...
<portType>...

<!concretedefinitions>
<binding>...
<service>...
</definition>
A WSDL definition is an XML document with a root definition element from the
http://schemas.xmlsoap.org/wsdl/ namespace.. The definitions element may contain
several
other elements including types, message, portType, binding, and service, all of
which come
from the http://schemas.xmlsoap.org/wsdl/ namespace.
The first three elements (types, message, and portType) are all abstract definitions
of the
Web service interface. These elements constitute the programmatic interface that
you typically
interface with in your code. The last two elements (binding and service) describe
the
concrete details of how the abstract interface maps to messages on the wire.
WSDL Elements
Element
Description
Name
A container for abstract type definitions defined using XML
Types
Schema
Message

A definition of an abstract message that may consist of multiple


parts,each
part may be of a different type

portType
binding
service

An abstract set of operations supported by one or more endpoints


(commonly known as an interface); operations are defined by an
exchange of messages
A concrete protocol and data format specification for a particular
portType
A collection of related endpoints, where an endpoint is defined as a
combination of a binding and an address (URI)

3.4 REST Services


The acronym REST stands for Representational State Transfer; this means that each
unique
URL is a representation of some object. You can get the contents of that object using
an HTTP
GET, to delete it, you then might use a POST, PUT, or DELETE to modify the object.

3.4.1 Who is using REST?

All of Yahoo's web services use REST, including Flickr, del.icio.us API uses it, pubsub,
bloglines,
technorati, and both eBay, and Amazon have web services for both REST and SOAP.

3.4.2 Motivation for REST


The motivation for REST was to capture the characteristics of the Web which made
the Web
successful. Subsequently these characteristics are being used to guide the evolution
of the
Web.

3.4.3 REST - An Architectural Style, Not a


Standard
REST is not a standard. You will not see the W3C putting out a REST specification.
You will not
see IBM or Microsoft or Sun selling a REST developer's toolkit. Why? Because REST
is just an
architectural style. You can't bottle up that style. You can only understand it, and
design your
Web services in that style. REST is not a standard, but it uses standards:

HTTP
URL
XML/HTML/GIF/JPEG/etc (Resource Representations)
text/xml, text/html, image/gif, image/jpeg, etc (MIME Types)

3.4.4 REST vs SOAP


The aforementioned companies that are using REST APIs haven't been around for
very long,
and their APIs came out this year mostly. So REST is definitely the new trend in
creating a web

service. The main advantages of REST web services are:


Lightweight - not a lot of extra xml markup
Human Readable Results
Easy to build - no toolkits required
SOAP also has some advantages:
Easy to consume - sometimes
Rigid - type checking, adheres to a contract
Development tools

3.5 Annotation Structures


An annotation structure is an XML document (a structure document) that defines
one particular
type of annotation. A Uniform Resource Identifier (URI) names every annotation
structure. The
URI identifies the annotation type defined by the structure. The annotation structure
is an
ordered collection of named fields, where each field defines one piece of data to be
collected in
an annotation conforming to the structure. Fields are typed using standard XML
Schema data
types; a field might be optional and can allow multiple values. Moreover, related
fields might be
grouped together.

3.5.1 Annotation

An annotation is an XML document (an instance document) that contains the actual
data of an
annotation. Every annotation has an associated annotation type, and the annotation
is an
instantiation of the corresponding annotation structure. In other words, an
annotation specifies
values for all of the fields defined by the annotation's structure. Within this API,
annotations are
identified by globally unique identifiers (GUIDs). Many annotations can share the
same
annotation type and structure.

3.6 Application on WebServices


The following example will describe how to write, deploy and run a webservice using
the
Editplus /netbeans IDE, JBOSS application server and the ANT tool.
There are three steps involved in writing a webservice.

STEP 1: Writing an Interface


packagewebservice1;
importjavax.jws.WebService;
importjavax.jws.WebMethod;
importjava.rmi.Remote;
importjava.rmi.RemoteException;
importjavax.jws.soap.SOAPBinding;
importjavax.jws.soap.SOAPBinding.Style;
@WebService(name="Calculator1")
@SOAPBinding(style=Style.RPC)
publicinterfaceCalculatorextendsRemote
{
@WebMethodintadd(intx,inty);
@WebMethodintsubtract(intx,inty);
}
STEP 2: Writing a class that implements the interface
packagewebservice1;
importjavax.ejb.Stateless;
importjavax.jws.WebService;
importjavax.jws.soap.SOAPBinding;
importjavax.jws.soap.SOAPBinding.Style;
@Stateless
@WebService(name="Calculator1",
endpointInterface="webservice1.Calculator")
publicclassCalculatorBean
{
publicintadd(intx,inty)
{
returnx+y;
}
publicintsubtract(intx,inty)
{
returnxy;
}
}
STEP 3: Writing a client program
packagewebservice1;
importjavax.xml.namespace.QName;
importjavax.xml.rpc.Service;
importjavax.xml.rpc.ServiceFactory;
importjava.net.URL;
importjava.io.File;
publicclassClient
{
publicstaticvoidmain(String[]args)throwsException
{

URLurl=new
URL("http://localhost:8080/tutorial/CalculatorBean?wsdl");
QNameqname=newQName("http://webservice1/",
"CalculatorBeanService");
ServiceFactoryfactory=ServiceFactory.newInstance();
Serviceservice=factory.createService(url,qname);
Calculatorcalculator=(Calculator)
service.getPort(Calculator.class);
System.out.println("1+1="+calculator.add(1,1));
System.out.println("11="+calculator.subtract(1,1));
}
}
The Webservice Folder should appear as under.

Steps to compile a web service:


Set the path of your webservice in the command prompt.

Cleaning the resourses by typing the command ant clean.

Run ant and start the Jboss application server.

3.7 Design Goals for WSE 3.0


WSE 3.0 is fundamentally a security product for Web services. When the WSE (1.0
and 2.0)
project was first conceived, its primary purpose was to show a practical and usable
implementation of the emerging WS-* security specifications, such as WS-Security,
WS-Trust,
and WS-SecureConversation and as a result provide feedback into the
standardization process.
Build Secure Web Services Easily: As well as an easy and intuitive API design, the
objective
here was to abstract common best practices when securing end-to-end messages.
From having
spoken to hundreds of existing WSE customers, there emerged five common
scenarios for
message-level security
Simplified Development of Service-Oriented Systems Using the Web Service
Protocols and .NET Framework v2.0: Continue to provide an easy-to-use
programming API
abstraction on targeted Web service specifications, introduce recent essential
specifications
such as Message Transmission Optimization Mechanism (MTOM), take advantage of
improvements to the .NET Framework 2.0, and provide an integrated set of tools
with Visual
Studio 2005.

3.8 Summary
Web Services is a set of standards that allow developers to implement distributed
applications - using radically different tools provided by many different vendors. The
web services model follows the publish, find and bind paradigm.
SOA (Service oriented Architecture) is a new architecture for the development of
loosely
coupled distributed applications. A service-oriented architecture is a collection of
many
services in the network.

XML Web services are becoming the platform for application integration.
Applications are
constructed using multiple XML Web services from various sources that work
together
regardless of where they reside or how they were implemented. Soap is the
communications protocol for XML Web services.
Universal Discovery Description and Integration is the yellow pages of Web
services.A
UDDI directory entry is an XML file that describes a business and the services it
offers.
A WSDL (Web Services Description Language) file is an XML document that
describes a
set of SOAP messages and how the messages are exchanged. WSDL plays an
important
role in the overall Web services architecture since it describes the complete contract
for
application communication.
REST (Representational State Transfer) is an architectural style that makes use of
standards such as HTTP, URL, XML/HTML/GIF/JPEG/etc (Resource Representations)
and
text/xml, text/html, image/gif, image/jpeg, etc (MIME Types).

Lesson 4

Rich Internet Applications and Flex


4.1 Lesson Objectives
Adobe Flex is a powerful application development tool for creating and deploying
RIAs
(Rich Internet Applications). This lesson provides an understanding of the Flex
Framework and the Flex application life cycle. Vital elements of the Flex
programming
environment such as ActionScript and MXML are discussed in detail with easy to
understand examples. Additionally, the lesson provides an explanation of working
with
XML objects in Flex. The Flex framework consists of a large number of UI
components,
data components and layout components. The lesson provides an explanation of
working with these components. Other key concepts covered include an overview of
Flex
layout containers, layout rules used by containers, how to work with containers and
children and nesting containers.

4.2 What is a Rich Internet Application?


The term Rich Internet Application or RIA was coined by Macromedia in 2002. A Rich
Internet Application provides a richer, more dynamic and responsive web
experience, as
opposed to a static page that contains multiple images and text. A Rich Internet
Application is built using Adobe Flash or Adobe Flex and deployed using Adobe Flash
Player or Adobe AIR. Examples of RIAs include the Flickr photo-sharing website,
eBay
Desktop and Nike Air among many others.
Generally, a web application has all the business logic stored on the server with an
application server maintaining state by using cookies and session variables. The
application does not do anything until the user performs an action that sends data
from
the client to the server for processing. RIA differs from other web applications in
that
the presentation tier is entirely on the client, instead of the logic lying entirely on
the
server side. In an RIA application developed using Flex, the application does not
post a
request to the server every time the user makes a change.

4.3 What is Flex?


Adobe Flex is a powerful application development software for creating and
deploying
cross platform Rich Internet Applications (RIAs). Flex is part of the Adobe Flash
Platform, which is a set of technologies with Flash Player at the core. Flex
applications
can be built using the free Flex SDK. However developers have to use the Adobe
Flex
Builder 3 software in order to speed up development.

A Flex application, at a very basic level, is a Flash .swf file that is embedded in an
HTML
file. Flex 2 content relies on features of Flash Player 9, meaning that users must be
running Flash Player 9 or higher to view Flex 2 content correctly. With nearly every
computer connected to the Internet having some version of Flash Player installed,
and
an increasing number of mobile devices being Flash-enabled, Flash Player is one of
the
most ubiquitous pieces of software anywhere.
Using the Flex framework, you can build and compile to the .swf format. The
compiled
.swf file is an intermediate byte code format that Flash Player can read. Flash Player
9
introduces a new virtual machine called A VM2. A VM2 is written from the ground
up,
and it functions in a fundamentally different way than previous versions of Flash
Player.
With A VM2, .swf content is no longer interpreted. Rather, it is compiled (the
equivalent
of just-in-time compilation) and run such that it can take advantage of lower-level
computing power. This is very similar to how Java and .NET applications work.

4.4 The Flex Framework

The Flex framework is an identical with the flex class library and is a collection of
Action
Script classes used by flex applications. The flex framework is built on entirely by
the
Action Script classes and defines controls, containers and managers designed to
simplify
building rich internet applications.
The Flex Framework:

Flex class libraries:

Form Controls: Form controls are the standard controls such as buttons, text
inputs,
text areas, lists, radio buttons, Check boxes and combo boxes. In addition to the
standard form controls familiar to most HTML developers, the flex class library also
includes controls such as a rich text editor, a color selector, a date selector and
more.

Menu controls: Flex provides a set of menu controls such as pop up menus and
menu
bars.
Media Components: Flex applications are enriched with the media support. A Flex
class library provides a set of components working with media such as images,
audio
and video.
Layout containers: Flex application enables highly configurable screen layout. You
can
use the layout containers to place contents with in a screen and determine how
they will
change overtime or when the user changes the dimensions of Flash player with a
diverse set of container components you can create sophisticated layout using
grids,
forms , boxes, canvases, and more. You can place elements with absolute or relative
coordinates So that they can adjust correctly to different dimension with in flash
player.
Data components and data binding: Flex applications are generally
heterogeneous
applications that make remote procedure calls to data services residing on servers.
The
data components consists of connectors that simplify the procedure calls , data
models
to hold the data that is returned, and data binding functionality to automatically
associate dorm controlled data with data models.
Formatters and validators: Data that is returned from remote procedure calls
often
needs to be formatted before getting displayed to the user. The Flex class library
includes a robust set of formatting Features (format a date in a variety of string
representations, format a number with specific precision, format a number as a
phone
number string, etc.) to accomplish that task. Likewise, when sending data to a data
service from user input, youll frequently need to validate the data beforehand to
ensure
it is in the correct form. The Flex class library includes a set of validators for just
that purpose.
Cursor management: Unlike traditional web applications, Flex applications are
stateful, and they don't have to do a complete screen refresh each time data is sent
or
requested from a data service. However, since remote procedure calls often incur
network and system latency, it's important to notify the user when the client is
waiting
on a response from the data service. Cursor management enables Flex applications
to
change the cursor appearance in order to notify the user of such changes.

State management: A Flex application will frequently require many state changes.
For
example, standard operations such as registering for a new account or making a
purchase usually require several screens. The Flex class library provides classes for
managing those changes in state. State management works not only at the macro
level
for screen changes, but also at the micro level for state changes within individual
components. For example, a product display component could have several states:
a
base state displaying just an image and a name, and a details state that adds a
description, price, and shipping availability. Furthermore, Flex provides the ability to
easily apply so that state changes are animated.
Effects: Flex applications are not limited by the constraints of traditional web
applications. Since Flex applications run within Flash Player, they can utilize the
animation features of Flash. As such, the Flex class library enables an assortment of
effects such as fades, zooms, blurs, and glows.
History management: As states change within a Flex application, the history
management features of the Flex class library enable you to navigate from state to
state.
Drag and drop management: The Flex class library simplifies adding drag and
drop
functionality to components with built-in drag and drop functionality on select
components and a manager class that allows you to quickly add drag and drop
behaviors to components. \
Tool tips: Use this feature of the Flex class library to add tool tips to elements as
the
user moves the mouse over them.
Style management: The Flex class library enables a great deal of control over how
nearly every aspect of a Flex application is styled you can apply style changes such
as
color and font settings to most controls and containers directly to the objects or via
CSS.
Flex consists of a compiler that is capable of compiling MXML and Actionscript. The
entire Flex framework is written in Actionscript and MXML. It provides a layer of
abstraction. The Flex framework consists of many thousands of lines of code, all of
which ultimately run instructions that Flash Player can understand. This means that
when you utilize the Flex framework, the compiler will include the necessary
libraries in
the .swf files. As a result, you can much more rapidly develop applications. For
example,
although you could write your own custom grid layout container or combo box
control,
doing so takes a lot longer than simply using the components that are part of the
Flex

framework.

4.5 The Flex Application Life Cycle


Having an understanding of the application life cycle will enable the developer to
configure features such as customized preloaders, do things such as load other Flex
applications at runtime, and manage the process of loading and unloading class
libraries
and assets at runtime. In addition, a good understanding of the Flex application life
cycle will enable the developer to build better applications because he/she will know
where to optimally run code. For example, to ensure that some code runs during a
preloader, the developer needs to know where to place the code for that event. An
understanding of the application life cycle helps to create applications that will
deliver an
optimal user experience.
Flex applications are essentially Flash applications that use the Flex framework
(which is
written in Action Script). That means everything in a Flex application can be
reconciled
to something that is available to flash applications. The root of a Flex application is
typically System Manager, which is a subclass of flash.Display.MovieClip, a Flash
Player
display object type. A movie clip is a display object type that supports frames, which
are
units of a timeline. System Manager has two frames. The .swf format is a
progressive
download format, which means that Flash Player can access content on frames as
they
download without having to wait for the entire file to download. The first frame is
used
to display a progress indicator while the application loads. This frame is lightweight
in
terms of file size so that it can download and run almost immediately, and it does
not
house much of the Flex framework. The second frame is the one in which the
application itself (along with the majority of the Flex framework utilized by the
application) is actually housed. The figure below illustrates the basic application
startup
event flow.

System Manager
Timeline>

Frame1

Frame2

preloder

Application
Flex framework used
By application

Fig: 4.5 Flex application lifecycle


Once the System Manager instance for a Flex application has advanced to the
second
frame, it creates an instance of the main application class for the Flex application.
The
System Manager instance for the Flex application has an application property that is
null
until it creates the application object on frame 2. At that point, the application
instance
is initialized and runs through its own startup procedure. That means that all the
application object's internal life cycle events occur. The internal life cycle events are
as
follows:
Pre-initialize: The application has been instantiated but has not yet created any
child
components.
Initialize: The application has created child components but has not yet laid out
those
components.

Creation Complete: The application has been completely instantiated and has laid
out
all components.
Once an application has completed its internal startup procedure, it notifies System
Manager, which dispatches an application complete event. From that point forward,
the
application is ready to run.

4.6 Flex Builder

4.7 MXML Language


Because MXML files are ordinary XML files, you have a wide choice of development
environments. You can write MXML code in a simple text editor, a dedicated XML
editor,
or an integrated development environment (IDE) that supports text editing. Flex
supplies a dedicated IDE, called Adobe Flex Builder, that you can use to
develop
your applications.
The following example shows a simple "Hello World" application that contains just
an
<mx:Application> tag and two child tags, the <mx:Panel> tag and the <mx:Label>
tag.
The <mx:Application> tag defines the Application container that is always the root
tag
of a Flex application. The <mx:Panel> tag defines a Panel container that includes a
title
bar, a title, a status message, a border, and a content area for its children. The
<mx:Label> tag represents a Label control, a very simple user interface component
that
displays text.
Example

<!mxml\HellowWorld.mxml>
<mx:Applicationxmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Paneltitle="MyApplication"
paddingTop="10"
paddingBottom="10"
paddingLeft="10"
paddingRight="10>
<mx:Labeltext="HelloWorld!"fontWeight="bold"
fontSize="24"/>
</mx:Panel>
</mx:Application>
Save this code to a file named hello.mxml. MXML filenames must end in a lowercase
.mxml file extension.

The following image shows the "Hello World" application rendered in a web browser
window.

4.8 ActionScript
The second element of the programming model, Action script, extends the
functionality
of the flex applications. Action script provides control and object manipulation
features
that are not available in strict MXML.
ActionScript is the programming language that can be used along with MXML to
create
stylish Flex applications. Mxml is a language, which is mostly used for creating user
interfaces and laying out the front end. ActionScript can be used for data models
and
sophisticated client-side business logic as well.
Flex applications require ActionScript 3.0.ActionScript 3.0 is compliant with the
ECMAA262 specification and influence parts of the pending ECMAScript Edition 4
specification. Action Script 3.0 supports a wide range of features including
formalized
classes, interfaces, and packages, runtime exception handling, runtime data types,
reflection, regular expressions, E4X (XML), and more.

4.9 MXML and ActionScript


MXML is a powerful way to simplify the creation of user interfaces. In most cases, it
is
far better to use MXML for layout than to attempt the same thing with Action Script.
Action Script is far better suited for business logic and data models. However, MXML
and
Action Script are not really so different. In fact, MXML actually gets converted to
Action
Script during compilation, and the MXML structure can be understood in terms of an
Action Script class. This can be useful because it allows you to better understand
how
MXML works and how it relates to Action Script.
When you use an MXML tag to create a component instance, it is the equivalent to
calling the component class's constructor as part of a new statement. For example,
the
following MXML tag creates a new button.
<mx:Buttonid="button"/>
That is equivalent to the following piece of ActionScript code.
varbutton:Button=newButton();
If you assign property values using MXML tag attributes, that's equivalent to setting
the
object properties via ActionScript. For example, the following creates a button and
sets
the label.
<mx:Buttonid="button"label="Click"/>
The following code is the ActionScript equivalent.
varbutton:Button=newButton();
button.label="Click";
This demonstrates that MXML component tags correspond to ActionScript classes.
Furthermore, MXML documents themselves are essentially ActionScript classes,
simply
authored in a different syntax. This is an extremely important point to understand.
An
application document is a class that extends the mx.core.Application, and
component
documents are classes that extend the corresponding component class (e.g.,
mx.containers.VBox).
MXML simplifies writing these classes because the MXML tags automatically
translate

into many lines of ActionScript code that handle important Flex framework tasks
such as
initialization, layout rules, and so forth.
When you create components with IDs in an MXML document, those are really
properties of the class formed by the document. For example, the following creates
a
new class that extends mx.core.Application and creates one property called Button
of
type mx.controls.Button.
<?xmlversion="1.0"encoding="utf8"?>
<mx:Applicationxmlns:mx=http://www.adobe.com/2006/mxml
layout="absolute">
<mx:Buttonid="Button"/>
</mx:Application>
The preceding example is essentially the same as the following ActionScript class:
package {
importmx.core.Application;
importmx.controls.Button;
publicclassExampleextendsApplication{
varbutton:Button;
publicfunctionExample(){
super();
button=newButton();
addChild(button);
}
}
}

When code is placed in an MXML script, it is equivalent to placing code within a


class
body. Variable declarations within MXML scripts are treated as properties of the
class,
and functions are methods of the class. This means that the rules that apply to
writing
pure ActionScript classes also apply to MXML scripts.
When designing and developing Flex and ActionScript applications, you work in the
Flex
Development perspective, which contains the Flex Builder editors and all the views
that
support code editing and design tasks. The configuration of the Flex Development
perspective depends on which editor and mode you're working in. For example,
when
you create a Flex project, the MXML editor works in two modes (Source and Design)
and

each mode contains its own collection of supporting views. For an overview of the
Flex
Development perspective, see The Flex Development perspective.

4.9.1 Using ActionScript


When you want to use ActionScript within Flex, you have four basic options for
where to
place the code:

Inline within MXML tags


Nested within MXML tags
In MXML scripts
Within ActionScript classes

The preceding lists the techniques for working with ActionScript code, from the
simplest
to the most complex form. The following sections examinet each of these
techniques.
Inline ActionScript
Inline ActionScript appears within MXML tags. Inline event handling and data
binding
using curly brace syntax necessarily uses basic ActionScript. The following example
uses
ActionScript to display an alert dialog box when the user clicks on a button.
<mx:Buttonid="alertButton"label="ShowAlert"
click="mx.controls.Alert.show('Example')"/>
In the above example, the text assigned to the click event handler attribute is
Action
Script code, which calls a show( ) method of an ActionScript class called Alert.
The next example uses data binding:
<mx:VBox>
<mx:TextInputid="input"/>
<mx:Textid="output"text="{input.text}"/>
</mx:VBox>
The above example uses the Action Script expression input. Text to evaluate the
text
property value for the input objects (the text input control).
Inline data binding represents the most limited use of Action Script, because it can

evaluate only one expression. For instance, the preceding example evaluates the
expression input. It is possible to use a more complex expression, as in the following
example.
<mx:VBox>
<mx:TextInputid="input"/>
<mx:Textid="output"text="{'Userinput:'+input.text}"/>
</mx:VBox>
The above example concatenates the string User input: with the user input from the
text
input control. Even more complex expressions using inline data binding.can be
created.
Inline event handlers facilitate writing more complex ActionScript that can consist of
several statements. ActionScript statements generally end with semicolons. The
following example illustrates a button with slightly more complex event handler
code,
consisting of two expressions:
<mx:Buttonid="alertButton"label="ShowAlert"
click="mx.controls.Alert.show('Example');alertButton.x+=
40;"/>
The above example first displays an alert dialog box. It then moves the button to
the
right by 40 pixels. Although many statements can be combined together (as in this
example), it is very uncommon. The code is difficult to read and manage when
several
inline statements are combined in that fashion. If an event handler needs to run
several
statements, it is far more common to simply call a function. The next section looks
at
functions later in the chapter, in the "Methods" section.
Nested ActionScript
ActionScript can be nested within MXML tags. Just as most properties values can be
nested, the values (ActionScript) for event handlers can also be nested. The code
must
be placed within a CDATA block. Here is an example.
<mx:Button>
<mx:click>
<![CDATA[mx.controls.Alert.show(UExampleU);]]>
</mx:click>
</mx:Button>
MXML Scripts

The second way to add ActionScript code to an application is to place it within an


MXML
script. An MXML script appears in an MXML document within a Script element.
<mx:Script></mx:Script>
Since ActionScript code may use special characters otherwise interpreted by the
MXML
compiler, you must place ActionScript code within Script tags and also within a
CDATA
block, as in the following example.
<mx:Script>
<![CDATA[
privatefunctionexample():void{
Alert.show(UExampleU);
}
]]>
</mx:Script>
Optionally, ActionScript code blocks can be placed in separate files, and you can
embed
them in a script block using the source attribute of a Script tag:
<mx:Scriptsource="code.as"/>
Within MXML scripts, you can import classes and declare properties and methods.
Each
of these are discussed in greater detail in the "Understanding ActionScript Syntax"
section, later in this chapter.
Classes
Classes are the most sophisticated and powerful use of Actionscript. Although it is
not
wrong to use inline code and MXML scripts, it is generally advisable to place the
majority
of the action script code with in Actionscript classes. Actionscript class code exists
with
in a separate documents, apart from the mxml application and component
documents.
Actionscript class files are text files that use the file extension .as.

4.9.2 Understanding Actionscript 3.0 syntax


It is important to understand basic ActionScript syntax in order to write ActionScript
code inline, in an MXML script, or in a class. The following sections look at the basic
elements of ActionScript, such as class syntax, variables, statements, expressions,

functions, and objects.


Understanding packages
The first thing to define in a custom ActionScript class is the package statement.
The
package statement includes the full folder path from root of your application to the
class, using dot notation to navigate the folder path, as shown here:
packagecom.mydomain.components
{
//classdefinition
}
A package groups together classes to ensure uniqueness of scope. For example,
there
can be only one Button class within a scope. Declaring two Button classes in the
same
scope, will result in a conflict; the compiler would not know which one to use.
A package allows creating several classes with the same name by placing them in
different scopes. For example, the Button class that is part of the Flex framework
(i.e.,
the button UI component) exists within a package called mx.controls. When a class
is
placed within a package, it has a fully qualified class name. Therefore, the fully
qualified
class name for Button is mx.controls.Button. That ensures that if you want to create
another Button class in a different package, you can do so without conflicting with
mx.controls.Button.
Clearly, it is much more convenient to use the shorthand form of a class name (i.e.,
Button). ActionScript allows you to reference a class by the shorthand notation if
you
first add an import statement. An import statement tells the compiler that you can
refer
to the class by its shorthand notation from that point forward. The following is an
import
statement for the Button class:
importmx.controls.Button;
Declaring Classes
Let us look at the basic syntax and structure of a class. At a minimum, all
ActionScript
3.0 classes consist of the following elements:
Class package declaration
Class declaration
Import statements

Creating class files


Each class must be defined in its own file. The name of the file must be the same as
the
name of the class it contains, and the file must use the .as file extension. For
instance,
to define an Example class, create a file named Example.as.
Package declarations
The syntax for all ActionScript 3.0 classes begins with a package declaration. A
package
name in ActionScript corresponds to the directory structure within which the
ActionScript
file is stored. Each directory and subdirectory is delimited by a dot (.) in a package
name.
For example, if a class is stored in the example subdirectory of a com directory,
the package name would be com. example. A class's package declaration uses the
package keyword followed by the package name.
Opening and closing curly braces,
which contain any import statements and class declarations, follow the package
declaration. The following package declaration says that the enclosed class exists
within
the COM.example package. This also means that the file must exist within a com
example directory relative to one of the source path directories:
package.com.example{
//Importstatementsgohere.
//classdeclarationgoeshere.
}

Import statements
Import statements should appear within the package declaration, but not within the
class declaration. (Technically, import statements can be placed anywhere, but by
convention, they should be placed within the package declaration, but not in the
class
declaration.)You must import any and all classes you intend to use.
ActionScript 3.0 classes don't automatically import classes. The following example

imports the URLLoader and URLRequest classes from the Flash Player API.
packagecom.example{
importflash.net.URLLoader;
importflash.net.URLRequest;
//Classdeclarationgoeshere.
}
Class declaration
All public ActionScript 3.0 classes placed within package declarations must be
declared
using the public keyword, followed by the class keyword and the name of the class.
Opening and closing curly braces then follow, within which the class definition is
placed.
Class names always start with initial capital letters by convention. The following
example
declares an Example class in the com.example package:
packagecom.example{
importflash.net.URLLoader;
importflash.net.URLRequest;
publicclassExample{
//Classcodegoeshere.
}}
Variables and Properties
A variable is a named element used to store data or a reference to data. Values can
be
assigned to and read from a variable. To work with a variable, it has to be declared
first.
Declaring a variable allocates memory for it and tells the application that the
variable
exists. A variable is declared using the var keyword. The var keyword is followed by
the
name of the variable. Variable names in ActionnScript are arbitrary, but they must
follow
a few simple rules:
The variable name can consist only of letters, numbers, dollar signs, and
underscores
The variable name must not start with a number
By convention, all ActionScript variables use initial lowercase characters rather
than initial uppercase characters.

The following declares a variable called username.

varuserName;
Although a variable can be declared without a data type, it's always recommended
that
you declare a variable with a data type. A data type to the variable declaration can
be
added using post-colon syntax as follows:
var variableName:DataType;
The data type determines the kind of data you can store in the variable. Some of
the
most common core data types are String, Number, int, uint, Boolean, Date, and
Array.
Data Type
String
Number
Int
Uint
Boolean
Date
Array

Description
One or more characters, including all Unicode characters
Any numeric value, including floating-point numbers
Positive and negative integers and 0
Positive integers and 0
True or false
The date and time
An index-ordered collection of data

The following example declares the userName variable with the data type String:
varuserName:String;
Once a variable has been decalred, the next thing to do is assign values using an
assignment
operator (an equals sign), as in the following example. Declaration and assignment
can be combined into one line.
varuserName:String="FlexUser";
Variables are placed within class methods (find more on method syntax in the
"Methods
section, later in this chapter). Variables declared outside of methods are called
properties, and they are scoped to the entire class. In most respects, variables and
properties are the same. However, there is one key difference that shows up
synBuilding
tactically, which is simply a matter of scope. Here we describe the contrast between
variable and property scope:
All variables declared within methods are scoped exclusively to those methods.
That means a variable cannot be referenced outside the method in which it is
declared.
Properties, on the other hand, have much greater scope. At a minimum, a property
is
accessible within the entire class. However, properties can be made accessible
outside

the class with various settings called modifiers.


Classes define properties using quite a few possible modifiers. A property can be
one of
the following.
Public: The public modifier means the property is accessible outside the class
(e.g., from an instance of the class).
Private: The private modifier makes the property accessible only within the
class.
Protected: The protected modifier makes the property accessible only within
the class and its subclasses.
Internal: The internal modifier makes the property accessible only within the
package.
It is a good practice to always declare properties as private or protected. It is not a
good
idea to declare public properties because a class should always manage its state
(the
values of its properties). Properties are declared properties in much the same way
as
variables i.e. using the var keyword. In addition, a property name must follow the
same
rules as variable names. A common convention (and one used by this book) names
private and protected properties with an initial underscore U to help distinguish
them
from local variables declared within methods. The following example declares a
private
property called _loader of type URLLoader.
packagecom.example{
importflash.net.URLLoader;
importflash.net.URLRequest;
public.classExample{
privatevar_loader:URLLoader;
}
}
In addition to the public, private, protected, and internal modifiers, these modifiers
can
be combined with the static modifier. The static modifier says that the property is
directly accessible from the class rather than from instances. Static modifiers are
used
for many purposes, including design patterns such as the Singleton pattern. The
following example adds a static private property called _ instance of type Example.
packagecom.example{
importflash.net.URLLoader;
importflash.net.URLRequest;

publicclassExample{
privatevar_loader:URLLoader;
staticprivatevar_instance:Example;
}
}
A concept related to properties is that of the constant. A constant is a container for
data, much like a variable/property except that once it has a value, the value cannot
be
changed. Examples of constants in the Flash Player and Flex framework API include
Event. COMPLETE, MouseEvent.CLICK, TimerEvent.TIMER, and Math.PI. Although not
a
requirement, most constants are declared as static, and most are also declared as
public
(unlike properties, constants aren't part of a class's state and can therefore be
declared
public). To declare a constant, use the const keyword rather than var. By
convention,
constant names are all uppercase, as shown below.
packagecom.example{
importflash.net.URLLoader;
importflash.net.URLRequest;
publicclassExample{
privatevar_loader:URLLoader;
staticprivatevar_instance:Example;
staticpublicconstTEST:String="testconstant";
}
}
Method
A method is a way to group together statements, give that group a name, and defer
the
execution of those statements until the method is called by its name. All method
definitions must be placed within a class body, and they use the function keyword
followed by the name of the method. Following the method name is a pair of
parentheses enclosing any parameters that the method might accept. That is
followed
by a colon and the return type of the method. If the function does not return a
value,
the return type is declared as void. Following the return type declaration is the
function
definition enclosed in opening and closing curly braces. The following is a
declaration for
a function called test().
functiontest():void{
}

The test( ) method is declared so that it does not expect any parameters, and it
does
not expect to return a value. Currently, the test() method doesn't do anything
either.
Next, add a few statements inside the function so that it does something:
functiontest():void{
varmessage:String="functionmessage";
trace(message);
}
Now the test() method declares a variable called message, assigns a value to it
(function
message), and then uses trace() to output the value to the console (if debugging) .
To call a method, use the method name followed by the function call operator (the
parentheses). For example, to call the test( ) method, use the following statement:
Test( );
To declare a method and pass method parameters, the parameters must be
declared
within the parentheses as a comma-delimited list. The parameter declarations
consist of
the parameter name and post-colon data typing. The following example rewrites
test()
so that it expects two parameters (a and b):
functiontest(a:String,b:String):void{
trace("Yourmessageis"+a+"and"+b);
}
To call a method with parameters, simply pass the values within the function call
operator, as in the following example:
Test(one,two);
ActionScript does not allow overloading. That means there cannot be two methods
with
the same name but different signatures (different parameter lists). However,
ActionScript does allow for rest parameters. Rest parameters allow passing zero or
more
additional parameters of unknown types to a function. Declare a rest parameter
using a
parameter name preceded immediately by three dots. Within the method, the rest
parameter values can be accessed as an array.
Currently, the test() example requires exactly two parameters (a and b). In order to
pass fewer or more than two parameters rest parameters can be used. The
following
code rewrites test() so that it always requires at least one parameter, but it also
allows

for zero or more additional parameters. By convention, the rest parameter is called
rest
(though you may use arbitrary names for the parameter).
functiontest(a:String,...rest):void{
varmessage:String="Yourmessageis";
for(vari:uint=0;i<rest.length;i++){
message+=""+rest[i];
}
trace(message);
}
To return a value from a method two things need to be done: specify the correct
return
type, and add a return statement. When a return type is specified, it results in
compiletime
and runtime checking. A function set to return a String value must return a string,
not a number, date, array, or any other type. A return statement immediately exits
the
function and returns the specified value to the expression or statement from which
the
function was called. The following rewrite of test ( ) returns a string.
functiontest(a:String,...rest):String{
varmessage:String="Yourmessageis";
for(vari:uint=0;i<rest.length;i++)
{
message+=""+rest[i];
}
returnmessage;
}
Methods use the same public, private, protected, internal, and static modifiers as
properties. If you the modifiers are omitted, Flex assumes the methods are internal.
The
following declares two methods, one public and one public and static.
packagecom.example{
importflash.net.URLLoader;
importflash.net.URLRequest;
publicclassExample{
privatevar_loader:URLLoader;
staticprivatevar_instance:Example;
staticpublicconstTEST:String="testconstant";
publicfunctiontraceMessage(message:String):void{
trace("Yourmessageisn+message):
}
staticpublicfunctiongetlnstance():Example
{

if(_instance==null){
_instance=newExample();
}
return_instance;
}
}
}
Classes also can and should have a special type of method called a constructor. The
constructor method has the following rules.
The method name must be the same as that of the class
The method must be declared as public
The method must not declare a return type or return a value
The following constructor assigns a new value to the _loader property.
packagecom.example{
importflash.net.URLLoader;
importflash.net.URLRequest;
publicclassExample{
privatevar_loader:URLLoader;
staticprivate,var_instance:Example;
staticpublicconstTEST:String="testconstant";
publicfunctionExample(){
_loader=newURLLoader();
}
publicfunctiontraceMessage(message:String):void
{
trace("Yourmessageis"+message);
}
staticpublicfunctiongetlnstance():Example
{
if(_instance==null){
_instance=newExample();
}
return_instance;
}
}}
There are two additional special method types called: implicit getter and setter
methods.
These are declared as methods, but they are accessible as though they were public
properties. The method declarations are identical to normal method declarations,
except
for the following:
Getter methods use the get keyword
Setter methods use the set keyword
Getter methods must not expect any parameters and must return a value

Setter methods must expect exactly one parameter and must be declared with a
void return type
The following example declares a getter and a setter method, each called sample
Property. In this example, a new private property is declared using the getter and
setter
methods as accessory. This IS not a requirement for getter and setter methods, but
it is
a common use case:
packagecom.example{
importflash.net.URLLoader;
importflash.net.URLRequest;
publicclassExample{
privatevar_loader:URLLoader;
staticprivatevar_instance:Example;
privatevar_sampleProperty:String;
publicfunctiongetsampleProperty():String
{
return_sampleProperty;
}
publicfunctionsetsampleProperty(value:String):void{
_sampleProperty=value;
}
staticpublicconstTEST:String="testconstant";
publicfunctionExample(){
_loader=newURLLoader();
}
publicfunctiontraceMessage(message:String):void{
trace("Yourmessageis"+message);
}
staticpublicfunctiongetlnstance():Example{
if(_instance==null){
_instance=newExample();
}
return_instance;
}
}
}
The getter method can be called by using the method name as a property in a
context
that attempts to read the value. The setter method can be called by using the
method
name as a property in a context that attempts to write a value. The following
example
creates an instance of the Example.c1ass; then writes and reads a value to and
from the

instance using the getter and setter methods.


varexample:Example=newExample();
example.sampleProperty="A";//Callthesetter,passingitAas
aparametertrace(example.sampleProperty);//Callthegetter

Expressions
An expression is any ActionScript that can be evaluated. At its simplest, an
expression
might consist of just one literal value or one variable. More complex expressions
combine several values and/or variables using operators. There are many types of
operators in ActionScript, ranging from mathematical operators to Boolean
operators to
bitwise operators. Most operators operate on two operands. For example, the
following
uses variables as operands in conjunction with a multiplication operator.
UnitValue*quantity
Generally, expressions are not used in isolation. For example, the preceding code
multiplies the values from two variables, but it does not do anything with that
product.
That value would typically be used in an assignment statement or as part of a larger
expression. Boolean expressions are often used in if and for statements (Discussed
in
the following section).
Statements
Statements are the building blocks of an application. They define the actions and
program flow. Statements tell the application to do something. They can consist of
variable declarations, assignments, function calls, loops, and conditionals. As
already
seen, the following is an example of a variable declaration statements.
vartotal:Number;

An assignment statement uses the equals sign (=) to apply the value on the right
side
to the variable on the left. For example, the following statement assigns the product
of
unitValue and quantity to a variable called total.
total=unitValue*quantity;
A statement can also be a call to a function. The following example calls a trace( )
function, which is a built-in Flash Player function that writes to the console when
running a debug version of an application in the debug player:
trace("This is a simple statement.");
All statements of these types should end with semicolons in ActionScript. These
types of
statements comprise the majority of ActionScript statements. However, there are
some
statements that do not end in semicolons. Those statements are looping and
conditional
statements including while, for, and if statements.
Looping statements, such as while and for, allow execution of a group of statements
as
long as a condition is met. The following is an example of a while statement in
ActionScript. This statement increment total as long as total is less than maxTotal.
while(total<maxTotal){total+=5;
}
for statements can be used as a compact way to write common loops. The for-loop
syntax is similar to that of the while statement, except that in place of the one
conditional expression, for statement uses three expressions: initialization,
condition,
and update. The following for statement calls trace( ) five times:
for(vari:int=0;i<5;i++){trace(i)};
Conditional statements use Boolean expressions to make the execution of some
statement or statements conditional. The following example adds five to total if
total is
less than maxTotal.
if(total<maxTotal){
total+=5;
}

If statements can be used on their own as in the preceding example and in


conjunction
with else clauses. Else clauses can be used only as part of an if-statement. If the if
statement conditional expression evaluates to false, else clauses that follow are run
until
one of the conditions evaluates to true. It is possible to nest conditionals, and by
convention the nested if statement starts on the same line as the else clause within
which it is nested, creating what are often thought of as else if clauses (though they
are
technically else clauses with nested if statements). The following example adds five
to
total if total is less than maxTotal; otherwise, the code subtracts five.
if(total<maxTotal)
{
total+=5;
}else{
total=5;
}
The following interjects an else if clause that tests whether the total is 20 more than
maxTotal. If so, it subtracts 10; otherwise, it goes to the else clause:
if(total<maxTotal){
total+=5;
}
elseif(total>maxTotal+20){
total=10;
}else{
total=5;
}

Arrays
Arrays are sets of data organized by integer indices or keys. ActionScript defines an
Array type. New arrays are defined using an Array constructor as part of a new
statement (See next section, "Objects"), or using literal notation. The literal notation
uses square brackets to create an array. The following creates a new empty array
and
assigns it to a variable.
varbooks:Array=[];

An array can be populated by adding a comma-delimited list of values between the


square brackets.
varbooks:Array=["ProgrammingFlex2","ActionScript3.0
Cookbook"];
Specific array elements are accessed using array access notation. The following
example
retrieves the first element from the array (ActionScript arrays are 00indexed) and
displays it in the console.
trace(book[O]);
Values can also be assigned to elements using array access notation.
book[2];"WebServicesEssentials";
Arrays are objects in ActionScript, and they have methods and properties like most
objects. It is beyond the scope of this book to delve into the Array API in depth.
However, of the Array API, the length property and push() method are the most
commonly used. The length property returns the number of elements in the array,
and it
is commonly used with a for-statement to loop through all the elements of an array.
The
push( ) method allows you to append elements to an array.
ActionScript arrays are not strongly typed. That means you can store any sort of
data in
an array, even mixed types. Theoretically, you could store numbers, strings, dates,
and
even other arrays in an array.
ActionScript does not have any formal hash maps or similar types. ActionScript does
have an Object type, which is the most basic of all object types. Unlike the majority
of
ActionScript classes the Object class is dynamic, which means arbitrary properties
cab
be added to Object instances. Although it is generally better to write data model
classes
than to store data in Object instances using arbitrary properties, there are cases
when it
is useful to use an Object instance as a hash map/associative array. The following
example creates an Object instance and assigns several keys and values.
varauthorsByBook:Object=newObject();
authorsByBook["ProgrammingFlex2"]="Kazoun,Lott";
authorsByBook["ActionScript3.0Cookbook"]="Bhangal,Colin";

Objects
Objects are composites of state and functionality that can be used as elements
within
ActionScript code. There are potentially an infinite range of object types, including
those
from the built-in Flash Player types to Flex framework types to custom types. An
object
is an instance of a class, which is a blueprint of sorts. Although there are other
mechanisms for creating objects, the most common is to use a new statement with
a
constructor. The constructor for a class is a special function that shares the same
name
as the class. For example, the constructor for the Array class is called Array. Like
any
other functions a constructor may or may not expect parameters. The only way to
know
whether a particular constructor expects parameters is to consult the API
documentation. However, unlike most functions, a constructor must be used as part
of a
new statement, and it always creates a new instance of the class. The following
example
creates a new array using a new statement.
varbooks:Array=newArray();
Objects may have properties and methods depending on the type. Properties are
essentially variables associated with an object, and methods are essentially
functions
associated with the object. Properties and methods of an object in ActionScript are
referenced using dot-syntax. Dot-syntax uses a dot between the name of the object
and
the property of the method. The following example uses dot-syntax to call the push(
)
method of the array object (the push( ) method appends the value as an array
element).
books.push("ProgrammingFlex2");
The next example uses dot-syntax to reference the length property of the array
object.
trace(books.length);
Inheritance
ActionScript allows creation of new classes (called subclasses) that inherit from
existing
classes (called superclasses).This is done by using the extends keyword when
declaring
the class. The extends keyword should follow the class name and be followed by the

class from which it inherits. The following defines class B, so it inherits from a
fictional
class A.
packagecom.example{
importcom.example.A;
publicclassBextendsA{
}}

ActionScript 3.0 allows a class to inherit from just one superclass. The subclass
inherits
the entire implementation of the superclass, but it can access only properties and
methods declared as public or protected. Properties that are declared as private and
methods are never accessible outside a class-not even to subclasses. Classes in the
same package can access properties declared as internal. Consider the class A and
class
B example, if A is defined as follows.
packagecom.example{
publicclassA{
privatevar_one:String;
protectedvar_two:String;
publicfunctionA(){
initialize();
}
privatefunctioninitialize():void
{_one="one;
_two="two";
}
publicfunctionrun():void{
trace("A");
}
}
}
In this example, B (which is defined as a subclass of A) can access _two and run ( ),
but
it cannot access _one or initialize().
If a subclass wants to create its own implementation for a method that it inherits
from a
superclass, it can do so by overriding it. Normally, a subclass blindly inherits all of
the
superclass implementation. However, while overriding a method, the subclass
should be
told to disregard the inherited implementation and use the overridden
implementation

instead. To override a method, use the override keyword in the method declaration.
The
following example illustrates overriding the run ( ) method.
packagecom.example{
importcom.example.A;
publicclassBextendsA{
overridepublicfunctionrun():void{trace("B");
}}
}
When a subclass overrides a superclass method, the subclass method's signature
must
be identical to the superclass method's signature, i.e., the parameters, return type,
and
access modifier must be the same.
Interfaces
ActionScript 3.0 also allows interfaces. Interfaces allow separating the interface
from the
implementation, which enables greater application flexibility. Much of what you
learned
about declaring classes applies to declaring interfaces as well. In fact, it is easier to
list
the differences.
Interfaces use the interface keyword rather than the class keyword
Interfaces cannot declare properties
Interface methods declare the method signature but not the implementation
Interfaces declare only the public interface for implementing classes, and therefore
method signature declarations do not allow for modifiers
By convention, interface names start with an uppercase 1. The following is an
example
of an interface:
packagecom.example{
publicinterfaceIExample{
functiona():String;
functionb(one:String,two:uint):void;
}}
In the preceding example, the interface IExample says that any implementing class
must declare methods a() and b() using the specified signatures.
A class can be declared that it implements an interface using the implements
keyword,
following the class name or following the superclass name if the class extends a
superclass.

The following example implements IExample.


packagecom.example{
importcom.example.IExarnple;
publicclassExampleimplementsIExample{
publicfunctionExample(){
}
publicfunctiona():String{return"a";
}
public function b(one:String, two:uint):void {
trace(one + " " + two);
}}
}
When a class implements an interface, the compiler verifies that it implements all
the
required methods. If it doesn't, the compiler throws an error. A class can implement
methods beyond those specified by an interface, but it must always implement at
least
those methods. A class can also implement more than one interface with a
commadelimited
list of interfaces following the implements keyword.
Handling Events
ActionScript 3.0 and the Flex framework use events to notify and receive notification
when things occur. Events occur in response to the user (for example, the user
clicks on
something), time (timer events), and asynchronous messaging (such as remote
procedure calls). Regardless of the cause of an event, nearly all ActionScript events
use
the same event model.
In ActionScript, events are handled by registering listeners. A listener is a function
or
method that should receive notifications when an event is dispatched. For example,
you
can register a method to receive a notification when the user clicks a button.
At least two elements are needed to register a listener, an object that dispatches
events,
and a function that listens for events. Objects capable of dispatching events either
extend the flash.events.EventDispatcher class or implement the flash. events.
IEventDispatcher interface. When an object can dispatch events, it has a public
addEventListener() method that requires at least two parameters; the name of the
event

to listen for and the function/method that should listen for the event.
object.addEventListener("eventName",listenerFunction);
The listener function must expect one parameter of type mx. events. Event or the
relevant subclass of Event. For example, if the object dispatches an event of type
MouseEvent, the listener should accept a MouseEvent parameter. The event
parameter
contains information about the event that occurred, including a reference to the
object
dispatching the event (the target property of the event object) and the object that
most
recently bubbled (relayed) the event (the currentTarget property). (In many cases,
the
target and currentTarget properties reference the same object.) The following
example
adds an event listener using ActionScript, and when the user clicks the button, the
listener displays the event object in an alert dialog box.
<?xmlversion="1.0"encoding="utf8"?>
<mx:Applicationxmlns:mx=http://www.adobe.com/2006/mxml
layout="absolute"initialize="initializeHandler(event)">
<mx:Script><![CDATA[
PrivatefunctioninitializeHandler(event:Event):void{
button.addEventListener(MouseEvent.CLICK,clickHandler)j
privatefunctionclickHandler(event:MouseEvent):void{
Alert.show(event.toString())j
}
]]></mx:Script>
</mx:Application>
An event listener is unregistered using the removeEventListener() method. This
method
requires the same parameters as addEventListener(). The method unregisters the
specified listener function as a listener for the specified event. It is extremely
important
to remove event listeners when they are no longer necessary. Flash Player will not
garbage-collect an object if there are any references to it still in memory. That
means
that even if an object is no longer used anywhere in the application, except for a
reference held by an event dispatcher, it will not be garbage-collected. The
following
example removes the event listener added in the previous example.
button.removeEventListener(MouseEvent.CLICK,onClick);
ErrorHandling
ActionScript 3.0 supports runtime error handling. That means that if and when an
error

occurs, the application can respond to the error in an elegant fashion rather than
simply
fail to work without any notification to the user. ActionScript 3.0 uses two types of
runtime errors: synchronous and asynchronous.

Handling Synchronous Errors


Synchronous errors occur immediately when trying to execute a statement.
try/catch/finally are used to handle synchronous errors. Code that may throw
runtime
errors, must be surrounded with a try statement.
try{
//Codethatmightthrowerrors
}
One or more catch blocks must be included following a try. If the code in the try
block
throws an error, the application attempts to match the error to the catch blocks in
the
order in which they appear. Every catch block must specify the specific type of error
that
it handles. The application runs the first catch block that it encounters to see if it
matches the type of error thrown. All error types are either flash.errors.Error types
or
subclasses of Error. Therefore, more specific error types first must be caught first,
and
more generic types (e.g., Error) later.
For example:
try{
//Codethatmightthrowerrors
}
catch(error:IOError){
//Codeincasethespecificerroroccurs
}
catch(error:Error){
//Codeincaseanonspecificerroroccurs
}
Inaddition,youcanaddafinallyclausethatrunsregardlessof
whetherthetrystatementissuccessful:
try{
//Codethatmightthrowerrors
}
catch(error:IOError){
//Codeincasethespecificerroroccurs

}
catch(error:Error){
//Codeincaseanonspecificerroroccurs
}
finally{
//Codetoruninanycase
}
Most Flash Player and Flex framework classes use asynchronous errors rather than
synchronous errors, so the following example may seem impractical, but it does
illustrate the syntax for using try/catch. The browse( ) method for a FileReference
object
opens a browse dialog box that lets the user select a file from his local file system.

However, Flash Player can display only one browse dialog box at a time. Calling
browse(
) while a browse dialog box is already open, throws a flash.errors.IOError type of
error.
If the error is not handled, the user receives a notification in a default error dialog
box.
<?xmlversion="1.0"encoding="utfS"?>
<mx:Applicationxmlns:mx=http://www.adobe.com/2006/mxml
layout="absolute"initialize="initializeHandler(event)">
<mx:Script><![CDATA[
privatefunctioninitializeHandler(event:Event):void{
varfile:FileReference=newFileReference();
file.browse();
file.browse();
}
]]></mx:5cript>
</mx:Application>
The following example rewrites the preceding code using error handling:
<?xmlversion="1.0"encoding="utfs"?>
<mx:Applicationxmlns:mx=http://www.adobe.com/2006/mxml
layout="absolute"initialize="initializeHandler(event)">
<mx:Script><![CDATA[
privatefunctioninitializeHandler(event:Event):void{
varfile:FileReference=newFileReference();
try{
file.browse();file.browse();}
catch(error:Error){errors.text+=error+"\n";
]]></mx:Script>

Handling Asynchronous Errors


Many objects in ActionScript can potentially throw asynchronous errors.
Asynchronous
errors are those that occur in response to network operations. For example, if a
requested file is not found, the network operation fails asynchronously, and an
asynchronous error is thrown. All asynchronous errors are in the form of events, and
they use the same event model as standard events. For example, if a URLLoader
object
attempts to load data outside the Flash Player security sandbox, it dispatches a
security
Error event. The following example illustrates how to handle error events.
<?xmlversion~"1.0"encoding~"utf8"?>
<mx:Applicationxmlns:mx=http://www.adobe.comI2008/mxml..
layout="absolute"initialize="initializeHandler(event)">
<mx:Script><![CDATA[
privatefunctioninitializeHandler(event:Event):void{
varloader:URLLoader=newURLLoader();
//Inordertotestthisyou'llneedtospecifyaURLofafile
thatexistsoutsideofthesecuritysandbox.
loader.load(newURLRequest("data.xml"));
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
securityErrorHandler);
}
privatefunction
securityErrorHandler(event:SecurityErrorEvent):void{
errors.text+=event+"\n";
]]></mx:Script>

4.10 Using XML in Flex


XML is a standard protocol for transferring, storing, and reading data for a variety of
purposes, including application initialization parameters, data sets, and remote
procedure calls. Flex applications can work with XML by using Flash Player's native
support. Flash Player 9 supports two mechanisms for working with XML: a legacy
XMLDocument class and the new XML class that implements the ECMAScript for
XML
(E4X) standard. All XML examples in this book use E4X unless otherwise noted.

4.10.1 Creating XML Objects


There are two ways to create XML objects in ActionScript: using XML literals or with
the

XML constructor. XML literals are useful when you want to define the XML data
directly
in the code and you know the exact XML data you want to use. The following
example
defines an XML literal and assigns it to a variable.
varxml:XML=<books><book>
<title>ProgrammingFlex2</title><authors>
<authorfirst="Chafic"last="Kazoun"/><authorfirst="Joey"
last="Lott"/></authors>
</book>
<book>
<title>ActionScript3.0Cookbook</title>
<authors>
<authorfirst="Joey"last="Lott"/>
<authorfirst="Keith"last="Peters"/>
<authorfirst="Darron"last="Schall"/>
</authors>
</book>
</books>
If it is not possible to define the XML data directly in ActionScript, data can be
loaded as
a string and passed to the XML constructor. In the following example, loaded
XMLData
is a variable containing XML data loaded from an external source at runtime.
varxml:XML=newXML(loadedXMLData);

While using the XML constructor, any string data passed to the constructor is parsed
into the XML object as XML nodes. By default, Flash Player attempts to interpret all
string data as XML. That means it interprets whitespace (carriage returns, tabs, etc.)
as
XML nodes. That can cause unexpected results. Therefore, if the XML string data
passed
to an XML constructor contains extra whitespace (for formatting purposes) that
should
not be interpreted as XML nodes, the static ignoreWhitespace property for the XML
class
should be set to true, as shown below.
XML.ignoreWhitespace=true;
varxml:XML=newXML(loadedXMLData);

4.10.2 Reading XML Data

There are two basic ways to read data from an XML object. By traversing the
document
object model (DOM) or by accessing the data using E4X syntax. The two techniques
are
not exclusive of one another and can be used in conjunction with one another.
When viewing the XML data in light of the DOM, treat it simply as a hierarchical
structure of data consisting of parent and child nodes. When looking at the DOM,
focus
primarily on the structure rather than the content. All content can be retrieved from
an
XML object in this manner, but data is accessed by structure by stepping into the
XML
one node at a time. The XML class defines a host of methods for retrieving DOM
structure information, including the following.
children()
The children ( ) method returns an XMLList object with all the child nodes of an XML
object. The XMLList class implements a very similar interface to that of XML, and all
of
the methods discussed in this section apply to both XML and XMLList. An XMLList
object
is essentially an array of XML or XMLList objects. Elements from an XMLList object
can
even be retrieved using array access notation. For example, the following code
retrieves
the book nodes as an XMLList. It then displays the first element from that list.
varbookNodes:XMLList=xml.children();
trace(bookNodes[0].toXMLString();
length ()
The length() method returns the number of elements. For XML objects, this always
returns 1. For XMLList objects, it may return more than 1. The following example
illustrates the children() and length() methods used in conjunction. This example
displays the titles of each of the books.
varbookNodes:XMLList=xml.children();
for(vari:uint=O;i<bookNodes.length();i++){
trace(bookNodes[i].children()[O].toXMLString();
}
parent()
The parent of an XML or XMLList object is retrieved using the parent() method. For

example, the following displays the first book node by accessing the title node first,
and
then it retrieves the parent of that node.
trace(xml.children()[O].children()[o].parent().toXMLString());
attributes()
The attributes() method returns an XMLList object with all the data from the
attributes
contained within an XML object. The name() method is called for each attribute in
the
XMLList to retrieve the name of the attribute as a string. The name is passed as a
parameter to the attribute( ) method of the XML object to retrieve the value of the
attribute. The following example illustrates how this works.
varauthors:XML=xml.children()[O].children()[l].children()[0];
varattributes:XMLList=authorO.attributes();
varattributeName:String;
for(vari:uint=0;i<attributes.length();i++){
attributeName=attributes[i].name();
trace(attributeName+""+authoro.attribute(attributeName));
}
As evident from the above example, traversing the XML DOM is effective but
laborious.
Often, it is far more effective to use E4X syntax, particularly when the structure is
already known. Using E4X syntax child nodes can be accessed by name as
properties of
parent nodes. For example, the following accesses the first book node.
trace(xml.book[o]);
This simple E4X syntax can be chained together as in the following example, which
retrieves the first author node of the first book node.
trace(xml.book[o].authors.author[o].toXMLString());
Using the @ symbol of the E4X syntax, attributes can be easily accessed. The
following
uses this syntax to retrieve the value of the first attribute of the author node.
trace(xml.book[o].authors.author[o].@first);
It is also possible to use E4X filters. Filters are enclosed in parentheses within which
conditions are specified. The following example retrieves all the author nodes in
which
the last attribute is Kazoun.
varauthors:XMLList=xml.book.authors.author.(@last==
"Kazoun");

for(vari:uint=0;i<authors.length();i++){
trace(authors[i].parent().parent().toXMLString());
}

4.10.3 Writing to and Editing XML Objects


ActionScript can be used to write to and edit XML objects. This can be done in the
following ways:
Modify existing data
Add new data
Remove existing data
Existing data can be modified using the same E4X syntax used to read the data on
the
left side of an assignment statement. For example, the following changes the title of
the
first book.
xml.book[0].title="ProgrammingFlex2:Edition1";
The following example changes the name of the second author of the first book.
xml.book[O].authors.author[l].@first:"Joseph";
The appendChild ( ), prependChild ( ), qnsertChildBefore(), and insertChildAfter()
methods are used to add new data. Each method inserts a new XML node into an
XML
or XMLList structure. The appendChild() and prependChild() methods each accept
one
parameter and insert the node at the end and at the beginning of the structure,
respectively.
The following adds a new publisher node to each book.
xml.book[O].appendChil(<publisher>genesis</publisher>);
xml.book[l].appendChild(<publisher>genesis</publisher>);
The insertChildBefore() and insertChildAfter() methods are used to add a new node
before or after an existing node. The methods each require two parameters: the
new
node to add, and a reference to the existing node. The following adds a new
publication
date node (publicationDate) between the authors and publisher nodes of the books.
xml.book[o].insertChildAfter(xml.book[o].authors,
<publicationDate>2008</publicationDate>);
xml.book[l].insertChildAfter(xml.book[l].authors,
<publicationDate>2008

</publicationDat>);
The delete operator is used to remove elements. The following example first adds a
new
middle attribute to an author node and then removes it.
xml.book[O].authors.author[l]=<authorfirst:"Joey"
middle:"Persnippity"last="Lott/>;
trace(xml.book[o].authors);
deletexml.book[o].authors.author[l].@middlej
trace(xml.book[O].authors);

4.11 Reflection
ActionScript 3.0 supports class reflection using the following functions in the
flash.utils
package.
getQualifiedClassName
getQualifiedSuperclassName
getDefinitionByName
describeType
Getting the Class Name
The getQualifiedClassName( ) function is used to retrieve the name of the class for
which an object is an instancen. The function returns the fully qualified name when
a
reference to an object is passed as a parameter.
varloader:URLLoader=newURLLoader();
varclassName:String=getQualifiedClassName(loader);
trace(className);
//Displaysflash.net.URLLoader
Ifyouwanttoretrievethefullyqualifiedsuperclassnamefor
anobject,youcanusethegetQualifiedSuperclassName()
function:
varloader:URLLoader=newURLLoader();
varclassName:String=getQualifiedSuperclassName(loader);
trace(className);
//Displaysflash.events.EventDispatcher
Getting the Class by Name
For a given class name, the getDefinitionByName( ) function can retrieve a
reference to

the class. The function requires a string parameter specifying a class name, and it
returns an Object type. The function returns an Object type rather than a Class type
because it could also theoretically return a reference to a function if a fully qualified
function name (e.g., flash.util.getTimer) is passed. If you are certain that you are
retrieving a class reference, you can cast the return value to Class, as in the
following
example:
varclassReference:Class=
Class(getDefinitionByName("flash.net.URLLoader"));
Once a class reference is retrieved, a new instance can be created as follows.
varinstance:Object=newclassReference();
The return value from getQualifiedClassName() or getQuali fiedSuperclassName( )
can
be used in conjunction with getDefinitionByNameO, as in the following example.

varloader:URLLoader=newURLLoader();
varclassName:String=getQualifiedClassName(loader);
varclassReference:Class=Class(getDefinitionByName(className));
varinstance:Object=newclassReference();
Class Introspection
The describeType( ) function is used to return a description of all the events, public
properties, and public methods of an object. The object that has to be introspected
is
simply passed as a reference to the method. The method returns an XML object that
details the class name, superclass, various class settings, implemented interfaces,
constructor signature, public method signatures, and public properties descriptions.

4.12 MXML, ActionScript, and CSS Editors


Flex Builder contains three editors for writing MXML, ActionScript, and CSS code.
The
MXML editor lets you edit MXML files. The MXML editor contains two modes: Source
and
Design. The Source mode allows the developer to write MXML and embed
ActionScript
and CSS code contained within <mx:Script> and <mx:Style> tags. The Design
mode
allows working with the layout and design of Flex applications. The ActionScript
editor is
used to edit AS files (ActionScript), which include main files for ActionScript projects,

and class and interface files. The CSS editor is used to create Cascading Style
Sheets
(CSS files).
As you enter MXML, ActionScript, and CSS code, hints are displayed to help you
complete your code. This feature is called Content Assist. Flex Builder also assists
you in
quickly developing your code by including MXML tag completion, automatic import
management, integration with Adobe Flex Language Reference, and the capability
of
choosing different colors and fonts to display your code in the workspace.

4.13 Managing Layout


One of the key features of Flex is its ability to simplify application layout. Traditional
application development requires writing layout code, or working with layout
components in a no intuitive manner. With MXML and Flex's layout containers,
developers can create most applications without having to write a single line of
custom
layout code.

4.13.1 Flex Layout Overview


Container components are the basis of how Flex provides layout logic. At the most
basic
level, the Application class is a container, and sub items within the Application class
(tag) are called children. In MXML, placing nodes within a container declaration
signifies
that the objects are instantiated and added to the container as container children,
and
the container automatically handles their positioning and sizing.
For example, in the following code two children are added to the Application
container
i.e. a Text Input instance and a Button instance:
<?xmlversion="1.0"encoding="utf8"?>
<mx:Applicationxmlns:mx=http://www.adobe.com/2006/mxml>

<mx:TextInput/>
<mx:Buttonlabel="Submit"/>
</mx:Application>

Figure 4.13.1 Adding child components


In Figure 4.13.1, two children are added to the Application container by simply
placing
the children as sub nodes of the container using MXML. This adds the children to the
container's display list, which is very similar to Flash Player 9's display list. Also,
notice
that there was no need to explicitly place the children at a specific position within
the
container in the code. That is because some containers by default automatically
position
children to enable the developer to use their layout rules, rather than requiring the
developer to provide the exact Coordinates of each child's position. Although this
may
seem like a limitation, it is not a requirement, and there is the option of setting
custom
values, using different containers to achieve the layout you want, or even specifying
an
exact fixed pixel position and size.

Containers and user interface components have many things in common regarding
the
Inheritance chain, which makes containers easier to work with for anyone who is
familiar with Flex Components in general. The main difference is that containers are
not
meant to receive user Input, as most user interface components are; instead, their

purpose is to house child Controls or other layout containers. Because of this, their
tab
Children property is set to true, and their tab Enabled property is set to false.
In the previous code sample, children were added to a container using MXML. The
same can be done using ActionScript.
Example: Adding children to a container using ActionScript
<?xmlversion="1.0"encoding="utf8"?>
<mx:Applicationxmlns:mx="http://www.adobe.com/2006/mxml"
initialize="addItems()">
<mx:Script>
<![CDATA[
importmx.controls.TextInput;
importmx.controls.Button;
privatefunctionaddItems():void
{
varti:TextInput=newTextInput();
this.addChild(ti);
varbtn:Button=newButton();
btn.label="Submit";
this.addChild(btn);
}
]]>
</mx:Script>
</mx:Application>
As seen in the above Example, the ActionScript code is much more verbose than the
MXML code. This is a prime example of how MXML is ideal for rapidly developing
application user interfaces. In general, application layout should be written in MXML
whenever possible, and choose ActionScript only to do more at runtime, such as add
an
arbitrary number of children, or in cases where MXML doesn't provide enough
control to
achieve the desired layout. Keep in mind that both ActionScript and MXML can be
mixed
to create an application's layout, so it is important to learn how to code in both
ways.

4.13.2 Working with UI Components


The Flex framework consists of a large number of components from data
components,
layout components to user interface (UI) components. UI components are visual
components that display something to the user and/or prompt the user to interact
with
the application.

Although there is no formal classification for the majority of the UI components in


the
Flex framework, it is useful to categorize them just for the purposes of discussion. UI
components based on the categories are listed in following Table.
Category
Buttons
Value selectors
Text components
List-based controls
Pop-up controls
Windows
Navigators
Control bars
Media and
progress
Indicators

Component
Button, linkbutton, radiobutton, check button
HSlider, VSlider, NumericStepper, ColorPicker, DateField,
DateChooser
Label,Text, Textlnput, TextArea, RichTextEditor
List,ComboBox, DataGrid, HorizontalList, TileList,Tree
PopUpButton,PopUpMenuButton
Panel,TitleWindow
ViewStack,Accordion, ButtonBar, LinkBar, MenuBar, TabBar,
TabNavigator, ToggleButtonBar
ControlBar,ApplicationControlBar
Image,SWFLoader,VideoDisplay,ProgressBar

Table 4.13.2 UI Components

4.13.3 Understanding UI Components


All UI components (and all layout components) are related because they inherit from
a
common superclass called mx.core.UIComponent. This UIComponent class is part of
the
Flex framework. The class is abstract, meaning A UIComponent instance can never
be
created directly. However, it is important to understand the UIComponent class
because
all the components inherit from it. The UIComponent class itself inherits from
mx.core.FlexSprite, which directly inherits from flash.display.Sprite, which is part of
the
Flash Player API. This means that all Flex UI components behave very much like
standard Flash display objects because they inherit from the display object
inheritance
chain. Figure 4.13.3 illustrates the inheritance relationship of UI components,
showing
only a partial list of the UI components (Button, Combo Box, DateFie1d, etc.).

Flash player

Object
EventDispatcher
DisplayObject
InteractiveObject
DisplayObjectContainer

Flex Framework

Sprite
FlexSprite
UI Component
Button

Link

bub

ComboBox

radio

Check
button

comboB
ox

colorpicke
r

Date field

Figure 4.13.3 A partial list of the UI components and the inheritance relationship of
UI
components and Flash Player classes

4.13.4 Handling Events

Events are the way in which objects (such as Flex UI components) can communicate
with the rest of the application. There are two basic types of events: user events
and
system events. User events are events that occur directly because of user
interaction
with the application. For example, when the user clicks on a button, a click event
occurs,
and when the user expands a drop-down menu (a combo box component), an open
event occurs. On the other hand, a system event occurs because something
happens
within the application in response to initialization, asynchronous operations, or other
such nonuser-driven behavior. For example, when a component is created, several
events occur during the stages of creation indicating that various aspects of the
component are accessible.
When an event occurs, the event is dispatched (or broadcasted). The object that
dispatches an event is called the target. All Flex UI components are potential event
targets, meaning all UI components dispatch events. The event that gets dispatched
is
in the form of an object of type flash.events.Event (or a subtype). The Event
instance
provides information about the event, including the type of event (click, open, etc.)
and
the target that dispatched the event.
When a component dispatches an event, nothing occurs in response unless
something
(called a listener) is configured to receive notifications. There are two ways to
handle
events in a Flex application: one uses MXML attributes and the other uses
ActionScript.
Handling events with MXML
While creating a component using MXML, an event handler can be added using an
attribute that has the same name as the event to be handled. For example, buttons
dispatch click events when the user clicks on them. Therefore, a click attribute is
added
to the Button tag to handle the click event. ActionScript also can be assigned to the
attribute. For example, the following code lowers the alpha by .1 of the button each
time the user clicks on it:
<mx:Buttonid="button"label="AlphaButton"click="{button.alpha=
.1}"/>
Although ActionScript expressions can be assigned to event handler attributes, as in
the
preceding example, it is more common (and useful) to assign a function call to the
event
handler attribute. This allows defining more complex functionality in response to the

event. When a function/method is called from an event handler attribute, you


should
pass a parameter called event to the function. In MXML, the event parameter will
automatically pass along the event object that the component dispatches:
<mx:Buttonid="button"label="AlphaButton"
click="clickHandler(event)"/>
You then need to define the method that is intended to handle the event. The
method
should accept a parameter of type Event (or the appropriate subtype). The following
example accomplishes the same thing as the inline expression did previously.
However,
in addition, it resets the alpha to 1 if and when the alpha is less than 0:
privatefunctionclickHandler(event:Event):void{
vartarget:Button=Button(event.target);
target.alpha=1;
if(target.alpha<0)
{
target.alpha=1;
}

Handling events with ActionScript


ActionScript can be used to add event listeners to a component as an alternative to
using MXML event attributes. This is advantageous for several reasons. First, it is
useful
to add event listeners with ActionScript while creating the component instance
using
ActionScript as opposed to MXML. Second, when event listeners are added using
ActionScript, the event listeners can also be removed later. This is handy to
temporarily
or permanently stop listening for a specific event for a component.
In order to register a listener for an event using ActionScript the addEventListener()
method is used. This method requires at least two parameters: the name of the
event

for which you want to listen and the function to use as the listener. Typically, use
constants for event names rather than quoted strings to avoid typos that would
introduce bugs that would not be caught by the compiler. The event name constants
are
members of the associated event class. For example, the Event class defines OPEN,
CLOSE, SCROLL, SELECT, and many other constants. The Mouse Event class defines
CLICK, MOUSE_OVER, and other mouse-related event constants. The FlexEvent class
defines constants for many of the Flex-specific events such as ADD, REMOVE,
CREATION_COMPLETE, and INITIALIZE. The following code creates a button and then
adds a listener for the click event.
varbutton:Button=newButton();
button.addEventListener(MouseEvent.CLICK,clickHandler);
addChild(button);
The event listener function is automatically passed an Event object as a parameter.
privatefunctionclickHandler(event:MouseEvent):void{
vartarget:Button=Button(event.target);
target.alpha=.1;
if(target.alpha<0)
{
target.alpha=1;
}
}

4.13.5 Event objects


The flash.events:Event class is the base class for all events in Flex applications.
However, many event objects are instances of event subtypes. For example, events
related to mouse behavior (click, mouseOver, etc.) are of type MouseEvent.
Event objects always have a type property that indicates the type of event the
object

represents. For example, a click event dispatches an object with a type property of
click.
Event objects also have target properties that reference the actual object which
dispatched the event. In some cases, the target may not be the object for which a
listener has been registered. This can occur when the object for which there is a
registered listener contains a child component that also dispatches the same event
(and
the event bubbles). To ensure that you are getting a reference to the object for
which
the listener is registered to listen for the event, use the current Target property.
Standard Flex component events
Each UI component type may have events that are specific to that type. For
example,
combo boxes dispatch open events when the menu is expanded. However, all UI
components have a set of events common.
Event
Add

Constant
FlexEvent.ADD

Remove

FlexEvent.REMOVE

Show

FlexEvent.SHOW

Hide

FlexEvent.HIDE

Resize

FlexEvent.RESIZE

Preinitializ
e

FlexEvent.PREINITIALIZE

Creation
Complete
Initialize

FlexEvent.CREATION_COMPLETE
FlexEvent.INITIALIZE

Description
The component has been added
to a container
The component has been
removed to a container
The component has been made
visible
The component has been made
nonvisible
The component Dimensions
have
changed
The component has started to
initialize
but children havent yet been
created
The component is completely
Created and laid out
The component has been
constructed,
but it has not yet been
measured and
laid out

Table 4.13.5 Event objects

Buttons
There are four basic button types of controls: Button, LinkButton, RadioButton, and
CheckBox. Although each type behaves similarly, they have different intended uses.
Figure 4.13.5a shows instances of each type.

Figure 4.13.5a Buttons


Of the four types, Button and LinkButton are the most similar in use. In fact, the
primary
difference between Button and LinkButton is purely cosmetic: buttons have borders
and
backgrounds, and link buttons do not. However, both types are used for similar
purposes-generally to initiate some behavior when the user clicks on the button or
link
button. Buttons are typically more common than link buttons.
With buttons and link buttons, the default behavior is that they respond to every
click in
the same way. However, the toggle property of a button or link button can be set to
true, in which case the button will have two states-selected and deselected-and it
will
toggle between those states each time the user clicks it.
Radio buttons are quite different in use from standard buttons. Radio buttons are
typically used in groups. Radio buttons can be selected or deselected, and only one
button can be selected per group. For this reason, radio buttons are often used to
allow
the user to select just one from a group of options. Typically a RadioButtonGroup
instance is first created when using radio buttons. Then, assign the ID of the group
to
the groupName property of each radio button in the group, as shown here:
<mx:RadioButtonGroupid="examplegroup"!>
<mx:RadioButtongroupName="examplegroup"label="A"value="a"!>
<mx:RadioButtongroupName="examplegroup"label="B"value="b"/>

Checkboxes are also buttons. They are most similar to standard buttons that have
been
set to toggle. When a user clicks a checkbox, it toggles the selected state of the
component.

Value selectors
Value selectors are components that allow the user to select a value. This is a fairly
diverse category of components because the types of values they allow the user to
select and the ways in which they allow the user to select the values are quite
different.
Figure 4.13.5b shows the basic value selector components (except for VSlider,
because
it is the vertical version of HSlider).

Figure 4.13.5b Value Selectors


The slider components (HSlider and VSlider) differ only in that one is horizontal and
one
is vertical. Otherwise, they behave identically. The slider components allow the user
to
select a numeric value along a range from a minimum to a maximum value. The
default
range is 0 to 10, but the range can be adjusted using the minimum and maximum
properties. The slider components allow the user to drag a thumb along that range.
Optionally, you can add more than one thumb and allow the user to select a range
of values.
The numeric stepper control allows the user to select a numeric value as well.
However,
the interface for a numeric stepper is quite different from that of a slider interface.

Where a slider interface is very graphical, the numeric stepper interface actually
displays
the current numeric value in digits, allowing the user to scroll through the list of
possible
values in the range.
The color picker component is very useful for allowing the user to select a color
value
from an expandable/collapsible grid of color swatches. The date field and date
chooser
components are useful because they allow the user to select date values. The date
field
component enables the user to select a single date in a compact form. Although the
date field component expands to display a calendar while the user is selecting a
date, it
again collapses to a compact form once the user has selected a value. The date
chooser
component, on the other hand, is an expanded format component that always
displays
the calendar from which the user can select a date. The date chooser component
also
allows the user to select multiple dates and ranges of dates.

Text Components
There are five basic text components that we can further categorize into display and
input components.

Figure 4.13.5c Text Components

The label and text components are display-only components. The user cannot edit
the
contents of either of these types. The label component is useful for displaying one
line
of text, whereas the text component is useful for displaying multiple lines of text.
The text input, text area, and rich text editor components are user input text
controls.
The text input component allows the user to input one line of text. The text area
component allows the user to input multiple lines of text, and it automatically adds
scrollbars when necessary. The rich text editor component not only allows the user
to
input multiple lines of text, but it also allows her to apply formatting styles such as
bold,
italic, underline, text align, etc.

List-Based Controls
List-based controls are some of the most sophisticated of the standard controls.
These
are the components that allow the user to select an item or items from a list of
options.
In the simplest form, a list might be a vertical, scrollable list of text labels from
which
the user can select. However, list-based controls can be increasingly complex from
there, supporting columns, horizontal and grid-based layout, hierarchical and
collapsible
structures, and even icons, images, and more. Figure 4.13.5d shows the list-based
controls.
The most fundamental of all the list-based controls is the list. Such lists are
vertically
scrolling, single-column controls. Horizontal lists are identical to standard lists
except
that they scroll horizontally rather than vertically. Horizontal lists are typically useful
for
scrolling icons and/or images (thumbnails), though a horizontal list could also be
used
for simple text.
Combo boxes are lists that collapse to a single line when not activated. These types
of
controls are often referred to by users as drop-down menus, and they allow the user
to
select from a vertically scrolling list of options when in an expanded state. Once a
value
has been selected, the control returns to the collapsed state.
Tile lists are scrollable lists in which the contents are arranged in a grid. Tile lists are

useful while displaying contents in a grid, but the grid is needed to scroll.
Data grids are vertically scrolling, multicolumn lists. Data grids are good for
displaying
data that consists of records of multiple values that a user might need to see at the
same time. For example, a data grid would be a good choice for displaying the
details of
a user's phone use history in which each row displays the time, the duration, and
the
destination phone number, each in a different column
Tree controls are hierarchical types of lists. They are very similar to standard lists
because they vertically scroll. However, where standard lists have linear data
models,
trees have hierarchical data models in which individual elements can expand and
collapse to reveal and hide nested elements.

Figure 4.13.5d List-Based Controls.


A data provider is always needed while working with a list. A data provider is the
data
model for which the list is the view. All list-based components have a data Provider
property is used to assign the data model or retrieve a reference to the current data
model.

Data models

Flex controls use model-view-controller, a software pattern that differentiates


between
the display of data and the data itself. This is very evident in the list-based controls.
All
list-based controls utilize data models. In the language used by these components,
the
data models are called data providers are independent objects which you can
associate
with a control. The control then uses that object's data to render its view.
Data providers always implement the mx.collections.ICollectonView interface.
Although
you can assign an array or an XML object to the data Provider property of most
listbased
components, Flex converts the object behind the scenes to a type that
implements ICollectionView. That means that arrays get converted to a type called
mx.collections.ArrayCollection and XML and XMLList objects get converted to
mx.collections.XMLListCollection. It's generally best to always explicitly wrap the
object
as a collection first before assigning it as the data provider. That way you are
assured of
having a reference to the actual data provider collection rather than the object
wrapped
by the collection.

Using Data Grids


The preceding examples illustrated how to work with simple list-based controls such
as
lists, combo boxes, tile lists, and horizontal lists. Data grids inherit from standard
lists,
and therefore they function in much the same way. However, because data grids are
more complex than standard lists, they have behavior that is specific to them. The
following sections look at working with data grids.

Using data providers


Data grid data providers are quite similar to standard data providers except that
each
element of a data grid data provider should consist of an object whose properties
correspond to the columns of the data grid. The following example creates a data
grid
with columns named city, state, and population:
<mx:DataGrid>
<mx:ArrayCollection>
<mx:Array>

<mx:Objectcity="LosAngeles"state="CA"population="3844829"!>
<mx:Objectcity="NewYork"state="NY"population="8143197"!>
<mx:Objectcity="Chicago"state="IL"population="2842S18"!>
<mx:Objectcity="Philadelphia"state="PA"population="1463281"/>
</mx:Array>
</mx:ArrayCollection>
</mx:DataGrid>

The same result can be achieved using ActionScript. Here is an example that
displays
the same content using ActionScript:
<?xmlversion="1.0"?>
<mx:Applicationxmlns:mx=http://www.adobe.comI2006/mxml
creationComplete="creationCompleteHandler(event)">
<mx:Script>
<![CDATA[
importmx.collections.ArrayCollection;
privatefunctioncreationCompleteHandler(event:Event):void{
vararray:Array=newArray({city:"Hyderabad",
state:"CA",population:3844829},({city:"Bombay",
state:"NY",population:2345678},{({city:"Kolkata",
state:"PA",population:1463281});
varcollection:ArrayCollection=newArrayCollection(array);
grid.dataProvider=collection;
}
]]>
</mx:Script>
<mx:DataGridid="grid"width="500/>
</mx:Application>

Working with data grid columns


By default, data grids automatically display columns corresponding to all the
properties
of the data provider elements. The code in the preceding section creates a data grid
with three columns with the headings city, state, and population. Although this may
be
the intended behavior, in many cases it is not very versatile. For this reason, it is
possible to explicitly control the columns of a data grid.
You can specify which columns will display within a data grid by setting the columns
property of the data grid to an array of DataGridColumn objects. Using these
column

objects, you can filter which columns get displayed, the widths of the columns, the
edit
ability of the columns, the heading text for the columns, and more. Here is an
example
that displays the city and population values with custom labels, but does not display
the
state data.
<mx:DataGridwidth="500>
<mx:columns>
<mx:DataGridColumnheaderText="City"dataField="city"/>
<mx:DataGridColumnheaderText="Population(withincitylimits)"
dataField="population"/>
</mx:columns>
<mx:ArrayCollection>
<mx:Array>
<mx:Objectcity="Hyderabad"state="AP"population="3844829"/>
<mx:Objectcity="Bombay"state="MR"population="8143197"/>
<mx:Objectcity="Kolkata"state="WB"population="2842S18"/>
<mx:Objectcity="Bangalore"state=Karnataka"
population="1463281"!>
</mx:Array></mx:ArrayCollection></mx:DataGrid>
The Following Figure 4.13.5e illustrates the above example code.

Figure 4.13.5e Working with data grid columns

Using Tree Controls


Like data grids, tree controls inherit from standard lists but have specialized
behavior. In
the case of trees, the specialized behavior is that trees can render hierarchical data
providers. Although most lists display a linear list of elements (whether vertically,

horizontally, or in grid format), tree controls render elements that themselves have
nested child elements. These sorts of data providers are called hierarchical data
providers. The following simple XML snippet demonstrates a hierarchical
relationship in
which the cities are child elements of states.
<statelabel="AP">
<citylabel="Hyderabad"/>
</state>
<statelabel=TN">
<citylabel="Chennai"/>
</state>
A tree control can represent this sort of data. Tree controls have two types of
elements:
branch elements and leaf nodes. When a data provider element has child elements
it is
automatically treated as a branch element, meaning it is expandable within the
tree.
Here is an example that uses a tree to display state and city data.

<mx:TreelabelField="@label"width="200">
<mx:XMLListCollection>
<mx:XMLList>
<statelabel="AP">
<citylabel="Hyderabad"/><citylabel="Vizag"/></state>
<statelabel="TN">
<citylabel="Chennai"/></state>
</mx:XMLList>
</mx:XMLListCollection>
</mx:Tree>
In the above example, the tree requires a labelField property value indicating what
to
use as the label for the elements, syntax to indicate that the tree should use the
label
attributes of each XML node for the label of the corresponding tree element.
Although it is easiest to visualize hierarchical relationships with XML, you are not
restricted to using XML-based data providers for trees. Any sort of collection can be
used. For example, an ArrayCollection object can be used as a data provider.
However,

to establish hierarchical relationships using collection types that aren't intrinsically


hierarchical, certain rules must be followed. Specifically, in order to add children to
an
element, they must be added as an array for a property called children. The
following
example illustrates this using the city/state example from before.
<mx:TreelabelField="label"width="200">
<mx:ArrayCollection>
<mx:Array>
<mx:Objectlabel="AP">
<mx:children>
<mx:Objectlabel="Hyderabad"/>
<mx:Objectlabel="Vizag"/>
</mx:children>
</mx:Object>
<mx:Objectlabel="TN">
<mx:children>
<mx:Objectlabel="Chennai"/>
</mx:children>
</mx:Object>
</mx:Array>
</mx:ArrayCollection>
</mx:Tree>

The same result can be achieved using ActionScript. Here is an example that
populates
a tree using XML data.
<?xmlversion="1.0"?>
<mx:Applicationxmlns:mx=http:www.adobe.com.2006.mxml..
creationComplete="creationCompleteHandler(event)">
<mx:Script>
<![CDATA[
importmx.collections.XMLListCollection;importmx.controls.Listj
privatefunctioncreationCompleteHandler(event:Event):void
{
varxmlList:XMLList=<items>;
<itemlabel="AP">

<itemlabel="Hyderabad"/><itemlabel="Bangalore"/></item>
<itemlabel="TN">
<itemlabel="Chennai"/></item>
</items>
varcollection:XMLListC_llection=new
XMLListCollection(xmlList);
tree.dataProvider=collection;
]]>
</mx:Script>
<mx:Treeid="tree"labelField="@label"width="200"/>
</mx:Application>

Pop-Up Controls
Apart from the ability to programmatically create menus and the menu bar
navigator
there are two Flex framework controls that are used to create pop-up controls:
Popup
Button and PopUpMenuButton. Both controls are very similar, and they each may
require an understanding of menus.

Understanding Menus
Menus are an instance of mx.controls.Menu. Like tree controls, menu controls
require
hierarchical data providers. The following code creates a menu and populates it with
an
XMLListCollection data provider. It also sets the label Field property just like when
using
a hierarchical data provider for a tree control.
.
varmenu:Menu=newMenu();
varxmlList:XMLList=<items>
<itemlabel="ActionScript">
<itemlabel="Class"/>
<itemlabel="Interface"/></item>
<itemlabel="MXML">
<itemlabel="Application"/>
<itemlabel="Component"/></item>
</items>;
menu.dataProvider=newXMLListCollection(xmlList);
menu.labelField="@label";

Using PopUpButton
The PopUpButton control allows you to associate the button with a pop up, such as a
menu. Here is an example.

<?xmlversion="1.0"?>
<mx:Applicationxmlns:mx=''http://'IMW.adobe.comI2006/mxml''
layout="absolute"
creationComplete="creationCompleteHandler(event)">
<mx:Script>
<![CDATA[
importmx.controls.Menu;
importmx.collections.XMLListCollection;
privatefunctioncreationCompleteHandler(event:Event):void{
_menu=newMenu();
varxmlList:XMLList=<items>
<itemlabel="ActionScript"><itemlabel="Class"/>
<itemlabel="Interface"/>
<litem>
<itemlabel="MXML">
<itemlabel="Application"/<itemlabel="Component"/>
<item>
</items>;
_menu.dataProvider=newXMLListCollection(xmlList);
menu.labelField="@label";
button.popUp=_menu;
]]>
</mx:Script>
<mx:PopUpButtonid="button"label="NewFile"/>
</mx:Application>

Using PopUpMenuButton
The PopUpMenuButton control simplifies associating a menu with a button by
automatically creating the menu when assigning a data provider to the button, as
illustrated in this example.
<mx:PopUpMenuButtonlabelField="@label">
<mx:dataProvider><mx:XMLListCollection>
<mx:XMLList>
<itemlabel="ActionScript">
<itemlabel="Class"/>
<itemlabel="Interface"/>
<litem>
<itemlabel="MXML">
<itemlabel="Application"/>
<itemlabel="Component"/>
<litem>
</mx:XMLList></mx:XMLListCollection>
</mx:dataProvider></mx:PopUpMenuButton>

Listening to Menu Events

Menu controls dispatch itemClick events of type mx. events. MenuEvent every time
the
user selects a menu item. You can listen for the event directly from the menu using
ActionScript and addEventListener. If using PopUpMenuButton, you can listen for the
itemClick event directly from the button, and you can even use MXML to listen for
the
event, as illustrated in the following example which changes the button label each
time
the user selects a menu item:
<mx:PopUpMenuButtonid="button"labelField="@label"I
ternClick="button.label=event.label">
<mx:dataProvider>
<mx:XMLListCollection>
<mx:XMLList>
<itemlabel="ActionScript">
<itemlabel="Class"/>
<itemlabe1="Interface"/>
<litem>
<itemlabel="MXML">
<itemlabel="Application"/>
<itemlabel="Component"/>
<litem>
</mx:XMLList>
</mx:XMLListCollection>
</mx:dataProvider>
</mx:PopUpMenuButton>

Navigators
Navigators are controls that allow users to navigate from screen to screen, page to
page, section to section, or option to option within a Flex application. Navigator
controls
can be further categorized as follows: accordion, divided boxes, option bars, and
view
stacks. The accordion control consists of two or more collapsible containers. Only
one
element within an accordion can be visible at a time. The other elements in the
accordion are collapsed so that only a title bar is visible. Accordions are often good
for
processes that require several steps and allow the user to return to previous steps.
For
example, an accordion is useful when a user input form contains many sections.
Rather
than try to present all the sections at once, an accordion allows the user to view just
one section at a time, making for a more manageable experience.

Creating accordions, like most other components in Flex, is quite simple. Accordions
act
just like all standard containers in that you can nest child elements in MXML or use
addChild() to add child elements using ActionScript. In the case of accordions, all
child
elements should be containers themselves, and you should add a label property to
all
accordion children. Accordions use the label properties of child elements for the title
bar,
and also have the ability to display icons when the icon property is set. Here is an
example.
<mx:Accordion>
<mx:Formlabel="Name"icon="@Embed(source='/firstStep.png')">
<mx:FormItemlabel="FirstName">
<mx:TextInputid="first"/>
</mx:FormItem>
<mx:FormItemlabel="MiddleName">
<mx:TextInputid="middle"/>
</mx:Formltem>
<mx:FormItemlabel="LastName">
<mx:Textlnputid="last"/>
</mx:Formltem>
</mx:Form>
<mx:Formlabel="Comments">
<mx:FormItemlabe1="Comments">
<mx:TextAreaid="comments"/>
</mx:FormItem>
</mx:Form>
</mx:Accordion>

Option Bars
Option bars consist of the following: ButtonBar, LinkBar, MenuBar, and
ToggleButtonBar. Each option bar type is similar in that they provide a convenient
way
in which to create groups of controls, whether buttons, link buttons, menus, and so
on.
Additionally, option bars can be used in conjunction with view stacks. Button bars,
link
bars, and toggle button bars are ways to create horizontal or vertical groups of
buttons.
These controls provide a convenient way to group buttons together.
Also, toggle button bars have the added behavior that only one of the toggle
buttons
can be selected at a time. All button, link, and toggle button bars use data
providers.

Here is an example that creates a toggle button bar:


<mx:ToggleButtonBar>
<mx:ArrayCollection>
<mx:Array>
<mx:Objectlabel="A"/>
<mx:Objectlabel="B"/>
<mx:Objectlabel="C"/>
<mx:Objectlabel="D"/>
</mx:Array>
</mx:ArrayCollection>
</mx:ToggleButtonBar>

Figure 4.13.5f Options Bar


Menu bars provide a convenient way to group together menus with a single data
provider. Here is an example.

<mx:MenuBarlabelField="@label">
<mx:XMLListCollection>
<mx:XMLList>
<itemlabel="File">
<itemlabel="New"/>
<itemlabel="Open"/>
<itemlabel="Close"/>
<itemlabel="Properties"/>
<litem>
<itemlabel="Edit">
<itemlabel="SelectAll"/>
<itemlabel="Copy"/>
<itemlabel="Cut"/>
<itemlabel="Paste"/>
</item>

</mx:XMLList>
</mx:XMLListCollection>
</mx:MenuBar>
View stacks are used to group together a set of containers and display just one at a
time. This is useful when it is required to use a page/screen/section metaphor. The
easiest way to work with a view stack is to use the tab navigator control, which has
view
stack behavior built in. Here is an example of a tab navigator with nearly the same
form
contents used earlier in the accordion example.

<mx:TabNavigator>
<mx:Formlabel="Name">
<mx:Formltemlabel="FirstName">
<mx:Textlnputid="first"/>
</mx:Formltem>
<mx:Formltemlabel="MiddleName">
<mx:Textlnputid="middle"/>
</mx:FormItem>
<mx:Formltemlabel="LastName">
<mx:Textlnputid="last"/>
</mx:FormItem>
</mx:Form>
<mx:Formlabel="Comments">
<mx:FormItemlabel="Comments">
<mx:TextAreaid="comments"/>
</mx:Formltem>
</mx:Form>
</mx:TabNavigator>

As with the accordion, label properties can be set for the child containers of a tab
navigator to determine what the tab labels should be. The view stack can be used
without having to use the tab navigator. It simply requires that the view stack with
the
child containers should be created first. Then, whether there is a button bar, link
bar, or
toggle button bar, you can simply assign the view stack as the data provider of the
bar.
<mx:VBox>
<mx:ToggleButtonBardataProvider="{viewStack}"/>
<mx:ViewStackid="viewStack">

<mx:Formlabel="Name">
<mx:Formltemlabel="FirstName">
<mx:Textlnputid="first"/>
</mx:FormItem>
<mx:Formltemlabel="MiddleName">
<mx:TextInputid="middle"/>
</mx:FormItem>
<mx:Formltemlabel="LastName">
<mx:TextInputid="last"/>
</mx:FormItem>
</mx:Form>
<mx:Formlabel="Comments">
<mx:Formltemlabel="Comments">
<mx:TextAreaid="comments"/>
</mx:FormItem>
</mx:Form>
</mx:ViewStack>
</mx:VBox>

Otherwise, you have to set the selected Index property of the view stack
programmatically to change the view:
viewStack.selectedlndex=1;

Control bars
Control bars allow you to group together all the controls for a panel or title window.
Application control bars are the application-wide analogs to control bars. Each
allows
you to group together all the controls for that container, even if they are non
uniform
(not all buttons, etc.).
Control bars work with title window and panel components, and you should add
them as
the last child for a title window or panel. You can then place controls within the
control
bar. Here is an example.
<mx:Panelid="panel"width="250"height="200">
<mx:TextAreaid="textArea"width="80%"height="80%"
text="Example"/><mx:ControlBar>
<mx:Buttonlabel="RandomFontSize"
click="textArea.setStyle('fontSize',Math.random()*20+
8)"/>
<mx:ColorPickerid="color"
change="panel.setStyle('backgroundColor',color.value)"/>

</mx:ControlBar>
</mx:Panel>

The application control bar works similarly, but it is applied only to an application
container. By default, the application control bar scrolls with the rest of the content.
However, it is possible to set the dock property to true to dock the control panel
such
that it does not scroll. Here is how it is done.
<?xmlversion="1.0"?>
<mx:Applicationxmlns:mx=http://www.adobe.com/2oo6/mxml
layout="absolute">
<mx:Canvasx="o"y="o"width="200"height="2000"/>
<mx:ApplicationControlBardock="true">
<mx:Labeltext="JumpToSection:"/>
<mx:ComboBox><mx:dataProvider>
<mx:ArrayCollection>
<mx:Array>
<mx:String>A</mx:String>
</mx:Array>
</mx:ArrayCollection>
</mx:dataProvider>
</mx:ComboBox>
<mx:VRulewidth="20"height="28"/>
<mx:TextInput/>
<mx:Buttonlabel="Search"/>
</mx:ApplicationControlBar></mx:Application>

4.14 Summary
RIA differs from other web applications in that the presentation tier is entirely on
the client, instead of the logic lying entirely on the server side. In an RIA
application developed using Flex, the application does not post a request to
the
server every time the user makes a change.
The Flex Framework includes MXML (Macromedia XML), user interface
components and class libraries
The Flex builder provides an Integrated Development Environment built on top
the Eclipse platform to edit MXML and ActionScript. Its features include an
integrated compiler, debugger, integrated version control, code hints and
design
view. The Flex Builder contains three editors for writing MXML, ActionScript, and
CSS code.
ActionScript is the programming language that can be used along with MXML to
create stylish Flex applications. Mxml is mostly used for creating user interfaces
and laying out the front end. ActionScript can be used for data models and
client-side business logic.
Flex applications can work with XML by using Flash Player's native support.

Flash Player 9 supports two mechanisms for working with XML: a legacy
XMLDocument class and the new XML class that implements the ECMAScript for
XML (E4X) standard.
ActionScript 3.0 supports class reflection using the functions in the flash.utils
package.
Flex simplifies application layout with MXML and Flexs layout containers,
enabling developers to create applications without having to write a single line of
custom layout code.
All UI components and layout components are related because they inherit from
a common superclass called mx.core.UIComponent which is part of the Flex
framework.

Lesson 5
Web 3.0 An Introduction
5.1 Lesson Objectives
Web 3.0, refers to a supposed third generation of Internet-based services that
collectively comprise what might be called 'the intelligent Web'. The term "Web 3.0"
has
been introduced to hypothesize about a future wave of Internet innovation. This
lesson
traces the history and evolution of the World Wide Webs evolution besides
explaining

related terminology. The lesson also provides an explanation on Mashup web


applications and categories of Mashups with examples. The lesson also provides a
discussion on other important concepts such as web services within the Flex
framework
and ontologies.

5.2 Mashups using Flex and Ajax


In technology, a mashup is a web application that combines data from more than
one
source into a single integrated tool; an example is the use of cartographic data from
Google Maps to add location information to real-estate data, thereby creating a new
and
distinct web service that was not originally provided by either source.
Content used in mashups is typically sourced from a third party via a public
interface or
API (web services), although some in the community believe that cases where
private
interfaces are used should not count as mashups. Other methods of sourcing
content for
mashups include Web feeds (e.g. RSS or Atom), and screen scraping. Many people
are
experimenting with mashups using Amazon, eBay, Flickr, Google, Microsoft, Yahoo
and
YouTube APIs, which has led to the creation of the mashup editor.
The architecture of Mashup web applications is always composed of three parts:
The content provider - It is the source of the data. Data is made available using
an API and different Web-protocols such as RSS, REST, and Web Service.
The Mashup site - It is the web application, which provides the new service,
using different data sources that are not owned by it.
The client web browser- It is the user interface of the Mashup. In a web
application, the content can be mashed by the client web browsers using client
side web language for example JavaScript.

Mashups should be differentiated from simple embedding of data from another site
to
form compound documents. A site that allows a user to embed a Youtube video for
instance, is not a mashup site. As outlined above, the site should itself access 3rd
party
data using an API, and process that data in some way to increase its value to the
sites's

users.

5.2.1 Types of Mashups


Mashups currently come in three general flavors: consumer mashups, data
mashups,
and business mashups.
The best known type is the consumer mashup, best exemplified by the many
Google
Maps applications. Consumer mashups combine data elements from multiple
sources,
hiding this behind a simple unified graphical interface.
Other common types are "data mashups" and "enterprise mashups". A data mashup
mixes data of similar types from different sources (see Yahoo Pipes), as for example
combining the data from multiple RSS feeds into a single feed with a graphical front
end. An enterprise mashup (see JackBe), usually integrates data from internal and
external sources - for example, it could create a market share report by combining
an
external list of all houses sold in the last week with internal data about which
houses
one agency sold.
A business mashup is a combination of all the above, focusing on both data
aggregation
and presentation, and additionally adding collaborative functionality, making the
end
result suitable for use as a business application. Mashups within mashups are
known as
'monster mashups'.

5.3 Understanding Mashup Building


Platforms for Business Applications
This section explores trends in the mashup space and the types of tools used to
build
and distribute mashups. Some of the most common approaches, or styles, for doing
mashups include:
Server-Side Mashups
Mashup can be designed in various ways. In one approach, called a server-side
mashup,
also known as a proxy-style mashup, services and content can be integrated on the
server. There are a number of good reasons for using the server-side mashup
approach.

This approach overcomes browser security restrictions that constrain


XMLHttpRequests
and the ability to access web sites across domains.

Client-Side Mashups
In a client-side mashup, the service or content integration takes place in the client,
which is typically a web browser. This is in contrast to a server-side mashup, where
the
service or content integration takes place in the server. A server-side mashup is also
called a proxy-style mashup because a component in the server acts as a proxy to
the
service.

5.3.1 Build Mashups With the Service Component


Architecture and Apache Tuscany
Service Component Architecture provides a flexibility of composition, reuse, and
technology and deployment choice that makes it an ideal environment in which to
build
and run mashup applications. This paper describes the Alert Aggregator sample, a
mashup style application with a Web 2.0 interface, which has been recently
developed
for the Apache Tuscany SCA Native runtime.

Examples
Mashups can be divided into four main categories, mapping, video & photo, search
&
shopping and news. Some examples of each are:
Mapping
Chicago Crime

The Chicago Police Department has a mashup which integrates


the departments database of reported crimes with Google Maps
in order to help stop crime in areas and warn citizens of areas
where the crime rate is high.
WikiCrimes

WikiCrimes is a wiki-style website where internet users can report


crimes by placing pins on a GoogleMaps based map. The website
classifies crimes as Robbery, Theft or Other by pin colour
Video and Photo
Flickr
Flickr is an image storage site that allows users to organise their
collection of images and share them. Through the use of its
Application Programming Interface (API) the content can be used
by other sites to create a mashup. Flickrvision is an example of a
mashup made using Flickr's API.
Search and Shopping
Travature
Travature is a travel portal which has integrated airfare meta
search engines, wiki travel guides, hotel reviews. It also allows the
user to share photos and discuss experiences with other
travellers.

News
Digg

Mashup of various news websites controlled almost entirely by the


users of the website.

5.4 Web Services in Flex


5.4.1 Flex Data Communications Overview
Why communicate?

For a Flex application to get fresh data from a database or other webservice
To send current data to end-users
Three-Tiered applications
Data -> View -> Controller

Data Communication Basics


Flex currently supports three types of data communications with external sources:

XML via HTTP Requests


SOAP Web-Services

Remote Objects

Web-Services
A web service is application functionality that can be published and consumed over
the
Internet.
Types
Publish a web service to make application functionality available for remote
users to use.
Consume a web service to access remote functionality to perform an
application task.

How does a Web Service Work?

SOAP or Web-Services can easily be called using the <mx:WebService> component.


Web Services allow you to communicate data back to the web-server, and retrieve
typed
objects (strings, numbers, arrays, queries)
Because it is based on XML, it is very verbose, and often slow for large sets of data.
How to use a web service in Flex
Place the <mx:WebService> tag at the root level of the document (application or
component) that you are working on.

Common Parameters of yhr <mx:WebService> tag


id Used to name the object
wsdl Points to the WSDL (Web Service Descriptor) file. This file is different for each
language
showBusyCursor Changes the current pointer to a rotating clock to let the user
know
something is happening.
Passing parameters:
You can pass parameters to web-services by naming operations (methods or
functions).
The operation tag allows for result or fault functions

5.5 The Semantic Web (Web 3.0)

Following the introduction of the phrase "Web 2.0" as a description of the recent
evolution of the Web, the term "Web 3.0" has been introduced to hypothesize about
a
future wave of Internet innovation. Views on the next stage of the World Wide Web's
evolution vary greatly, from the concept of emerging technologies such as the
Semantic
Web transforming the way the Web is used (and leading to new possibilities in
artificial
intelligence) to the observation that increases in Internet connection speeds,
modular
web applications, and advances in computer graphics will play the key role in the
evolution of the World Wide Web.

5.5.1 Proposed expanded definition


Web 3.0, refers to a supposed third generation of Internet-based services that
collectively comprise what might be called 'the intelligent Web'such as those
using
semantic web, microformats, natural language search, data-mining, machine
learning,
recommendation agents, and artificial intelligence technologieswhich emphasize
machine-facilitated understanding of information in order to provide a more
productive
and intuitive user experience.
Web 3.0 is the third decade of the Web (20102020) during which suggests several
major complementary technology trends will reach new levels of maturity
simultaneously
to include:
transformation of the Web from a network of separately siloed applications and
content repositories to a more seamless and interoperable whole.
ubiquitous connectivity, broadband adoption, mobile Internet access and mobile
devices;

network computing, software-as-a-service business models, Web services


interoperability, distributed computing, grid computing and cloud computing;
open technologies, open APIs and protocols, open data formats, open-source
software platforms and open data (e.g. Creative Commons, Open Data License);
open identity, OpenID, open reputation, roaming portable identity and personal
data.
the intelligent web, Semantic Web technologies such as RDF, OWL, SWRL,
SPARQL,
GRDDL, semantic application platforms, and statement-based datastores;
distributed databases, the "World Wide Database" (enabled by Semantic Web
technologies); and
intelligent applications, natural language processing, machine learning, machine
reasoning, autonomous agents.

Figure 5.5.1 Evolution of the World Wide Web


The traditional World Wide Web, also known as Web 1.0, is a Read-or-Write Web. In
particular, authors of web pages write down what they want to share and then
publish it
online. Web readers can watch these web pages and subjectively comprehend the
meanings. Unless writers willingly release their contact information in their authored
web pages, the link between writers and readers is generally disconnected on Web
1.0.
By leaving public contact information, however, writers have to disclose their
private
identities (such as emails, phone numbers, or mailing addresses). In short, Web 1.0
connects people to a public, shared environment World Wide Web. But Web 1.0
essential does not facilitate direct communication between web readers and writers.
The second stage of web evolution is Web 2.0. Though its definition is still vague,
Web

2.0 is a Read/Write Web. At Web 2.0, not only writers but also readers can both read
and write to a same web space. This advance allows establishing friendly social
communication among web users without obligated disclosure of private identities.
Hence it significantly increases the participating interest of web users. Normal web
readers (not necessarily being a standard web author simultaneously) then have a
handy way of telling their viewpoints without the need of disclosing who they are.
The link between web readers and writers becomes generally connected, though
many of
the specific connections are still anonymous. Whether there is default direction
communication between web readers and writers is a fundamental distinction
between
Web 1.0 and Web 2.0. In short, Web 2.0 not only connects individual users to the
Web,
but also connects these individual uses together. It fixes the previous disconnection
between web readers and writers.
We dont know precisely what the very next stage of web evolution is at this
moment.
However, many of us believe that semantic web must be one of the future stages.
Following the last two paradigms, an ideal semantic web is a Read/Write/Request
Web.
The fundamental change is still at web space. A web space will be no longer a
simple
web page as on Web 1.0. Neither will a web space still be a Web-2.0-style blog/wiki
that
facilitates only human communications. Every ideal semantic web space will
become a
little thinking space. It contains owner-approved machine-processable semantics.
Based
on these semantics, an ideal semantic web space can actively and proactively
execute
owner-specified requests by themselves and communicate with other semantic web
spaces. By this augmentation, a semantic web space simultaneously is also a living
machine agent. We had a name for this type of semantic web spaces as Active
Semantic Space (ASpaces). (An introductory scientific article about ASpaces can be
found at here for advanced readers.) In short, Semantic Web, when it is realized, will
connect virtual representatives of real people who use the World Wide Web. It thus
will
significantly facilitate the exploration of web resources.
A practical semantic web requires every web user to have a web space by himself.
Though it looks abnormal at first glimpse, this requirement is indeed fundamental. It
is
impossible to imagine that humans still need to perform every request by
themselves on
a semantic web. If there are no machine agents help humans process the
machineprocessable

data on a semantic web, why should we build this type of semantic web
from the beginning? Every semantic web space is a little agent. So every semantic
web
user must have a web space. The emergence of Semantic Web will eventually
eliminate
the distinction between readers and writers on the Web. Every human web user
must
simultaneously be a reader, a writer, and a requester; or maybe we should rename
them to be web participators.
In summary, Web 1.0 connects real people to the World Wide Web. Web 2.0
connects real people who use the World Wide Web. The future semantic web,
however, will connect virtual representatives of real people who use the World
Wide Web. This is a simple story of web evolution.

5.6 RDF ( Resource Description Framework)


The Resource Description Framework (RDF) is originally designed as a metadata
data model, which has come to be used as a general method of modeling
information
through a variety of syntax formats.
The RDF metadata model is based upon the idea of making statements about Web
resources in the form of subject-predicate-object expressions, called triples in RDF
terminology. The subject denotes the resource, and the predicate denotes traits or
aspects of the resource and expresses a relationship between the subject and the
object. For example, one way to represent the notion "The sky has the color blue" in
RDF is as the triple: a subject denoting "the sky", a predicate denoting "has the
color",
and an object denoting "blue". RDF is an abstract model with several serialization
formats (i.e., file formats), and so the particular way in which a resource or triple is
encoded varies from format to format.
This mechanism for describing resources is a major component in Semantic Web
activity: an evolutionary stage of the World Wide Web in which automated software
can
store, exchange, and use machine-readable information distributed throughout the
Web,
in turn enabling users to deal with the information with greater efficiency and
certainty.
RDF's simple data model and ability to model disparate, abstract concepts has also
led
to its increasing use in knowledge management applications unrelated to Semantic
Web
activity.

5.7 Ontologies
In both computer science and information science, an ontology is a formal
representation of a set of concepts within a domain and the relationships between
those
concepts. It is used to reason about the properties of that domain, and may be used
to
define the domain.
Ontologies are used in artificial intelligence, the Semantic Web, software
engineering,
biomedical informatics, library science, and information architecture as a form of
knowledge representation about the world or some part of it. Common components
of
ontologies include:
Individuals: instances or objects (the basic or "ground level" objects)
Classes: sets, collections, concepts, types of objects, or kinds of things.
Attributes: aspects, properties, features, characteristics, or parameters that
objects (and
classes) can have
Relations: ways in which classes and individuals can be related to one another
Function terms: complex structures formed from certain relations that can be used
in
place of an individual term in a statement
Restrictions: formally stated descriptions of what must be true in order for some
assertion to be accepted as input
Rules: statements in the form of an if-then (antecedent-consequent) sentence that
describe the logical inferences that can be drawn from an assertion in a particular
form
Axioms: assertions (including rules) in a logical form that together comprise the
overall
theory that the ontology describes in its domain of application. This definition differs
from that of "axioms" in generative grammar and formal logic. In these disciplines,
axioms include only statements asserted as a priori knowledge. As used here,
"axioms"

also include the theory derived from axiomatic statements.


Events: the changing of attributes or relations
Ontologies are commonly encoded using ontology languages.

5.7.1 Elements of an Ontology


Contemporary ontologies share many structural similarities, regardless of the
language
in which they are expressed. As mentioned above, most ontologies describe
individuals
(instances), classes (concepts), attributes, and relations. In this section each of
these
components is discussed in turn.
Individuals
Individuals (instances) are the basic, "ground level" components of an ontology. The
individuals in an ontology may include concrete objects such as people, animals,
tables,
automobiles, molecules, and planets, as well as abstract individuals such as
numbers
and words (although there are differences of opinion as to whether numbers and
words
are classes or individuals). Strictly speaking, an ontology need not include any
individuals, but one of the general purposes of an ontology is to provide a means of
classifying individuals, even if those individuals are not explicitly part of the
ontology.
In formal extensional ontologies, only the utterances of words and numbers are
considered individuals the numbers and names themselves are classes. In a 4D
ontology, an individual is identified by its spatio-temporal extent. Examples of
formal
extensional ontologies are ISO 15926 and the model in development by the IDEAS
Group.
Classes
Classes concepts that are also called type, sort, category, and kind can be
defined as
an extension or an intension. According to an extensional definition, they are
abstract
groups, sets, or collections of objects. According to an intensional definition, they
are
abstract objects that are defined by values of aspects that are constraints for being
member of the class. The first definition of class results in ontologies in which a
class is
a subclass of collection. The second definition of class results in ontologies in which
collections and classes are more fundamentally different. Classes may classify
individuals, other classes, or a combination of both. Some examples of classes:

Person, the class of all people, or the abstract object that can be described by the
criteria for being a person.
Vehicle, the class of all vehicles, or the abstract object that can be described by the
criteria for being a vehicle.
Car, the class of all cars, or the abstract object that can be described by the criteria
for
being a car.
Class, representing the class of all classes, or the abstract object that can be
described
by the criteria for being a class.
Thing, representing the class of all things, or the abstract object that can be
described
by the criteria for being a thing (and not nothing).
Ontologies vary on whether classes can contain other classes, whether a class can
belong to itself, whether there is a universal class (that is, a class containing
everything), etc. Sometimes restrictions along these lines are made in order to
avoid
certain well-known paradoxes.
The classes of an ontology may be extensional or intensional in nature. A class is
extensional if and only if it is characterized solely by its membership. More
precisely, a
class C is extensional if and only if for any class C', if C' has exactly the same
members
as C, then C and C' are identical. If a class does not satisfy this condition, then it is
intensional. While extensional classes are more well-behaved and well-understood
mathematically, as well as less problematic philosophically, they do not permit the
fine
grained distinctions that ontologies often need to make. For example, an ontology
may
want to distinguish between the class of all creatures with a kidney and the class of
all
creatures with a heart, even if these classes happen to have exactly the same
members.
In most upper ontologies, the classes are defined intensionally. Intensionally defined
classes usually have necessary conditions associated with membership in each
class.
Some classes may also have sufficient conditions, and in those cases the
combination of
necessary and sufficient conditions make that class a fully defined class.
Importantly, a class can subsume or be subsumed by other classes; a class
subsumed
by another is called a subclass (or subtype) of the subsuming class (or supertype).
For
example, Vehicle subsumes Car, since (necessarily) anything that is a member of
the

latter class is a member of the former. The subsumption relation is used to create a
hierarchy of classes, typically with a maximally general class like Anything at the
top,
and very specific classes like 2002 Ford Explorer at the bottom. The critically
important
consequence of the subsumption relation is the inheritance of properties from the
parent
(subsuming) class to the child (subsumed) class. Thus, anything that is necessarily
true
of a parent class is also necessarily true of all of its subsumed child classes. In some
ontologies, a class is only allowed to have one parent (single inheritance), but in
most
ontologies, classes are allowed to have any number of parents (multiple
inheritance),
and in the latter case all necessary properties of each parent are inherited by the
subsumed child class. Thus a particular class of animal (HouseCat) may be a child of
the
class Cat and also a child of the class Pet.

A partition is a set of related classes and associated rules that allow objects to be
classified by the appropriate subclass. The rules correspond with the aspect values
that
distinguish the subclasses from the superclasses. For example, to the right is the
partial
diagram of an ontology that has a partition of the Car class into the classes 2-Wheel
Drive Car and 4-Wheel Drive Car. The partition rule (or subsumption rule)
determines if
a particular car is classified by the 2-Wheel Drive Car or the 4-Wheel Drive Car class.
If the partition rule(s) guarantee that a single Car cannot be in both classes, then
the
partition is called a disjoint partition. If the partition rules ensure that every
concrete
object in the super-class is an instance of at least one of the partition classes, then
the
partition is called an exhaustive partition.
Attributes
Objects in an ontology can be described by relating them to other things, typically

aspects or parts. These related things are often called attributes, although they may
be
independent things. Each attribute can be a class or an individual. The kind of
object
and the kind of attribute determine the kind of relation between them. A relation
between an object and an attribute express a fact that is specific to the object to
which
it is related. For example the Ford Explorer object has attributes such as:
<has as name> Ford Explorer
<has by definition as part> door (with as minimum and maximum cardinality: 4)
<has by definition as part one of> {4.0L engine, 4.6L engine}
<has by definition as part> 6-speed transmission
The value of an attribute can be a complex data type; in this example, the related
engine can only be one of a list of subtypes of engines, not just a single thing.
Ontologies are only true ontologies if concepts are related to other concepts (the
concepts do have attributes). If that is not the case, then you would have either a
taxonomy (if hyponym relationships exist between concepts) or a controlled
vocabulary.
These are useful, but are not considered true ontologies.
Relationships
Relationships (also known as relations) between objects in an ontology specify how
objects are related to other objects. Typically a relation is of a particular type (or
class)
that specifies in what sense the object is related to the other object in the ontology.
For
example in the ontology that contains the concept Ford Explorer and the concept
Ford
Bronco might be related by a relation of type <is defined as a successor of>. The
full
expression of that fact then becomes:
Ford Explorer is defined as a successor of : Ford Bronco
This tells us that the Explorer is the model that replaced the Bronco. This example
also
illustrates that the relation has a direction of expression. The inverse expression
expresses the same fact, but with a reverse phrase in natural language.
Much of the power of ontologies comes from the ability to describe relations.
Together,
the set of relations describes the semantics of the domain. The set of used relation
types (classes of relations) and their subsumption hierarchy describe the expression
power of the language in which the ontology is expressed.
The most important type of relation is the subsumption relation (is-a-superclass-of,
the
converse of is-a, is-a-subtype-of or is-a-subclass-of). This defines which objects are

classified by which class. For example we have already seen that the class Ford
Explorer
is-a-subclass-of 4-Wheel Drive Car, which in turn is-a-subclass-of Car:

addition of the is-a-subclass-of relationships creates a hierarchical taxonomy; a


tree-like structure (or, more generally, a partially ordered set) that clearly depicts
how
objects relate to one another. In such a structure, each object is the 'child' of a
'parent
class' (Some languages restrict the is-a-subclass-of relationship to one parent for all
nodes, but many do not).
Another common type of relations is the meronymy relation, written as part-of, that
represents how objects combine together to form composite objects. For example, if
we
extended our example ontology to include concepts like Steering Wheel, we would
say
that a "Steering Wheel is-by-definition-a-part-of-a Ford Explorer" since a steering
wheel
is always one of the components of a Ford Explorer. If we introduce meronymy
relationships to our ontology, we find that this simple and elegant tree structure
quickly
becomes complex and significantly more difficult to interpret manually. It is not
difficult
to understand why; a class of which is described that there is always a member that
is a
part of a member of another class might also have a member that is part of a
member
of a third class. Consequently, classes may be part of more than one whole class.
The
structure that emerges is known as a directed acyclic graph (DAG).
As well as the standard is-a-subclass-of and is-by-definition-a-part-of-a relations,
ontologies often include additional types of relations that further refine the
semantics
they model. Ontologies might distinguish between different categories of relation
types.
For example:

relation
relation
relation
relation
relation

types
types
types
types
types

for
for
for
for
for

relations
relations
relations
relations
relations

between
between
between
between
between

classes
individuals
an individual and a class
a single object and a collection
collections

Relation types are sometimes domain-specific and are then used to store specific
kinds
of facts or to answer particular types of questions. If the definitions of the relation
types
are included in an ontology, then the ontology defines its own ontology definition
language. An example of an ontology that defines its own relation types and
distinguishes between various categories of relation types is the Gellish ontology.
For example in the domain of automobiles, we might need a made-in type
relationship
which tells us where each car is built. So the Ford Explorer is made-in Louisville. The
ontology may also know that Louisville is-located-in Kentucky and Kentucky isclassifiedasa state and is-a-part-of the USA. Software using this ontology could now answer a
question like "which cars are made in the USA?"

5.7.2 Domain ontologies and upper ontologies


A domain ontology (or domain-specific ontology) models a specific domain, or part
of
the world. It represents the particular meanings of terms as they apply to that
domain.
For example the word card has many different meanings. An ontology about the
domain
of poker would model the "playing card" meaning of the word, while an ontology
about
the domain of computer hardware would model the "punch card" and "video card"
meanings.
An upper ontology (or foundation ontology) is a model of the common objects that
are
generally applicable across a wide range of domain ontologies. It contains a core
glossary in whose terms objects in a set of domains can be described. There are
several
standardized upper ontologies available for use, including Dublin Core, GFO,
OpenCyc/ResearchCyc, SUMO, and DOLCE. WordNet, while considered an upper
ontology by some, is not an ontology: it is a unique combination of a taxonomy and
a
controlled vocabulary (see above, under Attributes).

The Gellish ontology is an example of a combination of an upper and a domain


ontology.
Since domain ontologies represent concepts in very specific and often eclectic ways,
they are often incompatible. As systems that rely on domain ontologies expand,
they
often need to merge domain ontologies into a more general representation. This
presents a challenge to the ontology designer. Different ontologies in the same
domain
can also arise due to different perceptions of the domain based on cultural
background,
education, ideology, or because a different representation language was chosen.
At present, merging ontologies is a largely manual process and therefore
timeconsuming
and expensive. Using a foundation ontology to provide a common definition
of core terms can make this process manageable. There are studies on generalized
techniques for merging ontologies, but this area of research is still largely
theoretical.

5.7.3 Ontology languages


An ontology language is a formal language used to encode the ontology. There are a
number of such languages for ontologies, both proprietary and standards-based:

OWL is a language for making ontological statements, developed as a followon


from RDF and RDFS, as well as earlier ontology language projects including

OIL,
DAML and DAML+OIL. OWL is intended to be used over the World Wide
Web,

and all its elements (classes, properties and individuals) are defined as RDF
resources, and identified by URIs.
KIF is a syntax for first-order logic that is based on S-expressions.
The Cyc project has its own ontology language called CycL, based on firstorder
predicate calculus with some higher-order extensions.
Rule Interchange Format (RIF) and F-Logic combine ontologies and rules.
The Gellish language includes rules for its own extension and thus integrates
an
ontology with an ontology language.

5.7.4 Web Ontology language (OWL)


The Web Ontology Language (OWL) is a family of knowledge representation
languages for authoring ontologies, and is endorsed by the World Wide Web
Consortium. This family of languages is based on two (largely, but not entirely,
compatible) semantics: OWL DL and OWL Lite semantics are based on Description
Logics, which have attractive and well-understood computational properties, while
OWL
Full uses a novel semantic model intended to provide compatibility with RDF
Schema.
OWL ontologies are most commonly serialized using RDF/XML syntax. OWL is
considered one of the fundamental technologies underpinning the Semantic Web,
and
has attracted both academic and commercial interest.

5.8 Summary
A mashup is a web application that combines data from more than one source
into a single integrated tool. Mashups currently come in three general flavors:
consumer mashups, data mashups, and business mashups. Mashups can be
divided into four main categories, mapping, video & photo, search & shopping
and news.
A web service is application functionality that can be published and consumed
over the Internet. SOAP or Web-Services can easily be called from within a Flex

application using the <mx:WebService> component.


Web 3.0 is the third decade of the Web (20102020) during which suggests
several major complementary technology trends will reach new levels of
maturity.
An ontology is a formal representation of a set of concepts within a domain and
the relationships between those concepts. Ontologies are used in artificial
intelligence, the Semantic Web, software engineering, biomedical informatics,
library science, and information architecture as a form of knowledge
representation about the world or some part of it.
Most ontologies describe individuals (instances), classes (concepts), attributes,
and relations.
An ontology language is a formal language used to encode the ontology. For
example, OWL is a language for making ontological statements.

You might also like