Professional Documents
Culture Documents
Lesson1 Web2.0 An Introduction
Lesson1 Web2.0 An Introduction
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.
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.
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.
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.
VoiceXML
Interpreter;generate events in response to user actions and system
events;require: audio output(TTS, audio files),audio input (SR,audio record, DTMF).
Information retrieval
Electronic transactions
Telephone services Call centers
Voice e-mail
Voice Access Control Voice Recognition
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.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.
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.4.1 String
The String object is used to manipulate a string literal. The properties and methods
of String
objects are shown below.
Description
Constructor
Length
Prototype
Method
anchor()
big()
Description
Creates an HTML anchor
Displays a string in a big font
blink()
bold()
charAt()
charCodeAt()
concat()
fixed()
fontcolor()
fontsize()
fromCharCode()
indexOf()
italics()
lastIndexOf()
link()
match()
replace()
search()
slice()
small()
split()
strike()
sub()
substr()
substring()
sup()
toLowerCase()
toUpperCase()
toSource()
valueOf()
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.
Description
Constructor
Prototype
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.
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
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()
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.
Description
A reference to the function that created the object
Allows you to add properties and methods to the object
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.
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
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
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)
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
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
<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.
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.
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.
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>
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: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
<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.
<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
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();
}
}
}
}
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
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.
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.
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
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.
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.
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.
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.
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
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.
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
<!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
portType
binding
service
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.
HTTP
URL
XML/HTML/GIF/JPEG/etc (Resource Representations)
text/xml, text/html, image/gif, image/jpeg, etc (MIME Types)
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.
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.
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
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.
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:
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.
System Manager
Timeline>
Frame1
Frame2
preloder
Application
Flex framework used
By application
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.
<!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.
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);
}
}
}
each mode contains its own collection of supporting views. For an overview of the
Flex
Development perspective, see The Flex Development perspective.
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
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.
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
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
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;
}
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=[];
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.
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.
}
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>
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);
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());
}
</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.
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.
<mx:TextInput/>
<mx:Buttonlabel="Submit"/>
</mx:Application>
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.
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
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
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
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;
}
}
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
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.
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).
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.
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.
Data models
<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>
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.
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,
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>
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.
<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
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.
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.
Examples
Mashups can be divided into four main categories, mapping, video & photo, search
&
shopping and news. Some examples of each are:
Mapping
Chicago Crime
News
Digg
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
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.
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.
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.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"
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:
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?"
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.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