# XML - Managing Data Exchange/XUL

+-----------------------------------------------+
| **Learning objectives**                       |
|                                               |
| -   Get a brief overview of what XUL is.      |
| -   Learn about the basic tag/widget library. |
| -   Create some simple, static XUL web pages. |
| -   Add event handlers to a XUL page.         |
+-----------------------------------------------+
|                                               |
+-----------------------------------------------+

## Introduction

XUL (pronounced zool and rhymes with cool), which stands for eXtensible
User interface Language, is an XML-based user interface language
originally developed for use in the Netscape browser. It is now
maintained by Mozilla. It is a part of Mozilla Firefox and many other
Mozilla applications, and is available as part of Gecko, the rendering
engine developed by Mozilla. In fact, XUL is powerful enough that the
entire user interface in the Firefox application is implemented in XUL.

Like HTML, in XUL you can create an interface using a relatively simple
markup language, define the appearance with CSS style sheets, and use
JavaScript to manipulate behavior. Unlike HTML, however, XUL provides a
rich set of user interface widgets to create, for example, menus,
toolbars and tabbed panels.

To put it in simple terms, XUL can be used to create lightweight,
cross-platform, cross-device user interfaces.

Many applications are developed using features of a specific platform
that makes building cross-platform software time-consuming and costly.
Some users may want to use an application on technologies other than
traditional computers, such as small handheld devices. To date, there
have been some cross-platform solutions already developed. Java, for
example, was created just for such a purpose. However, creating GUIs
with Java is cumbersome at best. Alternatively, XUL has been designed
for building portable user interfaces easily and quickly. It is
available on most versions of Windows, Mac OS X, Linux and Unix. Yahoo!
currently uses XUL and related technologies for its Yahoo! tool bar (a
Firefox extension) and Photomail application.

To illustrate XUL's potential, this chapter will work through a few
examples. Potential is the correct word here. The full capabilities of
XUL are beyond the scope of this chapter but it is designed to give the
reader a first look at the power of XUL. One more thing needs to be
noted: you'll need a Gecko-based browser (such as Firefox or the Mozilla
Suite) or XULRunner to
work with XUL.

## The Basics

XUL is XML, and like all good XML files, a good XUL file begins with the
standard XML version declaration. Currently, XUL is using the XML
version 1.0.

To make your XUL page look good, you must include a *global* stylesheet
in it. The URI of the default stylesheet is *href =
\"<chrome://global/skin/>\"*. While you can load as many stylesheets as
you like, it is best practice to load the global stylesheet initially.
Look at Fig.1. Notice the reference to "chrome". 'The chrome is the part
of the application window that lies outside of a window\'s content area.
Toolbars, menu bars, progress bars, and window title bars are all
examples of elements that are typically part of the chrome.'(1) Chrome
is the descriptive term used to name all of the elements in a XUL
application. Think of it like the chrome on the outside of a car. It's
what catches your eye. The elements in a XUL file are what you see in
the browser window.

All XML documents must have a namespace declaration. The developers of
XUL have provided a namespace that shows where they came up with the
name XUL. (The reference is from the movie 'Ghostbusters' for the
uninitiated)

``` XML
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window
   id="window identifier"
   title="XUL page"
   orient="horizontal"
   xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
   . . . (add elements here)
</window>
```

The next thing to note is the tag `<window>`{=html}. This tag is
analogous to the

```{=html}
<body>
```
tag in HTML. All the elements will live inside the window tag. In Fig. 1
the window tag has three attributes that are very important. The 'id'
attribute is important in that it is the way to identify the window so
that scripts can refer to it. While the title attribute is not
necessary, it is good practice to provide a descriptive name. The value
of title will be displayed in the title bar of the window. The next
attribute is very important. This tells the browser in what direction to
lay out the elements described in the XUL file. Horizontal means just
that. Lay out in succession across the window. Vertical is the opposite;
it adds the elements in column format. Vertical is the default value so
if you do not declare this attribute you'll get vertical orientation.

As was stated earlier, a XUL document is used to create user interfaces.
UI\'s are generally full of interactive components such as text boxes,
buttons and the like. A XUL document accomplishes this with the use of
widgets, which are self-contained components with pre-defined behavior.
For example buttons will respond to mouse clicks and menu bars can hold
buttons. All the normally accepted actions of GUI components are built
in to the widgets. There is already a rich library of predefined
widgets, but because this is open source, any one can define a widget or
a set of widgets for themselves.

The widgets are 'disconnected' until they are programmed to work
together. This can be done simply with JavaScript or a more complex
application can be made using something like C++ or Java. In this
chapter we will use JavaScript to illustrate XUL's uses and potential.

Also, a XUL file should have .xul extension. The Mozilla browser will
automatically recognize it and know what to do with it when you click on
it. Optionally, an .xml extension could be used but you would have to
open the file within the browser.

One more thing needs to be mentioned. There are a few syntax rules to
follow and they are:

-   All events and attributes must be written in lowercase.
-   All strings must be double quoted.
-   Every XUL widget must use close tags (either
    `<tag>`{=html}`</tag>`{=html} or `<tag/>`{=html}) to be well-formed.
-   All attributes must have a value.

## A First Example

What better way to start then with the good old 'Hello World' example.
Open up a text editor (not MS Word) like notepad or TextPad and type in:

``` XML
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window
id="Hello"
title="Hello World Example"
orient="vertical"
persist="screenX screenY width height"
xmlns= "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

<description style='font-size:24pt'>Hello World</description>
<description value='Hello World' style='font-size:24pt'/>
<label value = 'Hello World'  style='font-size:24pt'/>
</window>
```

Save it anywhere but be sure to give the file the .xul extension. Now
just double click on it and it should open in your Mozilla or Netscape
browser. You should get 'Hello World' three times, one on top of the
other. Notice the different ways that 'Hello World' was printed: twice
from a description tag and once from a label tag. Both
`<description>`{=html} and `<label>`{=html} are text related tags. Using
the description tag is the only way to write text that is not contents
of a 'value' attribute. This means that you can write text that isn\'t
necessarily assigned to a variable. In the second and third examples the
text is expressed as an attribute to the tag description or label,
respectively. You can see here that the orient attribute in window is
set to 'vertical'. That is why the text is output in a column.
Otherwise, if orient was set to 'horizontal', all the text would be on
one line. Try it.

Now let's start adding some more interesting elements.

## Adding Widgets

As stated earlier, XUL has an existing rich library of elements fondly
called widgets. These include buttons, text boxes, progress bars,
sliders and a host of other useful items. One good listing is the XUL
Programmer\'s Reference.

Let us take a look at some simple buttons. Enter the following code and
place it into a Notepad or other text editor that is not MS Word.

``` XML
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window
id="findfile-window"
title="Find Files"
orient="horizontal"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

<button id="find-button" label="Find" default="true"/>
<button id="cancel-button" label="Cancel"/>

</window>
```

Save it and give the file the .xul extension. Open a Mozilla or Netscape
browser and open the file from the browser. You should see a \"find\"
button and a \"cancel button\". From here it is possible to add more
functionality and build up elaborate interfaces.

There has to be some place to put all of these things and like the

```{=html}
<body>
```
tag in HTML, the `<box>`{=html} tag in XUL is used to house the widgets.
In other words, boxes are containers that encapsulate other elements.
There are a number of different `<box>`{=html} types. In this example
we'll use `<hbox>`{=html}, `<vbox>`{=html}, `<toolbox>`{=html} and
`<tabbox>`{=html}.

`<hbox>`{=html} and `<vbox>`{=html} are synonymous with the attributes
\'orient = \"horizontal\"\' and \'orient = \"vertical\"\', which
respectively form the `<window>`{=html} tag. By using these two boxes,
discrete sections of the window can have their own orientation. These
two elements can hold all of the other elements and can even be nested.

The tags `<toolbox>`{=html} and `<tabbox>`{=html} serve special
purposes. `<toolbox>`{=html} is used to create tool bars at the top or
bottom of the window while `<tabbox>`{=html} sets up a series of tabbed
sheets in the window.

Take the XUL framework from Fig. 1 and replace \". . .( add elements
here)\" with a `<vbox>`{=html} tag pair (that\'s both open and close
tags). This will be the outside container for the rest of the elements.
Remember, the `<vbox>`{=html} means that elements will be positioned
vertically in order of appearance. Add the attribute \'flex=\"1\"\'.
This will make the menu bar extend all the way across the window.

``` XML
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window
id="findfile-window"
title="Find Files"
orient="horizontal"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

<vbox flex="1">
    (... add elements here)
</vbox>

</window>
```

The \'flex\' attribute needs some explanation since it is a primary way
of sizing and positioning the elements on a page. Flex is a dynamic way
of sizing and positioning widgets in a window. The higher the flex
number (1 being highest), the more that widget gets priority sizing and
placement over widgets with lower flex settings. All elements have size
attributes, such as width and/or height, that can be set to an exact
number of pixels but using flex insures the same relative sizing and
positioning when resizing a window occurs.

Now put a pair each of `<toolbox>`{=html} and `<tabbox>`{=html} tags
inside of the `<vbox>`{=html} tags with `<toolbox>`{=html} first. As was
said `<toolbox>`{=html} is used to create tool bars so lets add a
toolbar similar to the one at the top of the browser.

This is the code so far:

``` XML
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window
id="findfile-window"
title="Find Files"
orient="horizontal"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">

<vbox flex="1">

<toolbox>

<menubar id="MenuBar">
<menu id="File" label="File" accesskey="f">
<menupopup id="FileMenu">
<menuitem label="New" accesskey="n"/>
<menuitem label="Open..." accesskey="o"/>
<menuitem label="Save" accesskey="s"/>
<menuitem label="Save As..." accesskey="s"/>
<menuitem label=" ... "/>
<menuseparator/>
<menuitem label="Close" accesskey="c" />
</menupopup>
</menu>

<menu id="Edit" label="Edit" accesskey="e">
<menupopup id="EditMenu">
<menuitem label="Cut" accesskey="t" acceltext="Ctrl + X"/>
<menuitem label="Copy" accesskey="c"  acceltext="Ctrl + C"/>
<menuitem label="Paste" accesskey="p" disabled="true"/>
</menupopup>
</menu>

<menu id="View" label="View" accesskey="v">
<menupopup id="ViewMenu">
<menuitem id="Tool Bar1" label="Tool Bar1"
type="checkbox" accesskey="1" checked="true"/>
<menuitem id="Tool Bar2" label="Tool Bar2"
type="checkbox" accesskey="2" checked="false"/>
</menupopup>
</menu>
</menubar>

</toolbox>

<tabbox>

</tabbox>

</vbox>

</window>
```

There should now be a menu bar with "File Edit View" in it and they
should each expand when you click on them. Let's examine the elements
and their attributes more closely to see how they work.

First the `<menubar>`{=html} holds all of the menu items (File, Edit
,View). Next there are the three different menu items. Each menu has a
set of elements and attributes. The `<menupopup>`{=html} does just it
says. It creates the popup menu that occurs when the menu label is
clicked. In the popup menu is the list of menu items. Each of these has
an \'accesskey\' attribute. This attribute underlines the letter and
provides the reference for making a hot key for that menu item. Notice
in the Edit menu, both \'Cut\' and \'Copy\' have accelerator text
labels. In the File menu there is a `<menuseperator/>`{=html} tag. This
places a line across the menu that acts as a visual separator. In the
Edit menu, notice the menu item labeled \'Paste\' has an attribute:
disabled=\"true\". This causes the Paste label to be grayed out in that
menu and finally in the View menu the menu items there are actually
checkboxes. The first one is checked by default and the second one is
not.

Now on to the `<tabbox>`{=html}. Let\'s make three different sheets with
different elements on them. Put this code in between the
`<tabbox>`{=html} tags:

``` XML
<tabbox flex="1">
<tabs>
   <tab id="Tab1" label="Sheet1" selected="true"/>
   <tab id="Tab2" label="Sheet2"/>
   <tab id="Tab3" label="Sheet3"/>
</tabs>

<tabpanels flex="1">
   <tabpanel flex="1" id="Tab1Sheet" orient="vertical" >
   <description style="color:teal;">
      This doesn't do much.
      Just shows some of the style attributes.
   </description>
   </tabpanel>

   <tabpanel flex="1" id="Tab2Sheet" orient="vertical">
   <description class="normal">
      Hey, the slider works (for free).
   </description>
   <scrollbar/>
   </tabpanel>

   <tabpanel flex="1" id="Tab3Sheet" orient="vertical">
   <hbox>
      <text value="Progress Meter" id="txt" style="display:visible;"/>
      <progressmeter id="prgmeter" mode="undetermined"
         style="display:visible;" label="Progress Bar"/>
   </hbox>
   <description value="Wow, XUL! I mean cool!"/>
   </tabpanel>
</tabpanels>
</tabbox>
```

The tabs **are first defined** with `<tab>`{=html}. They are given an id
and label. Next, a set of associated panels is created, each with
different content. The first one is to show that like HTML style sheets
can be applied in line. The second two sheets have component type
elements in them. See how the slider works and the progress bar is
running on its own.

XUL has a number of types of elements for creating list boxes. A list
box displays items in the form of a list. Any item in such a particular
list can be selected. XUL provides two types of elements to create
lists, a listbox element to create multi-row list boxes, and a menulist
element to create drop-down list boxes, as we have already seen.

The simplest list box uses the listbox element for the box itself, and
the listitem element for each item. For example, this list box will have
four rows, one for each item.

``` XML
<listbox>
  <listitem label="Butter Pecan"/>
  <listitem label="Chocolate Chip"/>
  <listitem label="Raspberry Ripple"/>
  <listitem label="Squash Swirl"/>
</listbox>
```

Like with the HTML option element, you a value can be assigned using the
value attribute. The list box will set to a normal size, but you can
alter the size to a certain level using the row attributes. Set it to
the number of rows to display in the list box. A scroll bar will
automatically come up to let the user be able to see the rest of the
items in the list box if the box is too small.

``` XML
<listbox rows="3">
  <listitem label="Butter Pecan" value="bpecan"/>
  <listitem label="Chocolate Chip" value="chocchip"/>
  <listitem label="Raspberry Ripple" value="raspripple"/>
  <listitem label="Squash Swirl" value="squash"/>
</listbox>
```

Assigning values to each of the listitems lets the user be able to
reference them later using script. This way, other elements can be
reference this items to be used for alternative purposes.

All these elements are very nice and easy to put into a window, but by
themselves they don\'t do anything. Now we have to connect things with
some other code.

## Adding Event Handlers and Responding to Events

To make things really useful, some type of scripting or application
level coding has to be done. In our example, JavaScript will be used to
add functionality to the components. This is done in a similar fashion
as to scripting with HTML. With HTML, an event handler is associated
with an element and some action is initiated when that handler is
activated. Most of the handlers used with HTML are also found in XUL, in
addition to some unique ones. Scripting can be done in additional lines
of code, but a more efficient way is to create a separate file with the
needed scripts inside of it. This allows the page to load faster since
the rendering engine doesn't have to decide what to do with the embedded
script tags.

That being said, we'll first add a simple script, in line, as a first
example.

Let's add an 'onclick' event handler to fire an alert box when an
element is selected. Inside the `<window>`{=html} tag add the line
beginning with onclick:

``` XML
<window
   onclick="alert(event.target.tagName); return false;"
   id="findfile-window"
   title="Find Files"
   orient="horizontal"
   xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
       (... add elements here)
</window>
```

Now when you click on any element in the window, you created an alert
box that pops up telling you the name of the element. One interesting
thing to note: When you click on the text enclosed by the description
tag the response is undefined but when you click on the text wrapped by
the label tag you get the tabName label.

This implies that a description tag is not really an element. After
playing with the alert box, delete that line and add this inside the
opening tag of the 'Close' menu item in the 'File' menu:

``` XML
oncommand="window.close()"
```

Now when you click on 'Close' or use the 'C' as a hot key, the entire
window will close. The oncommand event handler is actually preferred
over onclick because oncommand can handle hot keys and other non-mouse
events.

Let's try one more thing. Add this right after the opening
`<window>`{=html} tag.

``` javascript
<script>
function show()
{
  var meter=document.getElementById('prgmeter');
  meter.setAttribute("style","display: visible;");
  var tx=document.getElementById('txt');
  tx.setAttribute("style","display: visible;");
}

function hide()
{
  var meter=document.getElementById('prgmeter');
  meter.setAttribute("style","display: none;");
  var tx=document.getElementById('txt');
  tx.setAttribute("style","display: none;");
}

</script>
```

These two functions first retrieve a reference to the progress meter and
the text element using their ids. Then both functions set the style
attributes of the progress meter and text element to have a display of
\'visible\' or 'none' which will do just that: hide or display those two
elements. (The tabpanel for the progress meter has to be displayed in
order to see these actions)

Now add two buttons that will provide the event to fire these two
methods. First, add a new box element to hold the buttons. The width
attribute of the box needs to be set otherwise the buttons will be laid
out to extend the length of the window.

``` XML
<box width="200px">
  <button id="show" label="Show" default="true" oncommand="show();"/>
  <button id="hide" label="Hide" default="true" oncommand="hide();"/>
</box>
```

### Style Sheets

Style sheets may be used both for creating themes, as well as modifying
elements for a more elaborate user interfaces. XUL uses CSS (Cascading
Style Sheets) for this. A style sheet is a file which contains style
information for elements. The style sheet makes it possible to apply
certain fonts, colors, borders, and size to the elements of your choice.
Mozilla applies a default style sheet to each XUL window. So far, this
is the style sheet that has been used for all the XUL documents:

``` XML
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
```

That line gives the XUL document the default <chrome://global/skin/>
style sheet. In Mozilla, this will be translated as the file global.css,
which contains default style information for XUL elements. The file will
still show is this line is left out but it will not be as aesthetically
pleasing. The style sheet applies theme-specific fonts, colors and
borders to make the elements look more suitable. Even though style
sheets can provide a better looking file, adding styles cannot always
provide a better view. Some CSS properties do not affect the appearance
of a widget, such as those that change the size or margins. In XUL, the
use of the \"flex: attribute should be used instead of using specific
sizes. There are other ways that CSS does not apply, and may be to
advanced for this tutorial.

Using a style sheet that you perhaps have already made, you just have to
insert one extra line of code pointing to the CSS file you have already
made.

``` XML
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<?xml-stylesheet href="findfile.css" type="text/css"?>
```

This second line of code references the style sheet, and will take over
as the default style sheet used for the XUL document. Sometimes it is
desired not to have the style that comes with the default CSS file.

### Answers

## Conclusion

The examples shown in this chapter merely scratch the surface of XUL's
capabilities. Even though these examples are very simple, one can see
how easy it would be to create more complex UI's with XUL. With a
complete set of the standard components such as buttons and text boxes
at the programmer's disposal, the programmer can code anything in XUL
that can be coded in HTML. The cross-platform ability of XUL is another
bonus but the fact that it doesn't work with Microsoft's Internet
Explorer may suppress XUL's widespread use. There is some hope that due
to the delay in the development of the next version of IE that XUL may
find it's way into IE, but don't hold your breath..

## References

1.  \'Configurable
    Chrome\' by Dave
    Hyatt (hyatt@netscape.com) (Last Modified 4/7/99)
2.  XML User Interface Language
    (XUL) - The Mozilla
    Organization
3.  XulPlanet
4.  XUL Programmer\'s Reference Manual, Fifth Draft: Updated for XUL
    1.0

fr:Programmation XML/XUL


# XML - Managing Data Exchange/Web Services

+----------------------------------+----------------------------------+
| `<font size=4>`{=html}**Learning | sponsored by:                    |
| objectives**`</font>`{=html}\    |                                  |
|                                  | ```{=html}                       |
| -   `<font size=3>`{=html} To    | <center>                         |
|     understand web services, and | ```                              |
|     what they can                | `<font size=3>`{=html}**The      |
|     do.`</font>`{=html}          | University of                    |
| -   `<font size=3>`{=html} To    | Georgia**`</font>`{=html}        |
|     know what SOAP is, and what  |                                  |
|     web services use it for.     | `<font size                      |
|     `</font>`{=html}             | =5 color=#990000>`{=html}**Terry |
| -   `<font size=3>`{=html} To    | College of                       |
|     know what Web Services       | Business**`</font>`{=html}       |
|     Description Language is, and |                                  |
|     how to read a WSDL           | `<                               |
|     file.`</font>`{=html}        | font size=3>`{=html}**Department |
| -   `<font size=3>`{=html} To    | of Management Information        |
|     know what the Universal      | Systems**`</font>`{=html}        |
|     Description, Discovery, and  |                                  |
|     Integration (UDDI) standard  | ```{=html}                       |
|     is.`</font>`{=html}          | </center>                        |
| -   `<font size=3>`{=html} To    | ```                              |
|     understand how to use Java   |                                  |
|     to connect to a web          |                                  |
|     service.`</font>`{=html}     |                                  |
+----------------------------------+----------------------------------+

## Web Services Overview

**Web Services** are a new breed of Web application. They are
self-contained, self-describing, modular applications that can be
published, located, and invoked across the Web. Web services perform
functions, which can be anything from simple requests to complicated
business processes. Once a Web service is deployed, other applications
(and other Web services) can discover and invoke the deployed service.
Web services make use of XML to describe the request and response, and
HTTP as its network transport.

The primary difference between a Web Service and a **web application**
relates to collaboration. Web applications are simply business
applications which are located or invoked using web protocols.
Similarly, Web Services also perform computing functions remotely over a
network. However, Web Services use internet protocols with the specific
intent of enabling inter operable machine to machine coordination.

Web Services have emerged as a solution to problems associated with
distributed computing. **Distributed computing** is the use of multiple
systems to perform a function rather than having a single system perform
it. The previous technologies used in distributed computing, primarily
Common Object Request Broker Architecture (CORBA) and Distributed
Component Object Model (DCOM), had some limitations. For example,
neither has achieved complete platform independence or easy transport
over firewalls. Additionally, DCOM is not vendor independent, being a
Microsoft product.

Some of the primary needs for a distributed computing standard were:

-   Cross-platform support for Business to Business, as well as
    internal, communication.
-   Concordance with existing Internet infrastructure as much as
    possible.
-   Scalability, both in number and complexity of nodes.
-   Internalization.
-   Tolerance of failure.
-   Vendor independence.
-   Suitability for trivial and non-trivial requests.

Over time, business information systems became highly configured and
differentiated. This inevitably made system interaction extremely costly
and time consuming. Developers began realizing the benefits of
standardizing Web Service development. Using web standards seemed to be
an intuitive and logical step toward attaining these goals. Web
standards already provided a platform independent means for system
communication and were readily accepted by information system users.

The end result was the development of Web Services. A Web Service forms
a distributed environment, in which objects can be accessed remotely via
standardized interfaces. It uses a three-tiered model, defining a
service provider, a service consumer, and a service broker. This allows
the Web Service to be a loose relationship, so that if a service
provider goes down, the broker can always direct consumers to another
one. Similarly, there are many brokers, so consumers can always find an
available one. For communication, Web Services use open Web standards:
TCP/IP, HTTP, and XML based SOAP.

At higher levels technologies such as XAML, XLANG, (transactional
support for complex web transactions involving multiple web services)
and XKMS (ongoing work by Microsoft and Verisign to support
authentication and registration) might be added.

## SOAP

!SOAP structure{width="220"}

**Simple Object Access Protocol (SOAP)** is a method for sending
information to and from Web Services in an extensible format. SOAP can
be used to send information or remote procedure calls encoded as XML.
Essentially, SOAP serves as a universally accepted method of
communication with web services. Businesses adhere to the SOAP
conventions in order to simplify the process of interacting with Web
Services.

``` XML
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
 <SOAP:Header>

  <!-- SOAP header -->

 </SOAP:Header>
 <SOAP:Body SOAP:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">

  <!-- SOAP body -->

 </SOAP:Body>
</SOAP:Envelope>
```

A SOAP message contains either a request method for invoking a Web
Service, or contains response information to a Web Service request.

Adhering to this layout when developing independent Web Services
provides notable benefits to the businesses. Due to the fact that Web
Applications are designed to be utilized by a myriad of actors,
developers want them to be easily adoptable. Using established and
familiar standards of communication ultimately reduces the amount of
effort it takes users to effectively interact with a Web Service.

The SOAP Envelope is used for defining and organizing the content
contained in Web Service messages. Primarily, the SOAP envelope serves
to indicate that the specified document will be used for service
interaction. It contains an optional SOAP Header and a SOAP Body.
Messages are sent in the SOAP body, and the SOAP head is used for
sending other information that wouldn\'t be expected in the body. For
example, if the SOAP:actor attribute is present in the SOAP header, it
indicates who the recipient of the message should be.

A web service transaction involves a SOAP request and a SOAP response.
The example we will be using is a Web Service provided by Weather.gov.
The input is latitude, longitude, a start date, how many days of
forecast information desired, and the format of the data. The SOAP
request will look like this:

``` XML
  <?xml version="1.0" encoding="UTF-8" standalone="no"?/>
  <SOAP-ENV:Envelope
      SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
      xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">

     <SOAP-ENV:Body>
        <m:NDFDgenByDayRequest xmlns:SOAPSDK1="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl">
           <latitude xsi:type="xsd:decimal">33.955464</latitude>
           <longitude xsi:type="xsd:decimal">-83.383245</longitude>
           <startDate xsi:type="xsd:date"></startDate>
           <numDays xsi:type="xsd:integer">1</numDays>
           <format>24 Hourly</format>
        </m:NDFDgenByDayRequest>
     </SOAP-ENV:Body>

  </SOAP-ENV:Envelope>
```

The startDate was left empty because this will automatically get the
most recent data. The format data type is not defined because it is
defined in the WSDL document.

The response SOAP looks like this.

``` XML
  <?xml version="1.0" encoding="UTF-8" standalone="no"?/>
  <SOAP-ENV:Envelope
      SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
      xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">

     <SOAP-ENV:Body>
        <NDFDgenByDayResponse xmlns:SOAPSDK1="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl">
           <dwmlByDayOut xsi:type="xsd:string">.....</dwmlByDayOut>
        </NDFDgenByDayResponse>
     </SOAP-ENV:Body>

  </SOAP-ENV:Envelope>
```

SOAP handles data by encoding it on the sender side and decoding it on
the receiver side. The data types handled by SOAP are based on the W3C
XML Schema specification. Simple types include strings, integers,
floats, and doubles, while compound types are made up of primitive
types.

``` XML
  <element name="name" type="xsd:string" />
  <SOAP:Array SOAP:arrayType="xsd:string[2]">
     <string>Web</string>
     <string>Services</string>
  </SOAP:Array>
```

Because they are text based, SOAP messages generally have no problem
getting through firewalls or other barriers. They are the ideal way to
pass information to and from web services.

## Service Description - WSDL

**Web Service Description Language (WSDL)** was created to provide
information about how to connect to and query a specific Web Service.
This document also adheres to strict formatting and organizational
guidelines. However, the methods, parameters, and service information
are application specific. Web Services perform different functionality
and contain independent information, however they are all organized the
same way. By creating a standard organizational architecture for these
services, developers can effectively invoke and utilize them with little
to no familiarization. To use a web service, a developer can follow the
design standards of the WSDL to easily determine all the information and
procedures associated with its usage.

Essentially, a WSDL document serves as an instruction for interacting
with a Web Service. It contains no application logic, giving the service
a level of autonomy. This enables users to effectively interact with the
service without having to understand its inner workings.

The following is an example of a WSDL file for a web service that
provides a temperature, given a U.S. zip code.

``` XML
<?xml version="1.0"?>
<definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:si="http://soapinterop.org/xsd" xmlns:tns="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
xmlns:typens="http://www.weather.gov/forecasts/xml/DWMLgen/schema/DWML.xsd" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl>

 <types>
    <xsd:schema targetNamespace="http://www.weather.gov/forecasts/xml/DWMLgen/schema/DWML.xsd">
       <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
       <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" />
       <xsd:simpleType name="formatType">
          <xsd:restriction base="xsd:string">
             <xsd:enumeration value="24 hourly" />
             <xsd:enumeration value="12 hourly" />
          </xsd:restriction>
       </xsd:simpleType>
       <xsd:simpleType name="productType">
          <xsd:restriction base="xsd:string">
             <xsd:enumeration value="time-series" />
             <xsd:enumeration value="glance" />
          </xsd:restriction>
       </xsd:simpleType>
       <xsd:complexType name="weatherParametersType">
          <xsd:all>
             <xsd:element name="maxt" type="xsd:boolean" />
             <xsd:element name="mint" type="xsd:boolean" />
             <xsd:element name="temp" type="xsd:boolean" />
             <xsd:element name="dew" type="xsd:boolean" />
             <xsd:element name="pop12" type="xsd:boolean" />
             <xsd:element name="qpf" type="xsd:boolean" />
             <xsd:element name="sky" type="xsd:boolean" />
             <xsd:element name="snow" type="xsd:boolean" />
             <xsd:element name="wspd" type="xsd:boolean" />
             <xsd:element name="wdir" type="xsd:boolean" />
             <xsd:element name="wx" type="xsd:boolean" />
             <xsd:element name="waveh" type="xsd:boolean" />
             <xsd:element name="icons" type="xsd:boolean" />
             <xsd:element name="rh" type="xsd:boolean" />
             <xsd:element name="appt" type="xsd:boolean" />
          </xsd:all>
       </xsd:complexType>
    </xsd:schema>
</types>

<message name="NDFDgenRequest">
   <part name="latitude" type="xsd:decimal"/>
   <part name="longitude" type="xsd:decimal" />
   <part name="product" type="typens:productType" />
   <part name="startTime" type="xsd:dateTime" />
   <part name="endTime" type="xsd:dateTime" />
   <part name="weatherParameters" type="typens:weatherParametersType" />
</message>

<message name="NDFDgenResponse">
   <part name="dwmlOut" type="xsd:string" />
</message>

<message name="NDFDgenByDayRequest">
   <part name="latitude" type="xsd:decimal" />
   <part name="longitude" type="xsd:decimal" />
   <part name="startDate" type="xsd:date" />
   <part name="numDays" type="xsd:integer" />
   <part name="format" type="typens:formatType" />
</message>

<message name="NDFDgenByDayResponse">
   <part name="dwmlByDayOut" type="xsd:string" />
</message>

<portType name="ndfdXMLPortType">
   <operation name="NDFDgen">
      <documentation> Returns National Weather Service digital weather forecast data </documentation>
      <input message="tns:NDFDgenRequest" />
      <output message="tns:NDFDgenResponse" />
   </operation>
   <operation name="NDFDgenByDay">
      <documentation> Returns National Weather Service digital weather forecast data summarized over either 24- or 12-hourly periods </documentation>
      <input message="tns:NDFDgenByDayRequest" />
      <output message="tns:NDFDgenByDayResponse" />
   </operation>
</portType>

<binding name="ndfdXMLBinding" type="tns:ndfdXMLPortType">
   <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
   <operation name="NDFDgen">
      <soap:operation soapAction="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl#NDFDgen" style="rpc" />
      <input>
         <soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
             encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
      </input>
      <output>
         <soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
             encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
      </output>
   </operation>
   <operation name="NDFDgenByDay">
      <soap:operation soapAction="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl#NDFDgenByDay" style="rpc" />
      <input>
         <soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
             encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
      </input>
      <output>
         <soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
             encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
      </output>
   </operation>
</binding>

<service name="ndfdXML">
   <documentation>The service has two exposed functions, NDFDgen and NDFDgenByDay.
                        For the NDFDgen function, the client needs to provide a latitude and
                        longitude pair and the product type. The client also needs to provide
                        the start and end time of the period that it wants data for. For the
                        time-series product, the client needs to provide an array of boolean values
                        corresponding to which weather values should appear in the time series product.
                        For the NDFDgenByDay function, the client needs to provide a latitude and longitude
                        pair, the date it wants to start retrieving data for and the number of days worth
                        of data. The client also needs to provide the format that is desired.</documentation>
   <port name="ndfdXMLPort" binding="tns:ndfdXMLBinding">
      <soap:address location="http://www.weather.gov/forecasts/xml/SOAP_server/ndfdXMLserver.php" />
   </port>
  </service>
</definitions>
```

The WSDL file defines a service, made up of different endpoints, called
ports. The port is made up of a network address

`       and a binding.`

``` XML
<service name="ndfdXML">
   <documentation>The service has two exposed functions, NDFDgen and NDFDgenByDay.
                        For the NDFDgen function, the client needs to provide a latitude and
                        longitude pair and the product type. The client also needs to provide
                        the start and end time of the period that it wants data for. For the
                        time-series product, the client needs to provide an array of boolean values
                        corresponding to which weather values should appear in the time series product.
                        For the NDFDgenByDay function, the client needs to provide a latitude and longitude
                        pair, the date it wants to start retrieving data for and the number of days worth
                        of data. The client also needs to provide the format that is desired.</documentation>
   <port name="ndfdXMLPort" binding="tns:ndfdXMLBinding">
      <soap:address location="http://www.weather.gov/forecasts/xml/SOAP_server/ndfdXMLserver.php" />
   </port>
</service>
```

The binding identifies the binding style and protocol for each
operation. In this case, it uses Remote Procedure Call style binding,
using SOAP.

``` XML
   <binding name="ndfdXMLBinding" type="tns:ndfdXMLPortType">
   <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
   <operation name="NDFDgen">
      <soap:operation soapAction="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl#NDFDgen" style="rpc" />
      <input>
         <soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
             encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
      </input>
      <output>
         <soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
             encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
      </output>
   </operation>
   <operation name="NDFDgenByDay">
      <soap:operation soapAction="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl#NDFDgenByDay" style="rpc" />
      <input>
         <soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
             encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
      </input>
      <output>
         <soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
             encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
      </output>
   </operation>
</binding>
```

Port Types are abstract collections of operations. In this case, the
operation is getTemp.

``` XML
   <portType name="ndfdXMLPortType">
      <operation name="NDFDgen">
         <documentation> Returns National Weather Service digital weather forecast data     </documentation>
         <input message="tns:NDFDgenRequest" />
         <output message="tns:NDFDgenResponse" />
      </operation>
      <operation name="NDFDgenByDay">
         <documentation> Returns National Weather Service digital weather forecast data summarized over either 24- or 12-hourly periods </documentation>
         <input message="tns:NDFDgenByDayRequest" />
         <output message="tns:NDFDgenByDayResponse" />
      </operation>
   </portType>
```

Finally, messages are used by the operations to communicate - in other
words, to pass parameters and return values.

``` XML
   <message name="NDFDgenByDayRequest">
      <part name="latitude" type="xsd:decimal" />
      <part name="longitude" type="xsd:decimal" />
      <part name="startDate" type="xsd:date" />
      <part name="numDays" type="xsd:integer" />
      <part name="format" type="typens:formatType" />
   </message>

   <message name="NDFDgenByDayResponse">
      <part name="dwmlByDayOut" type="xsd:string" />
   </message>
```

From the WSDL file, a consumer should be able to access data in a web
service.

For a more detailed analysis of how this particular web service, please
visit Weather.gov

## Service Discovery - UDDI

You\'ve seen how WSDL can be used to share interface definitions for Web
Services, but how do you go about finding a Web Service in the first
place? There are countless independent Web Services that are developed
and maintained by just as many different organizations. Upon adopting
Web Service practices and methodologies, developers sought to foster the
involvement and creative reuse of their systems. It soon became apparent
that there was a need for an enumerated record of these services and
their respective locations. This information would empower developers to
leverage the best practices and processes of Web Services quickly and
easily. Additionally, having a central reference of current Web Service
capabilities enables developers avoid developing redundant applications.

UDDI defines registries in which services can be published and found.
The UDDI specification was creaed by Microsoft, Ariba, and IBM. UDDI
defines a data structure and Application Programming Interface (API).

In the three-tier model mentioned before, UDDI is the service broker.
Its function is to enable service consumers to find appropriate service
providers.

Connecting to UDDI registries using Java can be accomplished through the
Java API for XML Registries (JAXR). JAXR creates a layer of abstraction,
so that it can be used with UDDI and other types of XML Registries, such
as the ebXML Registry and Repository standard.

## Using Java With Web Services

To execute a SOAP message, an application must be used to communicate
with the service provider. Due to its flexibility, almost any
programming language can be used to execute SOAP message. For our
purposes, however, we will be focusing on using Java to interact with
Web Services.

Using Java with web services requires some external libraries.

-   Apache SOAP Toolkit
-   Java Mail Framework
-   JavaBeans Activation Framework
-   Xerces XML parser

Let\'s go through using Java to query the Temperature Web Service we
talked about earlier.

``` java
import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.soap.util.xml.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;

public class TempClient
{

 public static float getTemp (URL url, String zipcode) throws Exception
 {

  Call call = new Call ();

  // Service uses standard SOAP encoding
  String encodingStyleURI = Constants.NS_URI_SOAP_ENC;
  call.setEncodingStyleURI(encodingStyleURI);

  // Set service locator parameters
  call.setTargetObjectURI ("urn:xmethods-Temperature");
  call.setMethodName ("getTemp");

  // Create input parameter vector
  Vector params = new Vector ();
  params.addElement (new Parameter("zipcode", String.class, zipcode, null));
  call.setParams (params);

  // Invoke the service ....
  Response resp = call.invoke (url,"");

  // ... and evaluate the response
  if (resp.generatedFault ())
  {
   throw new Exception();
  }
  else
  {
   // Call was successful. Extract response parameter and return result
   Parameter result = resp.getReturnValue ();
   Float rate=(Float) result.getValue();
   return rate.floatValue();
  }
 }

 // Driver to illustrate service invocation
 public static void main(String[] args)
 {
  try
  {
   URL url=new URL("http://services.xmethods.net:80/soap/servlet/rpcrouter");
   String zipcode= "30605";
   float temp = getTemp(url,zipcode);
   System.out.println(temp);
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}
```

This Java code effectively hides all the SOAP from the user. It invokes
the target object by name and URL, and sets the parameter *zipcode*. But
what does the underlying SOAP Request look like?

``` XML
  <?xml version="1.0" encoding="UTF-8"?>
  <soap:Envelope xmlns:n="urn:xmethods-Temperature"
      xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
      xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

     <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
        <n:getTemp>
           <zipcode xsi:type="xs:string">30605</zipcode>
        </n:getTemp>
     </soap:Body>

  </soap:Envelope>
```

As you see, the SOAP request uses the parameters passed in by the Java
Call to fill out the SOAP envelope and direct the message. Similarly,
the response comes back into the Java program as \'70.0\'. The response
SOAP is also hidden by the Java program.

``` XML
  <?xml version='1.0' encoding='UTF-8'?>
  <SOAP-ENV:Envelope
      xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema">

     <SOAP-ENV:Body>
        <ns1:getTempResponse xmlns:ns1="urn:xmethods-Temperature"
            SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
           <return xsi:type="xsd:float">70.0</return>
        </ns1:getTempResponse>
     </SOAP-ENV:Body>

  </SOAP-ENV:Envelope>
```

Here\'s an additional example of using Java and SOAP to interact with
Web Services. This particular Web Service is called the \"US Zip
Validator\" and takes a ZipCode as a parameter, which then returns a
corresponding latitude and longitude. When developing applications to
interact with Web Services, the first step should be to review the WSDL
document.

The WSDL document for this service is located here:
<http://www.webservicemart.com/uszip.asmx?WSDL>

This document will contain all the necessary instructions for
interacting with the \"US Zip Validator\" Web Service.

**SOAPClient4XG**

Modified by - Duncan McAllister From:
<http://www.ibm.com/developerworks/xml/library/x-soapcl/>

``` java
import java.io.*;
import java.net.*;
import java.util.*;

public class SOAPClient4XG {

    public static void main(String[] args) throws Exception {

        args = new String[2];

        args[0] = "http://services.xmethods.net:80/soap/servlet/rpcrouter";
        args[1] = "SOAPrequest.xml";

        if (args.length  < 2) {
            System.err.println("Usage:  java SOAPClient4XG " +
                               "http://soapURL soapEnvelopefile.xml" +
                               " [SOAPAction]");
                System.err.println("SOAPAction is optional.");
            System.exit(1);
        }

        String SOAPUrl      = args[0];
        String xmlFile2Send = args[1];

          String SOAPAction = "";

        // Create the connection where we're going to send the file.
        URL url = new URL(SOAPUrl);
        URLConnection connection = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) connection;

        // Open the input file. After we copy it to a byte array, we can see
        // how big it is so that we can set the HTTP Cotent-Length
        // property. (See complete e-mail below for more on this.)

        FileInputStream fin = new FileInputStream(xmlFile2Send);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        // Copy the SOAP file to the open connection.
        copy(fin,bout);
        fin.close();

        byte[] b = bout.toByteArray();

        // Set the appropriate HTTP parameters.
        httpConn.setRequestProperty( "Content-Length",
                                     String.valueOf( b.length ) );
        httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
          httpConn.setRequestProperty("SOAPAction",SOAPAction);
        httpConn.setRequestMethod( "POST" );
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);

        // Everything's set up; send the XML that was read in to b.
        OutputStream out = httpConn.getOutputStream();
        out.write( b );
        out.close();

        // Read the response and write it to standard out.

        InputStreamReader isr =
            new InputStreamReader(httpConn.getInputStream());
        BufferedReader in = new BufferedReader(isr);

        String inputLine;

        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);

        in.close();
    }

  // copy method from From E.R. Harold's book "Java I/O"
  public static void copy(InputStream in, OutputStream out)
   throws IOException {

    // do not allow other threads to read from the
    // input or write to the output while copying is
    // taking place

    synchronized (in) {
      synchronized (out) {

        byte[] buffer = new byte[256];
        while (true) {
          int bytesRead = in.read(buffer);
          if (bytesRead == -1) break;
          out.write(buffer, 0, bytesRead);
        }
      }
    }
  }
}
```

This Java class refers to an XML document(SOAPRequest.xml), which is
used as the SOAP message. This document should be included in the same
project folder as the Java application invoking the service.

After reviewing the \"US Zip Validator\" WSDL document, it is clear that
we would like to invoke the \"getTemp\" method. This information is
contained within the SOAP body and includes the appropriate parameters.

**SOAPRequest.xml**

``` XML
<?xml version="1.0" encoding="UTF-8"?>
  <soap:Envelope xmlns:n="urn:xmethods-Temperature"
      xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
      xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

     <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
        <n:getTemp>
           <zipcode xsi:type="xs:string">30605</zipcode>
        </n:getTemp>
     </soap:Body>

  </soap:Envelope>
```

Following a successful interaction, the Web Service provider will
provide a response that is similar in format to the user request. When
developing in NetBeans, run this project and examine the subsequent SOAP
message response in the Tomcat output window.

## Web Services with Netbeans

The Netbeans version used for this explanation is 5.0.

After Netbeans is open, click on the \"Runtime\" tab on the left pane,
then right-click \"Web Services\" and select \"Add Web Service.\" In the
\"URL\" field, enter the address of the web service WSDL file, in our
example above it is
\"<http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl>\" and
click Get Web Service Description. This will bring up the information of
the web service.

## Summary

  ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  Web services are applications that use XML to communicate with many different systems to perform a task. To facilitate the use of web services, protocols were developed that allow them to be flexible and scalable. SOAP is used to send and define information and WSDL was created to provide information about how to connect to and query a web service. UDDI describes where these web services can be found.
  ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Exercises

## Answers

## Appendix

## References and Links

-   Weather.gov
-   WebServices.org
-   W3C\'s Web Services Reference
-   UDDI.org
-   XMethods.net
-   Java API for XML Registries
-   Apache SOAP Toolkit
-   JavaMail Framework
-   Java Activation
    Framework
-   Xerces Java Parser
-   Jasnowski, Mike. *Java, XML, and Web Services Bible*
-   Microsoft Web Services
-   <http://www.xml.com/>
-   <http://www.w3schools.com/soap/soap_intro.asp>
-   <http://en.wikibooks.org/wiki/XML_-_Managing_Data_Exchange/Web_services>
-   <http://www.w3.org/TR/2007/REC-soap12-part0-20070427/>
-   <http://www.eweek.com/article2/0,1895,1589730,00.asp>
-   <http://www.ibm.com/developerworks/xml/library/x-soapcl/>


# XML - Managing Data Exchange/XMLHTTP

## History

The XMLHttpRequest object enables JavaScript to make HTTP requests to a
remote server without the need to reload the page. It was first
implemented by Microsoft as an ActiveX object but is now available as a
native object within both Mozilla and Apple\'s Safari browser.
Javascript is used to transfer information back to the server in real
time where it can be processed by the server, and then returned
instantaneously to the user.

## Purpose

The main function of the XMLHttpRequest object is that it provides an
easy way for webpages to receive updated information from servers
without having to refresh the whole webpage. As a result, the
webserver's processing load is reduced and the user receives information
faster without seeing any interruptions in service.

## Future Application

The XMLHttpRequest object has many improvements over the existing data
exchange methods. Many developers still rely on Common Gateway
Interchange (CGI) for data exchange. Since CGI has no adequate
restriction about the format of data, XML usage is relatively pointless
from a data exchange standpoint. Utilizing the inherent abilities of
XMLHttp will remove the inadequacies originating from the widespread use
of CGI. The XMLHttpRequest object provides a more adequate approach for
real-time content delivery than existing development methods.

## Tutorials

<http://developer.apple.com/library/safari/#documentation/appleapplications/Conceptual/SafariJSProgTopics/Articles/XHR.html>


# XML - Managing Data Exchange/Database and XML

+-----------------------------------------------------+
| **Learning objectives**                             |
|                                                     |
| -   Learn about Native XML Databases                |
| -   Learn about the conversion technology available |
| -   Create Table and retrieve information           |
+-----------------------------------------------------+
|                                                     |
+-----------------------------------------------------+

## Native XML Database

The term **Native XML database**: has become popular since 1999, after
the company Software AG released the first version of its native XML
server Tamino, which included a native XML database. A definition of a
native databases is that it:

\"\[d\]efines a (logical) model for an XML document and stores and
retrieves documents according to that model.\" (Bourret, 2002)\"

To model data in XML, two principle approaches are used: Data-centric
documents and Document-centric documents.

-   Data-centric documents (for data transport) have fairly regular
    structure, order typically does not matter, and little or no mixed
    content.

```{=html}
<!-- -->
```
-   Document-centric documents (usually for human consumption) have less
    regular or irregular structure, significant order of the elements,
    and lots of mixed content.

Examples of Native databases

```{=html}
<table width="60%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<th width="15%">
```
Product

```{=html}
</th>
```
```{=html}
<th width="15%">
```
Developer

```{=html}
</th>
```
```{=html}
<th width="15%">
```
License

```{=html}
</th>
```
```{=html}
<th width="15%">
```
DB Type

```{=html}
</th>
```
```{=html}
</tr>
```
```{=html}
<tr style="text-align:center">
```
```{=html}
<td>
```
Tamino

```{=html}
</td>
```
```{=html}
<td>
```
Software AG

```{=html}
</td>
```
```{=html}
<td>
```
Commercial

```{=html}
</td>
```
```{=html}
<td>
```
Proprietary. Relational through ODBC.

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style="text-align:center">
```
```{=html}
<td>
```
XediX Multimedia Solution

```{=html}
</td>
```
```{=html}
<td>
```
XediX Tera Solution

```{=html}
</td>
```
```{=html}
<td>
```
Commercial

```{=html}
</td>
```
```{=html}
<td>
```
Proprietary

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
eXist

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Wolfgang Meier

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Open Source

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Relational

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
dbXML

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
dbXML Group

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Open Source

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Proprietary

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
Xindice

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Apache Software Foundation

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Open Source

```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Proprietary (Model-based)

```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
### eXist

eXist is an Open Source effort to
develop a native XML database system, tightly integrated with existing
XML development tools like Apache\'s Cocoon. The database may be easily
deployed, running either standalone, inside a servlet engine, or
directly embedded in an application.

Some features that are available in eXist and that can be found in most
Native XML databases are :

-   Schema-less storage - Documents do not have to be associated to
    schema or document type, meaning they are allowed to be well formed
    only.

```{=html}
<!-- -->
```
-   Collections - A collection plays a similar role to a directory in a
    file system. When submitting a query the user can choose a distinct
    part of the collection hierarchy or even all the documents contained
    in the database.

```{=html}
<!-- -->
```
-   Query languages - The most popular query languages supported by
    Native XML databases are XPath (with extensions for queries over
    multiple documents) and XQuery.

## Relational Databases

Database vendors such as IBM, Microsoft, Oracle, and Sybase have
developed tools to assist in converting XML documents into relational
tables.

Let us look at IBM and Oracle:

### IBM Technology

**DB2 XML Extender** provides access, storage and transformation for XML
data through user-defined functions and stored procedure. It offers 2
key storage models: **XML Colums** and **XML Collections**.

1\. XML Column: stores and retrieves entire XML documents as DB2 column
data. Use of XML Columns is recommended when XML documents already exist
and/or when there is a need to store XML documents in their entity.

2\. XML Collection: composes XML Documents from a collection of
relational tables.

A **data access definition (DAD)** file is used for both XML Column and
XML Collection approaches to define the \"mapping\" between the database
tables and the structure of the XML document.

`<Xcollection>`{=html} Specifies that the XML data is either to be
decomposed from XML documents into a collection of relational tables, or
to be composed into XML documents from a collection of relational
tables.

The DAD file defines the XML document tree structure, using the
following kinds of nodes:

-   root_node - Specifies the root element of the document.
-   element_node - Identifies an element, which can be the root element
    or a child element.
-   text_node - Represents the CDATA text of an element.
-   attribute_node - Represents an attribute of an element.

``` XML
<?xml version="1.0"?>
<!DOCTYPE DAD SYSTEM ""c:\dxx\samples\db2xml\dtd\dad.dtd">
<DAD>
  ...
<Xcollection>
<SQL_stmt>
       ...
</SQL_stmt>
<prolog>?xml version="1.0"?</prolog>
<doctype>!DOCTYPE Order SYSTEM
                  ""c:\dxx\samples\db2xml\dtd\getstart.dtd""</doctype>
<root_node>
 <element_node name="Order">      --> Identifies the element <Order>
  <attribute_node name="key">     --> Identifies the attribute "key"
   <column name="order_key"/>     --> Defines the name of the column,
                                      "order_key", to which the
                                      element and attribute are
                                      mapped
  </attribute_node>
  <element_node name="Customer">  --> Identifies a child element of
                                      <Order> as <Customer>
   <text_node>                    --> Specifies the CDATA text for
                                      the element <Customer>
    <column name="customer">      --> Defines the name of the column,
                                      "customer", to which the child
                                      element is mapped
   </text_node>
  </element_node>
        ...
 </element_node>

      ...
</root_node>
</Xcollection>
</DAD>
```

\
\* XML for DB2 Information Integration
Redbook.

### Oracle

Oracle\'s **XML SQL Utility (XSU)** uses a schematic mapping that
defines how to map tables and views, including object-relational
features, to XML documents. Oracle translates the chain of object
references from the database into the hierarchical structure of XML
elements.

``` SQL
CREATE TABLE Customers
{
     FIRSTNAME      VARCHAR,
     LASTNAME       VARCHAR,
     PHONENO      INT,
     ADDRESS        AddressType, // object reference

}

CREATE TYPE AddressType as OBJECT
{
     ZIP       VARCHAR (100),
     CITY      VARCHAR (100),
     STREET    VARCHAR (100),
}
```

\
A corresponding XML document generated from the given object-relational
model looks like:

``` XML
<?xml version="1.0"?>
<ROWSET>
     <ROW num="1">

        <FIRSTNAME>JOHN</FIRSTNAME>
        <LASTNAME>SMITH</LASTNAME>
        <PHONENO>7061234567</PHONENO>

        <ADDRESS>
   <ZIP>30601</ZIP>
   <CITY>ATHENS</CITY>
   <STREET>123 MAIN STREEET</STREET>
        </ADDRESS>

    </ROW>

    <!-- additional rows ... -->

 </ROWSET>
```

\
XSU can be used for executing queries in a Java environment and retrieve
XML from the database.

``` java
import oracle.jdbc.driver.*;
import oracle.xml.sql.query.OracleXMLQuery;
import java.lang.*;
import java.sql.*;

// class to test XML document generation as String
class testXMLSQL {

   public static void main(String[] args)
   {
     try {
      // Create the connection
      Connection conn  = getConnection("root","");

      // Create the query class
      OracleXMLQuery qry = new OracleXMLQuery(conn,
         "SELECT  * FROM Customers");

      // Get the XML string
      String str = qry.getXMLString();

      // Print the XML output
      System.out.println("The XML output is:\n"+str);

      // Always close the query to get rid of any resources..
      qry.close();
     } catch(SQLException e) {
      System.out.println(e.toString());
     }
   }

   // Get the connection given the user name and password.!
   private static Connection getConnection(String username,
        String password)
        throws SQLException
   {
      // register the JDBC driver..
       DriverManager.registerDriver(new
          oracle.jdbc.driver.OracleDriver());

      // Create the connection using the OCI8 driver
       Connection conn =
        DriverManager.getConnection(
           "jdbc:oracle:thin:@dlsun489:1521:ORCL",username,password);

      return conn;
   }
}
```

## Query Languages

### XPath

../XPath/ is a language for addressing parts of
an XML document, and is the common locator used by both XSLT and
XPointer. An XPath expression is a series of location steps separated by
\" / \". Each step selects a set of nodes that become the current
node(s) for the next step. The set of nodes selected by the expression
are the nodes remaining after processing each step in order.

### XQuery

../XQuery/ is a query language under
development by the World Wide Web Consortium (W3C). The ambitious task
is to develop the first world standard for querying Web documents.
XQuery is a versatile markup language, capable of labeling the
information content of diverse data sources including structured and
semi-structured documents, relational databases, and object
repositories.

-   Catalog of XQuery Processors at
    www.SQLSummit.com.

## MySQL 5.1

MySQL has a command line utility for executing queries against a MySQL
database; it has an option for using XML as their output format. MySQL
also allows convertion to XML; more information can be found in
../Converting MySQL to XML/
MySQL allows users to execute any SQL query. mysqldump allows users to
specify which tables to dump and to specify a where clause to restrict
the rows that are dumped. In its Beta release of MySQL 5.1, several
features have been added including new **XML functions**.

In order to understand these New functions, we will use the following
table:

``` mysql
CREATE TABLE Customers (doc VARCHAR(150));

INSERT INTO Customers VALUES
('
<person id="1">
      <firstname>John</firstname>
      <lastname>Smith</lastname>
      <phoneno>123-5678</phoneno>
</person>
');

INSERT INTO Customers VALUES
('
<person id="2">
      <firstname>Aminata</firstname>
      <lastname>Cisse</lastname>
      <phoneno>123-5679</phoneno>
</person>
');

INSERT INTO Customers VALUES
('
<person id="3">
      <firstname>Lamine</firstname>
      <lastname>Smith</lastname>
      <phoneno>123-5680</phoneno>
</person>
');
```

\

### XML Functions

MySQL version 5.1 has functions for searching and changing XML
documents: **ExtractValue()** and **UpdateXML()**.

-   EXTRACTVALUE (XML_document, XPath_string);

This function takes 2 string arguments: The first parameter correspond
to the XML_document string, and the 2nd Parameter XPath_string (XPath
expression / locator). This will result in the return of the string
containing a value from the document.

    <nowiki>
    mysql> SELECT EXTRACTVALUE(doc,'//firstname') FROM Customers;

    +------------------------------------------+
    | EXTRACTVALUE(doc,'//firstname')          |
    +------------------------------------------+
    | John                                     |
    | Aminata                                  |
    | Lamine                                   |
    +------------------------------------------+
    3 rows in set (0.01 sec)
    </nowiki>

\

    <nowiki>
    mysql> SELECT ExtractValue(doc,'/person[@id="3"]/firstname') as fname FROM Customers;

    +---------+
    | fname   |
    +---------+
    |         |
    |         |
    | Lamine  |
    +---------+
    3 rows in set (0.02 sec)
    </nowiki>

\

-   UPDATEXML (XML_document, XPath_string, new_value);

This function takes 3 string arguments: The first two paramaters are
similar to the ones used with extractValue(), XML_document and
XPath_string. The third parameter is the new value that will replace the
one found. This function will then returns the changed XML.

    <nowiki>
    mysql> SELECT UpdateXML(doc,'/person[@id="3"]/phoneno', '<phoneno>111-2233<phoneno>') FROM Customers;

    +-------------------------------------------------------------------------------
    ----------------------------------------------------+
    | UpdateXML(doc,'/person[@id="3"]/phoneno','<phoneno>111-2233<phoneno>')
                                                        |
    +-------------------------------------------------------------------------------
    ----------------------------------------------------+
    |
    <person id="1">
          <firstname>John</firstname>
          <lastname>Smith</lastname>
          <phoneno>123-5678</phoneno>
    </person>
             |
    |
    <person id="2">
          <firstname>Aminata</firstname>
          <lastname>Cisse</lastname>
          <phoneno>123-5679</phoneno>
    </person>
          |
    |
    <person id="3">
          <firstname>Lamine</firstname>
          <lastname>Smith</lastname>
          <phoneno>111-2233<phoneno>
    </person>
     |
    +-------------------------------------------------------------------------------
    ----------------------------------------------------+
    3 rows in set (0.00 sec)
    </nowiki>

\

### Installation

Currently (04/05/06) MySQL 5.1 does not come with the installer (Beta
Version).

Quick Windows
installation.

Details information can be found in the online Manual:

-   Windows.

```{=html}
<!-- -->
```
-   Mac
    OS.

```{=html}
<!-- -->
```
-   Linux.

```{=html}
<!-- -->
```
-   and more in the
    Manual.

## Summary

## Exercises

## Answers


# XML - Managing Data Exchange/SyncML

## Learning objectives

Upon completion of this chapter, you will be able to

-   Understand SyncML fundamentals and general syntax.
-   Understand how and why SyncML is implemented.
-   Quickly locate and use SyncML technical specifications.

## Introduction

Mobile devices such as PDAs, pagers, mobile phones and laptops are- by
nature- not always connected to a network. Yet these devices contain
applications which require information obtained from a network in order
to be useful. While most PDAs and mobile phones contain applications
such as calendars, task lists, and address books for storing useful
information, this information is far less useful when it is static, only
available on the device itself. For example, copies of static
information will always be dissimilar when changes are made on one copy
or the other. Synchronization offers a device the ability to connect to
a network in order to update either the information on the device or the
information on the network, such that both sets of information are
identical and up-to-date.

Given the proliferation of proprietary mobile devices and protocols, as
well as the increasing consumer demand for ubiquitous mobile access of
information, leading technology companies saw the need to create a
standard, universal language for describing the synchronization actions
between devices and applications. They formed a consortium to sponsor
the SyncML initiative to create this language.

Currently, the SyncML consortium has been adopted and incorporated into
the Open Mobile Alliance, a larger
group of over 300 companies which sponsors many collaborative technology
projects and protocols.

## What is SyncML?

SyncML or *Synchronization Markup Language* is an XML-based,
industry-standard protocol for synchronizing mobile data across a
variety of multiple networks, platforms and devices. SyncML started as
an initiative in mid 2000 by major technology companies such as
Ericsson, IBM, Palm Inc., Lotus, Matsushita Ltd. (Panasonic), Motorola,
Nokia, Openwave, Starfish Software, Psion and Symbian. Their
initiative\'s goals were to create a universal language from the myriad,
proprietary, synchronization protocols used by mobile devices and
provide a complete set of synchronization functionality for future
devices. The consortium released version 1.0 in December 2000. They then
implemented new features and resolved issues with the subsequent version
releases, finalizing the protocol with version 1.1 in February 2002.

The SyncML protocol is designed with these goals in mind:

-   As a common language, any device should be able to synchronize with
    any SyncML service (a networked data repository).
-   Any service speaking SyncML should be able to synchronize with any
    SyncML-capable device.
-   The protocol must address the limitations of mobile devices,
    specifically with respect to memory storage.
-   It must support a variety of transport protocols such as HTTP, SMTP,
    Bluetooth and others.
-   It must deliver common synchronization commands to all devices.
-   It builds upon existing web technologies, specifically XML.
-   Support asynchronous communication and error-handling, since the
    Internet has latency.

SyncML consists of client and server commands enclosed within
DTD-defined\...

## SyncML Fundamentals

### Vocabulary

Let\'s begin by defining a vocabulary:

-   Client - the mobile device, its application and local database.
-   Server - a remote system communicating to the system database or
    application.
-   Modifications - data in fields in a database are changed.
-   Sync - The client and server exchange SyncML messages with commands.
-   Package - SyncML DTD conformant XML markup describing requests or
    actions to be taken by either a SyncML client or server. A package
    is a collection of actions to be performed
-   Message - the smallest unit of SyncML markup. Large packages are
    broken into separate messages.
-   Mapping - using an intermediate identifier to tie two pieces of
    information together. example: let\'s say \'green\' is \'5\', and
    \'5\' is nice. What is nice? If you said \'green\' you are correct.
    You\'ve just done mapping!

Abbreviations:

  --------------------------------- -------------------------------------------
  ../IMEI/   International Mobile Equipment Identifier
  GUID                              Global Unique Identifier
  LUID                              Local Unique Identifier
  --------------------------------- -------------------------------------------

### Messages and Packages

SyncML messages are requests from either a client or server to perform
some action. The action may be to synchronize data, perform some checks
on data, update a status, or handle any errors with these actions.
Messages are bundled together as packages, as kind of a to-do list.
Messages are a laundry list of requests, and they can be pieced together
out of order if sufficient mapping information is given to identify to
which package the message belongs.

SyncML is designed this way to accommodate for errors and dropped
messages. Should one message be dropped, a syncML client or server will
know there is a problem because the mapping cannot be completed. It will
then issue a request for the information to be resent. Once the data is
received, the updates to the information can proceed.

### Structure of a SyncML message

Like SOAP, there are two parts to the SyncML message, a Sync Header
`<SyncHdr>`{=html} and Sync Body `<SyncBody>`{=html}. The header
contains meta-information about the request, such as the target database
`<Target>`{=html} and source database \<Source\> URIs, Authentication
information `<Cred>`{=html}, the session ID `<SessionID>`{=html}, the
message ID `<MsgID>`{=html}, and SyncML version declaration
`<VerDTD>`{=html}. The body contains the actual requests, alerts and
data.

### Addressing

Addressing is done through the \<syntaxhighlight\> and `<LocURI>`{=html}
tags. A server will have a familiar URI like
http://www.chris.syncml.org/sync and a client mobile device will have an
IMEI identification number like this 30400495959596904.

### Mapping

SyncML is based on the idea that clients and servers can have their own
way of mapping information in their databases. Therefore, clients and
servers must each have their own set of unique identifiers.

-   Locally Unique Identifiers (LUID) are numbers assigned by the client
    to a data object in a local database (like a field or a row). They
    are non-reusable numbers assigned to these objects by the SyncML
    client.
-   Globally Unique Identifiers (GUID) are numbers assigned to a data
    object for use in a remote database. This identifier is assigned by
    the server.

LUID and GUID numbers only have to be unique if they are being used in a
table between two communicating parties. In other words, these numbers
are temporary, used for mapping data to tables and only really exist for
the complete duration of transactions between client and server.

The server will create a mapping table to tie the LUID and GUID
together.

`<small>`{=html}Client-side data`</small>`{=html}

+---------------+---------------+
|     <nowiki>  |     <nowiki>  |
|     LUID      |     Data      |
|     ----      |     ----      |
|     5         |     Green     |
|               |     </nowiki> |
|     </nowiki> |               |
+---------------+---------------+

`<small>`{=html}Server-side data`</small>`{=html}

+---------------+---------------+
|     <nowiki>  |     <nowiki>  |
|     GUID      |     Data      |
|     ----      |     ----      |
|     5050505   |     Green     |
|               |     </nowiki> |
|     </nowiki> |               |
+---------------+---------------+

`<small>`{=html}Server Mapping`</small>`{=html}

+---------------+---------------+
|     <nowiki>  |     <nowiki>  |
|     GUID      |     LUID      |
|     ----      |     ----      |
|     5050505   |     5         |
|               |     </nowiki> |
|     </nowiki> |               |
+---------------+---------------+

### Change Logs

The Server and Client track of changes made to their databases during
synchronization through \"change logs\". SyncML doesn\'t define the
change logs, instead SyncML does require that the changes and
corrections be negotiated between client and server through messages.
Using change logs, the Client and Server know which fields need to be
updated. The implementation of change tracking in the application which
will use SyncML is not defined.

### Sync Anchors

During Synchronization, the Client and Server need to know which fields
to update. If a client/server application is checking the fields prior
to updating/modifying them, how then does the client/server keep track
of the position of current field in the database? The answer is \"by
using Sync Anchors\".

There are two kinds of Anchors : Last and Next. The \'Last\' anchor
describes which updates occurred during the last synchronization event.
The \'Next\' anchor describes the current and future synchronization
request. These anchors describe the events from the standpoint of the
sending device.

Anchors are sent back and forth from client and server to keep track of
what is happening to the database fields and what\'s going on in overall
through the lifetime of the sync operation.

By coordinating Sync Anchors and change logs with the type of Sync that
is requested, the server application can determine and track (with
change logs) which information is the most up-to-date. For example, it
is possible to overwrite \'newer\' information- that is information for
which there is the most recent time-stamp in the change log- with older
information. This could be done by choosing a sync in which the client
tells the server to overwrite it\'s information with client data. This
is called a \'refresh sync from client\'. The types of syncs are
described below.

### Syncs

There are seven types of Syncs in the SyncML 1.1 language. The following
section describes the types of syncs:

1.  **Two-way Sync** - The client and server exchange information about
    modified data. The client sends the modifications first.
2.  **Slow sync** - a two-way sync in which all fields in the database
    are checked on a field-to-field basis. This type of sync is used for
    the first sync, or after a synchronization failure.
3.  **One-way sync, client only** - the client sends the modified data
    first. The server accepts and updates the data and does not send its
    modifications.
4.  **Refresh sync from client** - the client sends the entire database
    to the server. The server does not sync. Rather, the server replaces
    the target database with the client\'s database.
5.  **One-way sync, server only** - the server sends the modified data
    first. The client accepts and updates the data and does not send its
    modifications.
6.  **Refresh sync from server** - the server sends all its information
    from a database to the client, replacing the client\'s database.
7.  **Server alerted sync** - the server remotely commands the client to
    initiate one of the above sync types with the server. In this way,
    the server is remotely-controlling the client.

### Sync Initiation

Sync Initiation is the process the client and server must go through
prior to an actual Synchronization. The first step is for the client and
server to speak the same language, exchanging and revealing each
other\'s capabilities (as defined by device, as in amount of memory, and
protocol as defined by DTD). The second step is identification of the
databases to be synchronized. Next the two must decide on the type of
synchronization. The third and final step is authentication. Once this
step is completed successfully, the synchronization activities can
begin.

### Authentication

The SyncML server can send the client a message containing the
`<Chal>`{=html} tag in order to represent an authentication challenge to
the information the client is attempting to access. The client must then
respond, giving the username and password within the `<Cred>`{=html}
tag.

SyncML uses MD5 digest access authentication. The Client and Server
exchange credentials during the authentication process, returning error
codes if the process breaks down at some point. The `<Cred>`{=html} tag
is used in the `<SyncHdr>`{=html} for holding the credentials to be used
for authentication.

## Common SyncML implementations

Nokia was the first company to make a SyncML-enabled phone. It
synchronized the calendar database on the phone. SyncML can synchronize
to-do lists, calendars, address books, phone-books, pretty much anything
an organizer can do. SyncML is capable of much more. It would be
appropriate to use SyncML any time there are two disparate, remote
applications which need to share the same data.

## SyncML Syntax

### SyncML Example

`<small>`{=html}Abbreviated SyncML example`</small>`{=html}

+---------------+-----------------------------------------------------+
|     <nowiki>  |     <nowiki><SyncML>                                |
|     1         |     <SyncHdr>                                       |
|     2         |     <VerDTD>1.1</VerDTD>                            |
|     3         |     <VerProto>SyncML/1.1</VerProto>                 |
|     4         |     <SessionID>104050403</SessionID>                |
|     5         |     <MsgID>5</MsgID>                                |
|     6         |     <Cred>...</Cred>                                |
|     7         |     </SyncHdr>                                      |
|     8         |     <SyncBody>                                      |
|     9         |     <Status>...</Status>                            |
|     10        |     <Sync>                                          |
|     11        |     <Target>target database URI</Target>            |
|     12        |     <Source>source database URI</Source>            |
|     13        |     <Add>datafield and data</Add>                   |
|     14        |     <Repl                                           |
|     15        | ace>an existing data field with some data</Replace> |
|     16        |     </Sync>                                         |
|     17        |     </SyncBody>                                     |
|     18        |     </SyncML></nowiki>                              |
|     </nowiki> |                                                     |
+---------------+-----------------------------------------------------+

Notice lines {1} and {18} start the SyncML file with the root tags.
Next, the SyncHdr is defined by lines {2} and {8}. Further, lines {3,4}
define the versioning information, line {5} defines the sessionID to
distinguish which unique dialogue is occurring between client and server
applications, line {6} shows the MsgID to uniquely identify this set of
requests (this entire markup) to be performed by the requested
application. Also in the syncHeader are credentials, on line {7}.

The SyncBody begins on line {9}. In this part of the syncML message,
device/application status {10}, target/source URIs {12,13}, and
requested actions such as the sync itself between lines {11,16}, Add and
Replace {14,15} commands are given.

### WBXML and SyncML

WAP Binary XML (WBXML) is a form of XML whereby the XML tags are
abbreviated in order to shorten the markup for transmission to mobile
devices, which commonly have bandwidth and memory limitations. The XML
tags are encoded into a binary shorthand to save space. Let\'s take a
look at an example so that this will make more sense.

The following is WBXML binary code depicting a SyncML message. Notice in
the first line there is a the document type definition, represented here
in hexadecimal tokens. Can you see what happens to the following string?
\"//SYNCML//DTD SYNCML 1.1//EN\"

!wbxml

Immediately following this string are the characters \'6D 6C 71\'. Each
of these represent a SyncML tag.

`<small>`{=html}wbxml abbreviations`</small>`{=html}

+-----------------+---------------------------+
|     <nowiki>    |     <nowiki>              |
|     6D          |     = "<SyncML>"          |
|     6C          |     = "<SyncHdr>"         |
|     71</nowiki> |     = "<VerDTD>"</nowiki> |
+-----------------+---------------------------+

`<small>`{=html}wbxml abbreviations (cont.)`</small>`{=html}

+-----------------+---------------------------------------------------+
|     <nowiki>C3  |     <nowiki                                       |
|     03          | > = represents the beginning of opaque (xml) data |
|     "1" "." "1" |                                                   |
|     01</nowiki> |  = this represents the length of this opaque data |
|                 |     = The characters "1" followed by "." and "1"  |
|                 |     = represents "</VerDTD>"</nowiki>             |
+-----------------+---------------------------------------------------+

tells the SyncML processor that this is the beginning of opaque (xml)
data this represents the length of this opaque data The characters \"1\"
followed by \".\" and \"1\" represents \"`</VerDTD>`{=html}\"

All together this WBXML code snippet, *6D6C71C303\"1.1\"01* represents:

`<small>`{=html}SyncML header snippet`</small>`{=html}

+---------------+-----------------------------------+
|     <nowiki>  |     <nowiki>                      |
|     1         |     <SyncML>                      |
|     2         |     <SyncHdr>                     |
|     3         |     <VerDTD>1.1</VerDTD></nowiki> |
|     </nowiki> |                                   |
+---------------+-----------------------------------+

So you can see how using WBXML shorthand would be a more compact means
of representing XML, saving bandwidth for mobile devices.

For more information please refer to Ed Dumbill\'s articles on syncML
with WBXML:

-   Have Data, Will
    Travel
-   WBXML and
    SyncML

## SyncML specifications

The best source of information on SyncML is the protocol itself. Visit
the Open Mobile Alliance for the SyncML specifications.

### Open Mobile Alliance

Download OMA SyncML Specifications and white
papers at the
Open Mobile Alliance. Or check out
the SyncML
Articles at
the Open Mobile Alliance.

## SyncML Implementations

Although the SyncML specifications are useful, you still have to
implement the protocol in your application. There are a few toolkits and
implementations out there that you can use to get a head start.

### SyncML Reference Toolkit

The Open Mobile Alliance has released a toolkit written in C to
demonstrate SyncML. You can get it
here. If you can
read German, you can get a sample application using the toolkit
here.

### Funambol

Interested in developing SyncML for Java? Check out the open source
project Funambol. It offers a Java
and C++ SDK that implements the SyncML data synchronization protocol, a
Java-based application framework for building SyncML server
applications, and a standalone SyncML server.

## Summary

Mobile Device Technology is improving and changing at a rapid pace. As
US telecommunication companies implement Third generation (3G) WCDMA
technology (wide-band code-division multiple access), or wireless
broadband, we will begin to see powerful devices emerge on the market.
These devices will be able to deliver full color, video, streaming
multimedia and a variety of data services such as Multimedia Messaging
Service (MMS) through WAP. In that infrastructure is becoming cheaper,
these telecommunication companies are starting to shift towards being
service providers and media vendors as opposed to communications
utilities. Cingular wireless, multimedia messaging and ringtones
services are a good example of the shift of their company towards being
a *media platform*. The companies that will survive will be the ones
that listen to customers needs and make easy-to-use services.

Telecommunications companies can add value to their services by creating
custom applications and services that use SyncML for synchronization.

```{=html}
<div style="color:#8b4513;">
```
## Exercises

1.  Visit the Open Mobile Alliance Website, download the pdf of the
    SyncML v. 1.1 protocol and review it. Reading this reference is a
    valuable exercise in learning.
2.  Answer these questions:
    -   What is WBXML and why is it used?
    -   How do you foresee SyncML being used in the future?
    -   Name a problematic situation whereby SyncML is the best \'tool\'
        for the job.

`<small>`{=html}`<small>`{=html}*Answers: 2a) WBXML is Wap Binary XML,
it is a form of XML whereby the XML tags are abbreviated in order to
shorten the markup for transmission to mobile devices, which commonly
have bandwidth and memory limitations. 2b) SyncML will likely be used as
a general, standard syncing mechanism for synchronizing data sets
between systems, not just for mobile devices. 2c) A ticket-tracking
system called TNT helpdesk is a web-based open work request management
system. The staff running this system would like to have live data from
this system on their PDAs, listing open requests. Currently, the PDA
database is synced via a docking sync station attached to the staff
members\' PCs. Staff members have to download the request list as a CSV
file, convert it into a usable PDA database and upload it to the PDA,
making it this process cumbersome, prone to error, and always
out-of-date. Recommendation: Create a custom app to push live updates to
the PDAs using SyncML over
Bluetooth/Wireless*`</small>`{=html}`</small>`{=html}

```{=html}
</div>
```
## References

+----------------------------------------------------------------------+
| Dumbill, E.(2002, January 1). *XML Watch: Have data, will            |
| travel.* IBM.com. Retrieved April 6, 2004 from\                      |
| <http                                                                |
| ://www-106.ibm.com/developerworks/xml/library/x-synchml/index.html>\ |
+----------------------------------------------------------------------+
| Dumbill, E.(2003, March 1). *XML Watch: WBXML and basic SyncML       |
| server requirements.* IBM.com. Retrieved April 6, 2004 from\         |
| <http://www-106.ibm.com/developerworks/xml/library/x-syncml2.html>\  |
+----------------------------------------------------------------------+
| *How \[SyncML\] works*(n.a). Nokia.com. Retrieved April 6, 2004      |
| from\                                                                |
| <http://www.nokia.com/nokia/0,8764,2559,00.html>\                    |
+----------------------------------------------------------------------+
| *The New SyncML Standard.* . Cellular Dot Co Dot Za                  |
| Website. Retrieved April 6, 2004 from\                               |
| <http://www.cellular.co.za/syncml.htm>\                              |
+----------------------------------------------------------------------+
| Open Mobile Alliance (2002, April 2). *SyncML version 1.0, 1.1       |
| specification, white paper, errata.* Retrieved April 6, 2004 from\   |
| <http://                                                             |
| www.openmobilealliance.org/tech/affiliates/syncml/syncmlindex.html>\ |
+----------------------------------------------------------------------+
| Pabla, C(2002, April 1). *SyncML Intensive: A beginner\'s look at    |
| the SyncML protocol and procedures.* IBM.com. Retrieved April 6,     |
| 2004 from\                                                           |
| <http://www-106.ibm.com/developerworks/xml/library/wi-syncml2/>\     |
+----------------------------------------------------------------------+
| SyncML Initiative, Ltd.(2000, December 7). *SyncML Specification     |
| Protocol version 1.0.* The Open Mobile Alliance. Retrieved April 6,  |
| 2004 from\                                                           |
| <http://www.openmobileall                                            |
| iance.org/tech/affiliates/syncml/syncml_represent_v10_20001207.pdf>\ |
+----------------------------------------------------------------------+
| SyncML Initiative, Ltd.(2002, February 15). *SyncML Device           |
| Information DTD version 1.1.* . Retrieved April 6, 2004 from\        |
| <http://www.openmobile                                               |
| alliance.org/tech/affiliates/syncml/syncml_devinf_v11_20020215.pdf>\ |
+----------------------------------------------------------------------+
| Saarilahti, A, Group SyncML, et al.(2001, April 23). *Tik-76.115     |
| Short introduction to SyncML.* . Retrieved April 6, 2004 from\       |
| <http://www.hut.fi/u/asaarila/syncml/syncml_intro.html>\             |
+----------------------------------------------------------------------+
| Stemberger, S.(2002, October). *Syncing Data: An introduction to     |
| SyncML.* IBM.com. Retrieved April 6, 2004 from\                      |
| <http://www-106.ibm.com/developerworks/wireless/library/wi-syncml/>\ |
+----------------------------------------------------------------------+
| Synchronica Software GmbH(n.d.). *SyncML for Microsoft               |
| Exchange.* Synchronica Software Website. Retrieved May 24, 2004      |
| from\                                                                |
| <http://www.synchronica.com/products/syncml/corporate_syncml.html>\  |
+----------------------------------------------------------------------+
| Weblicon Technologies AG (n.d.). *SyncML for SunOne.* Weblicon       |
| Technologies AG Website. Retrieved April 6, 2004 from\               |
| <http://www.weblicon.net/html/products_syncml.html>\                 |
+----------------------------------------------------------------------+
| XML Cover Pages (n.a., 2003, April 29). *The SyncML Initiative.* XML |
| Cover Pages Dot Org Website. Retrieved April 6, 2004 from\           |
| <http://xml.coverpages.org/syncML.html>\                             |
+----------------------------------------------------------------------+

fr:Programmation XML/SyncML