# XRX/Print version

Current, editable version of this book is available in Wikibooks, collection of open-content textbooks at URL: http://en.wikibooks.org/wiki/XRX
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license can be obtained here.

# Section 0: Overview and TOC

XRX or XForms/REST/XQuery is a simple and elegant web application architecture that leverages modern declarative and functional programming systems. XRX allows the developer to create rich-client web applications that perform complex functions without the need for middle-tier objects, relational databases or client-side JavaScript.
XRX is based on three standards:
* XForms on the client
* REST interfaces
* XQuery on the server
These three standards have been created by the W3C standards organization and represent their vision of the future of web application development. For discussions on alternate definitions of the XRX web application architecture see What is XRX.
This wikibook is intended as an example that specifically uses all three of these technologies to create small applications that work together.

## Related Wikibooks

There are two sibling Wikibooks that this Wikibook is designed to complement.
The XForms Tutorial and Cookbook Wikibook has over 90 sample XForms application to help you become familiar with the XForms model and XForms controls. Although XForms has only 21 elements they can be combined in many different ways to build very complex web clients.
The XQuery Wikibook is focused on using the XQuery language with almost all of the sample programs using the eXist native XML database.
The XForms Wikibook has minimal dependencies on which server you use to host your web forms. Almost all of the XQuery Wikibook does not assume any prior knowledge of XForms. This book, on the other hand, assumes that you will be using both XForms and XQuery to create a complete web application development environment.

## Subversion Repository

Many of the example programs in this cookbook are now being stored in a Subversion repository on GoogleCode. The URL for the XRX GoogleCode is here:
http://code.google.com/p/xrx
If you are using an IDE with a Subversion client such as Eclipse or oXygen, the URL for the repository is:
https://xrx.googlecode.com/svn/trunk
If you would like a read-only copy, you can use the non-SSL URL
http://xrx.googlecode.com/svn/trunk

## Table of Contents
### Introduction

* Introduction - an overview of the goals of this Wikibook and the intended audience
* Benefits of XRX - an analysis of the technical benefits of the XRX web application architecture
* XRX Application Server - how XRX has allowed the XQuery language to move from a database language to an application language
* Building your First XRX Application - some suggestions on how to get started building your first XRX application
* Background Technologies - a summary of the background technologies you will use to build XRX applications
* Patching you Browser to Support XForms - how to add functionality to support the W3C XForms standards
* XSLTForms and eXist - getting XSLT forms to work with eXist

## Common Patterns

* Application Modularity - XRX applications can be managed and reused if they have modular structure
* Data Encapsulation - XRX applications contain and manage their own data sets and provide XQuery functions as interfaces
* Standard Views - XRX applications contain standardized views of their data
* Searchability - XRX applications provide tools to search their own data and interfaces to allow it to participate in site-wide search functions
* Code Table Management - XRX applications manage code tables (selection lists) and make it easy for non-programmers to maintain these codes
* Server Field Validation - XRX can use server-side XQuery to validate a field
* Breadcrumb Navigation Bar - XRX applications are nested in a hierarchical structure an navigation breadcrumbs are context aware

### Sample Applications

* Configuration File Editor - a simple file, single user XML configuration file editor using XForms and eXist
* Dictionary Editor - a simple round-trip create/update edit using XForms and eXist
* Regular Expression Builder - a demonstration of using regular expressions in XQuery
* Autoincrement File ID - save an instance from a form into a collection and have the id automatically created by the server
* Move a Resource - simple resource move utility
* Save File Dialog - saving a file to a collection similar to a save dialog panel
* Login and Session Management - a login panel and methods of authenticating users
* File Locking - strategies to prevent multiple users from overwriting each others updates
* Selection List Generator - a tool to generate selection lists from code tables
* Glossary Term Editor - a tool to manage specialized business vocabularies
* FAQ Manager - a tool to manage frequently asked questions
* Detecting Duplicates - checking for duplicates as you type
* Data Element Editor - a tool to manage ISO/IEC 11179 data elements
* Selection List Management - tools to manage selection list codes in your XForms
* Customizing Selection Lists - customize the selection list based on role or other session variable
* Table Sorting - customization of table sort order
* NIEM Services - tools to create NIEM web services
* Product Ratings - allows users to assign a rating of one to five stars to an item in a collection
* Business Rules Template - a sample of a simple business rules template
* Metadata Shopper - a shopping cart tool for your metadata elements
* Subset Generator - a program that generates a subset of a metadata registry that is imported into an XML Schema
* XForms Generator - convert an XML Schema directly into an XForms application
* XForms Instance Generator - convert an XML Instance directly into an XForms application
* Large XForms Generator - create large XForms using a single REST parameter
* User Manager - track users and manage their login attempts, session timeouts and roles
* Map Navigation - add map navigation to your XRX applications

### XRX Patterns

* Content Routing - inspecting the content of an XML document to apply save rules
* URL Rewriting - allow URIs to reflect the logical structure of a service, not the collection structure of the database

### Related Technologies

* LAMP - Linux, Apache, MySQL and PHP
* AJAX - Asynchronous JavaScript and XML
* Adobe Flex - Adobe's system for building rich-client interfaces (Now Apache Flex)
* Microsoft Silverlight - Microsoft's strategy for putting XML in the browser (Discontinued)

### References

* Related Wikibooks
** XForms
** XQuery
Please add {{alphabetical}} only to book title pages.

# Section 1: Introduction
## Background

This cookbook was created by Dan McCreary in the Spring of 2008. The XRX label was created by Dan soon after the December 2007 XTech meeting in Boston. Dan found many people there that all came to the same conclusion: using XForms and a native XML database offered some huge advantages. He also found that his related cookbook (the XForms cookbook) started to have many examples that used not just XForms but also XQuery as a back end. In order to keep the XForms cookbook general and still appeal XForms developers, many of the XForms/XQuery examples were migrated to this Wikibook.
Many XRX fans feel XRX to be a superior web application architecture, a natural consequence of XML being used both in the client, as a data transmission standard, and in the server.
We hope you find this book useful and we hope you contribute to the examples.
Next: Benefits of XRX

## Benefits of XRX Architecture

XRX benefits from each of its three underlying standards:
* XForms
** Unlike technologies such as AJAX, XRX assumes a model-view-controller architecture
** XForms supports a dependency graph that allows the right views to be automatically updated
** All interactions between the client and the server are sent through the model via submission elements
* REST
** XRX takes advantage of web infrastructure such as multi-level caching and technologies that are collectively known as deep REST systems.
* XQuery
** XQuery is a functional XML-oriented query and transform language that can perform the business logic for many systems. In addition to its XML transform capabilities, it has advantages over older query languages such as SQL designed in the 1970s and 1980s. XQuery has the expressive power of SQL (joins etc) and can also manipulate recursive hierarchical data structures. Unlike SQL, XQuery is a W3C standard with very strong standardization across vendors and over 14,000 tests to ensure cross vendor compatibility. Developers frequently develop XQuery applications on low-cost OpenSource databases and port them to commercial systems without significant changes.
Together, these three standards allow developers to use a single data format (XML) on the client, middle tier and the databases server. This means there is no translation of the data formats between layers. In contrast to this, many other modern systems communicate using XML, process business logic in an object-oriented layer, store data in a relational database, and render a GUI as HTML.
Consider all the "glue" code in a typical modern system, which serves no purpose other than to translate from one representation to another: object-relational mappings, HTML rendering code, XML import/export code. These web application architectures take HTML forms (which use flat key-value pairs), convert these data structures to middle tier objects such as Java or .Net and then transform the objects into tabular data streams so they can be stored in relational databases. Once in the relational database the data must then be re-serialized by doing SELECT statements, converted into objects and the objects then converted back into HTML forms. This is a four-step translation architecture.
In contrast, XRX uses a zero-translation architecture. Zero translation implies that XML is stored in the web client, transmitted to a middle tier validation rules engine in XML and then stored in its entirety in an XML database. Typically, XML is also the format that data is delivered or streamed in from other systems. The storage as XML is also known as a zero-shredding process since the data files are not separated into Third Normal Form (3NF) data structures.
This relational (3NF) storage is often not helpful. XML data has the relationships built into the data, whereas relational data is stored in "dumb" tables and allows/requires the applications to specify the relationships. For applications where the relationships are well known (e.g. a user has a collection of blog posts, and those posts have collections of comments and replies) XML is better. When a "data warehouse" is needed and the relationships will vary widely based on the calling application, a relational store may be better because RDBs are optimized for ad-hoc joins where XML DBs are generally not. (e.g. a group of users are in a social network and there are a variety of ad-hoc relationships that *all* must be queried quickly - use an RDB). XML databases are optimized for the relationships built into the XML, relational databases are optimized for easy programming and performance on one preferred set of relationships.
The biggest difference, though, is zero-translation vs. "translation everywhere."

## 1+1+1=10

Using a combination of all these three standards gives web developers a tenfold increase in productivity.
Back: Introduction • Next: XRX Application Server

## References

XRX: Simple, Elegant, Disruptive

## XRX as an Application Server

XQuery is a transform language in addition to a query language. Its original name was "Quilt" reflecting its ability to knit together different pieces of (XML) content.
This means that it is good at querying XML data from a data store and transforming it into an XHTML web page. Any XQuery-capable XML data store that accepts HTTP requests can talk to your web browser and send it an arbitrarily complex, valid (X)HTML document.
Here is a short example of how XQuery can transform XML database records into valid HTML:
can be "transformed" to HTML:
with XQuery something like (not tested):
Many free and commercial XQuery-enabled databases are available. They include: BaseX, DB2, eXist, MarkLogic, Oracle, and xHive. BaseX and eXist are free, and MarkLogic (and perhaps others) has a free community edition. Many if not all of them support HTTP requests, and therefore can be used as web/app servers.
BaseX:
BaseX is both a light-weight, high-performance and scalable XML Database and an XQuery 3.1 Processor with full support for the W3C Update and Full Text extensions. It focuses on storing, querying, and visualizing large XML and JSON documents and collections. A visual frontend allows users to interactively explore data and evaluate XQuery expressions in realtime. BaseX is platform-independent and distributed under the free BSD License.(from their website)
It also has a stand-alone mode and a web-server mode.
eXist:
Although the eXist database was originally created to simply store XML data like a traditional database, the rich REST interfaces that have been added to eXist have transformed it into a web server. The eXist database is now able to provide a rich set of functions that are only available in other application servers. What remains is the application development standards that would allow a large number of people developing XRX applications to all work together.
MarkLogic:
MarkLogic is perhaps the most capable XML data management product at this writing. It combines XML/XQuery with text indexing and retreival, geospatial, alerting, and enterprise class scaling and performance.
xHive (or xDB):
xHive is a state-of-the-art native XML database with XQuery support, transaction control, extensive indexing features and top-class scalability.
DB2, Oracle, PostgreSQL:
DB2, Oracle and PostgreSQL support XML by incorporating it as a large CLOB field, and support XQuery on this data. PostgreSQL currently supports only XPath (as a subset of XQuery). It checks the input values for well-formedness, and there are support functions to perform type-safe operations on it.

## XRX Application Server Vision

The XRX application server can now be set up to allow a wide variety of applications to be installed that all work together.
Back: Benefits of XRX • Next: Building your First XRX Application

## How Build Your First XRX Application

Although there are many different ways you can build an XRX application, there are two vital ingredients to get you started. First you will need a way to create XQueries with RESTFul interfaces. The OpenSource native XML database eXist seems to be the favorite of most people although the MarkLogic server has a community version that is free as long as your data sets are under 10GB which seems to be enough for most pilot and learning projects.
The second component you will need is some client that will take an XForms data stream intended for a browser and build applications with it. Because the XSLTForms client is now bundled with both eXist and MarkLogic and runs on all browsers many people are using this client.
If you need forms that need to load quickly without the overhead of loading the large XSLT transforms and JavaScript libraries, the FireFox XForms addon is also a very mature product, but does not run on FireFox versions higher than 3.0.12.
The Picoforms XForms client for IE and Chiba forms will also work very well. If you are looking for a pure server-side transform you may want to look into Orbeon Forms or the IBM Workplace Forms tools.
There are five architectural tasks that you will need to master. They go by phrase CRUDS: Create, Read, Update, Delete and Search. Having a tool to quickly import XML data from spreadsheets is also very useful as you migrate more data into your XRX application server. The oXygen XML editor is a favorite because is has strong support for the eXist database.
Once you have understood the basic concepts in the CRUDS cycle, you can then explore ways to optimize reports using XQuery and XQuery functions and modules.
Back: XRX Application Server • Next: Background Technologies

## Standing on the Shoulders of Giants

The XRX architecture did not appear overnight. It was only made possible by the diligent work of many standards organizations over many years. Clearly the XML standard is one that enabled most of the key technologies. But the role of HTML, HTTP, CSS, XPath, XML Schema, XSLT, XForms, REST, Schematron and XQuery and other standards created by the W3C really must be appreciated to understand the true scope of the standardization efforts. Here is a brief overview of these technologies and a rough order that they were created and could be learned.

## XML Syntax

The syntax of using "less than" and "greater than" characters to bracket data elements embedded in a text document goes back to early markup languages such as SGML. SGML was the language that the HTML standard was modeled on. SGML was a complex standard that required the user to be familiar with many technologies, so in 1997 an effort was made to simplify the standard and the XML standard was first published by the W3C.

## XPath

The XPath language is a smaller data-selection language that is used extensively within other XML standards. Both our client technology (XForms) and our server technology (XQuery) heavily depend on using XPath to surgically remove the elements we want from much larger XML tree structures. If you are familiar with UNIX or web file system paths you may already have a good mental model for how XPath expressions work. For the purposes of this book we will be using mostly very simple XPath expressions that merely narrow XML data sets using "child" paths and "where" paths called predicates.

## XForms

Although this wikibook is not intended to be a book on XForms, the use of XForms makes client application development very consistent with the rest of the material in this book. We will cover just enough background to help you understand the key architectural features of XForms and how it leverages REST interfaces to get and submit data to the server. Technically you can still benefit from the XRX architecture without using any XForms applications on the client but you may find that you duplicate most of the components that are already in XForms when you do this. Central to the concepts in XForms are the MVC architecture, Binding, the dependency graph and declarative submission elements. If you are a fan of JavaScript and AJAX, you can implement much of the functionality of XForms using these tools. But this topic is not covered in this wikibook. In fact many people use XRX architecture specifically to avoid having to learn JavaScript and the myriad of JavaScript frameworks that are popular today.

## XQuery

Anyone who is familiar with the SQL language understands the role of the SELECT statement in selecting the appropriate tables, columns and rows from a relational database. XQuery on the surface may seem only like a version of SQL for XML databases. Because XQuery can be easily extended, however, it has taken on a much larger role then just a reporting language for XML databases. XQuery may be the only server language that a developer will ever need. Because it can be easily extended, it has already been extended in hundreds of useful ways.
The first major extension has been the ability of XQuery to update XML data. This was considered important to the original XQuery authors, but they decided to focus on data selection first and data updating second.

## CSS

One of the most elegant aspects of the XForms model is that it was designed from the ground up to work with the W3C's Cascading Style Sheet (CSS) standard. Thus, almost every aspect of how web application controls are arranged on the screen can be managed by a single site-wide CSS file. The consequence is that if you decide to make a site-wide change, only a single file needs to be altered. The downside is that the level of CSS support varies dramatically in many browsers. Since XForms is implemented as a separate namespace and CSS is designed to be namespace aware, most modern style sheets for XForms leverage this basic feature. The challenge is that not all browsers have implemented the CSS namespace functionality. This issue is complex and any XRX architecture that is building applications to support older browsers must take these caveats into consideration.
Back: Building your First XRX Application • Next: Patching your Browser to Support XForms

## Motivation

Your browser does not support the W3C XForms standards.

## Method

Browsers should detect the XForms namespace and just render the XForms controls per the XForms specification. But many browsers vendors do not do this, perhaps because they feel that supporting their own standards is in the best interest of their stockholders. Whatever the reason, it can make life difficult for the website developer.
If you are running Firefox, you can load an extension that will correctly recognize the XForms namespace and do the right thing.
Some XForms implementations, such as XSLTForms, require you to add an XML Processing instruction to correctly convert XForms controls into HTML+JavaScript.
Here is an example of how to do this using the XML processing-instruction function within eXist:
This will return a sequence of two items, the Processing instruction and the form itself.
You can also build your own "form assembler" that uses a title, model and content.
Back: Background Technologies • Next: XSLTForms and eXist

## Motivation

You want to port your standard XForms applications to work with XSLTForms and to be able to dynamically generate XForms from eXist XQueries.

## Method

XSLTForms is a very lightweight XForms processor that can be configured to run either on the web server or the web client. XSLTForms transforms each XForms element in the XForms application into HTML with some JavaScript. If you are using the client to do the transform, you must be aware of some limitations in client side-browsers.

## Client-Side or Server-Side Transform: Design Tradeoffs

The design decision of where to execute the transform, on the client or on the server, is one that may vary based on your situation. Transforming the form on the server can sometimes avoid the transmission of the full XSLT transform to the client and it also avoids browser-dependent variations. This process also may work more naturally for pipeline operations that use tools like XProc on the server.
On the other hand, once the first form is loaded, the XSLT transform can be read from the local browser cache. This allows you to only have to transmit the actual XForms application specification and not the much larger JavaScript and HTML code. So this option can minimize the network traffic as well as minimize the delay in displaying the changes.
The XSLTForms application is a library for doing XSL transforms based on the XForms input file. The output is a combination of HTML and JavaScript that will run across many browsers (Firefox, Internet Explorer 6, 7 and 8, Apple Safari, Google Chrome, and Opera).
Note that for many internal forms on an intranet, it is possible to request that all your users use a web browser that supports in-client plugins. This means that your XForms load times are very fast and your testing process is simple. For public forms, you often can not specify what browser the users must use, so the forms developer is required to test on many different versions of many different browsers. This can dramatically slow the forms development process and can cause testing and development costs to grow.

## Disabling betterFORM on eXist 2.0 and 2.1

eXist 2.0 and 2.1 come with the server-side XForms processor betterFORM installed as default. In order to allow XSLTForms to process XForms, you should do one of the following:
To use XLSTForms in a certain context, but allow the use of betterFORM in other contexts, set the following dummy attribute in your XQuery:
in the XQuery that generates your form.
In order to disable betterFORM completely, change
<property name="filter.ignoreResponseBody" value="false"
to "true" in $EXIST_HOME/webapp/WEB-INF/betterform-config.xml
or comment out the entries for XFormsFilter in $EXIST_HOME/webapp/WEB-INF/betterform-config.xml and/or in $EXIST_HOME/webapp/WEB-INF/web.xml and restart.

## Browser Portability Issues

One of the large challenges attendant on supporting multiple versions of browsers from many vendors is that the way they render CSS can be dramatically different. Since XForms frequently leverage advanced CSS structures for form layout, this can be a large concern for XForms application developers. IE 6 can be especially troublesome due to its lack of full support for the CSS box model. This is especially true of forms that do not use HTML Table layouts to render forms. What was a simple style sheet for a single browser may often grow to be very complex and require many days of testing. For example the use of inline-block has many variations on many different browsers.
The best defense against the browser incompatibilities is to keep your forms very small and simple. Use many different class attributes and don't use repeating structures unless absolutely necessary.

## Problem with Namespace Axis in Firefox 3.0

There is currently a namespace bug in the Mozilla Firefox browser that prevents any instances from being loaded that use the non-null namespaces. For example the following XML file cannot be loaded into an instance using the src attribute.
The workaround is to put a dummy namespace prefix reference in the HTML root element, such as:
The ex:dummy="dummy" will fix the problem and the instances will load correctly into the form. This patch may not work on other versions of Firefox. Note that the instance can be loaded inline to get around this bug. Also note that using the default namespace in the instance will also not work.
This is known as the Firefox Namespace Axis Problem. This is not a problem in Internet Explorer, Safari, Opera or Chrome. Firefox is the only browser that does not support namespace axis functions. XML support appears to be a low priority within Mozilla. We encourage anyone that feels that Firefox should support XML namespaces to vote for this bug fix on the Mozilla web site.
See Mozilla Bug ID 94270. The comment by C. M. Sperberg-McQueen is very informative.
The article by Uche Ogbuji discusses the new features Firefox 3.0 offers for XML processing.

## How XSLTForms works

To convert your standard XForms to work with XSLTForms you only have to add the following statement as the first line of your XForms file.
The actual URL to use on your eXist installation may vary depending on your version. This document is large for an XSLT stylesheet (currently about 114KB and 4,500 lines long), but much smaller than many JavaScript libraries that run over 50,000 lines of code. The XSLT process also loads a 363KB JavaScript file. The key is that once it is loaded for the first form it can be stored in the web cache. A compressed version of this file may provide faster loading times in the future. This process will always be slower than a native XForms processor like the Firefox XForms extension, but the benefit is that it will work on multiple browsers once the XForms stylesheets have been tested on one browser.

## Controlling Client and Server XSLT Execution

By default, eXist will always attempt to perform server-side XSLT processing whenever it encounters an XML Processing Instruction that signals that it should perform a transform.
If your XForms are static, meaning that they do not change at all based on the context of the situation, you can store the forms anywhere on a web file system. They do not need to be stored in eXist.
If you store the XForms in eXist, there are two items you must be aware of.
By default, eXist processes all XML XSL processing instructions and runs them on the server BEFORE they ever reach the browser. This is not the way that XSLTForms was originally designed to work. It also requires a lot more bandwidth between the client and the server.
To disable server-side XSLT processing you will need to add the following instruction to your XQuery that generates the XForms:
The first line sets the XHTML serialization type and also sets the standard XML mime type.
Note: Many browsers such as IE do not recognize the proper XForms mime type of application/xhtml+xml. To get around this problem you can use the incorrect mime type of text/xml. There are ways to fix IE to recognize the correct mime types by making changes to the Windows registry but these changes are difficult to make for general users. For more details see here
The second line is required by the current release of XSLTForms. The last line tells the server-side to not process the transform.
These three options can be combined into a single statement:
Note that in the context of eXist, process-xsl-pi=no means "do not process this on the server before you send it to the browser".
One approach to generating dynamic forms is to use the following style:
You can then return the following at the end of your form:
For debugging you can also use:
Here the href points to the location you have installed your XSLTForms library.

## Server-side Transformation using the transform Function

eXist provides a method for doing a server-side XSLT transform using the transform module. The following is an example of using this transform function to perform server-side transformation of the form.

## Using XSLTForms on the Server Side in a URL Rewrite Filter

It is also possible to perform server-side transformation using eXist's URL Rewrite function.
Sample from /eXist/webapp/xforms/controller.xql
See Example from eXist subversion

## Modifying your CSS to work with XSLTForms

Because XSLTForms uses XSLT on the web client, it only knows how to parse XML files. To get your CSS files to work you will have to make each of your CSS files a well-formed XML document. This can be easily done by simply wrapping your CSS file with a root data element such as:
If you wish your CSS to be both valid CSS and well-formed XML, you can use a special prolog <css><![CDATA[/**/ and epilog /*]]>*/</css> as shown in the two examples below. As interpreted by an XML parser:
The same file interpreted by a CSS parser:
You can then just import the CSS file into your XForms file using the link element:
XQuery can also be used to automatically generate the CSS file from the server. On the server the CSS file can be wrapped, but for non XSLTForms clients the root element can be removed.
If there are small changes in the CSS that are not global to all other forms, you can insert them directly into the <style> tag of the form. Note that if your XForms are dynamically generated from an XQuery you must enclose the style with CDATA wrappers or use double curly braces {{ and }} to escape the XQuery processing.
Note that in the Firefox plugin the CSS class for changing the value was .xf-value. In XSLTForms the class is .xforms-value.

## Disabling the CSS Conversion Option

XSLTForms also allows you to add the following XML Processing Instruction flag to your XForms file.
If you add these lines the CSS files will not need to be converted to XML files. You can not use the @namespace xf features within the CSS, and you may have to add class attributes to tags, but some users prefer this method.

## Formatting XForms Elements

The following syntax should be used for styling XForms elements:
Note that this format has been tested with XSLTForms on IE 8, Firefox, Opera and Safari running on Windows, the Mac and Linux.

## Rendering Block Forms

Block forms are forms that use a block layout for each control so each control appears on a different line. Block forms have a consistent layout and have room for hint text, required field labels and help icons. Inline forms that have multiple fields on a line should be used only when you have screen area constraints.
To render block forms correctly we suggest you wrap all block forms in a standard div tag with a class of "block-form":
This allows you to use a CSS file where the block display items are only triggered if they are decendants of the block form div element.
Here are some sample CSS rules for block forms.
The most risky part of this is the inline-block rule. This is required to allow you to fix the width of the label.

## Aligning select1 with appearance=full

If you want to display all the items in a selection list you can add the attribute
To keep the item values together you must add the following to your CSS file:

## Using xf:load in place of xf:submission

The current release of XSLTForms does not support the xf:submission element with the correct URL rewrite when the replace="all" attribute is used. This structure is used in many search forms, when a form is used to gather a set of parameters, such as keywords and date ranges that are used to limit the search. These search parameters are traditionally stored in a single instance in the model and used to construct a URL for a restful search service.
Here is an example of search parameters stored in an instance in your model:
XSLTForms does however support the xf:load function, and when you use xf:load with the xf:resource subelement you can achieve the same result.
For example within a trigger action you can use the following:

## Controlling Namespace Prefixes in the Output

XSLTForms can change the way that namespace prefixes in your instance data are managed. If you load an instance with a default namespace, all the submitted data will include a namespace prefix.
If your input is:
Then the saved output will become:
This can be controlled by the includenamespaceprefixes attribute of the submission element.

## Bind Restrictions

With XSLTForms you can only have a single bind per element in your instance. So for example you can not put the data type in a separate bind as a required bind. It will generate an error, but will not indicate which element is bound twice.

## Set Focus on Inserts

There is no way to set the focus on a new insert.
See Repeat Test 1

## Upload file with XSLTForms

Versions of XSLTForms earlier than rev. 537 (April 2012) do not support the XForms Control upload.
For versions 537 and later, the XForms "upload" control is supported and behaves essentially as described in the XForms 1.1 specification.
For version earlier than 537, there is a work-around.
In case of submission method "xml-urlencoded-post" XSLTForms dynamically build a form whose ID is "xsltforms_form"
If this form still exists, XSLTForms replaces the value of the first child of the form by the serialization of the submitted instance content.
Example
Model
Form
Submission
XQuery load.xql
This is a trick that enables uploading files within an XSLTForms application. File content is not loaded in instance.

## References

* XSLTForms Home Page
* XSLTForms on SourceForge
* XSLTForms Test Results
* XSLT transform the transform itself is around 3,000 lines

## Acknowledgements

Most of the above materials were generated with the kind assistance of the XSLTForms author Alain Couthures.
Back: Patching your Browser to Support XForms • Next: Configuration File Editor

# Section 2: Common Patterns
## Motivation

You want to be able to package and reuse XRX applications.

## Method

We will use the collection structure of native XML databases to package XRX applications.
Our XRX Application framework uses the following conventions:
* All applications are placed in a common collection called apps. This is similar to the "/Applications" folder on a Mac(TM) or the "Program Files" folder in Microsoft Windows(TM).
* Each application has a collection of its own within the apps collection. We use REST-friendly application names that have only lowercase letters and dashes. For example a tool that manages organization business terms might be located in a collection called "/db/apps/terms". Databases that host multiple organizations might store each application collection in a separate apps collection for each organization. For example "/db/org/my-company/apps"
* All user-manageable data that is contained within the application is contained with a "data" collection within the application collection.
* XQuery functions that are common to multiple applications should be stored in a sibling folder to the "apps" collection. This allows each application to use relative module imports so that applications can be quickly re-installed on other sites.

## Motivation

There are several motivations for data encapsulation.
* You want to make it clear to others what data an application manages.
* You want to use the same encapsulation patterns of object-oriented systems.
* You want to be able to prevent other applications from changing your data.
* You want to use consistent role-based access control for your applications data.
* You want to make it easy for all applications to share data management code for tasks such as ID assignment, versioning and linking.

## Method

Each XRX application stores all its user-managed data in a sub-collection of the application called data. For example if your application manages business terms the collection path to the terms might be:
Each XRX application stores its own data. When this application's main collection is removed, all the data that it manages is also automatically removed by the simple nature of the collection structure.

## Motivation

XRX applications need standards for viewing lists of items as well as HTML view of specific items.

## Method

One of the first functions of most web applications is to provide some way to browse and view data. With XRX application we call these functions list-items and view-item. These are generic XQuery scripts that are located in a views sub-collection of the main application collection. View are by their name, read-only views of the XML data.

### Listing Items

In general, the list-items function must show a brief summary of each record. It is usually displayed in a table view with each column helping to identify a record and distinguish this record from other records. The following are typical requirements of a list-items XQuery
* Display a single line representation of a record
* Display the records in a logical order
* Display columns that help identify the record
* Allow for pagination for large record sets
* Provide links to key per-record functions such as viewing the full record, edit or delete

## View Item

* The view-item query provides a read-only view to a specific record. It required a parameter of the record identifier.

## Motivation

You want to make it easy for users to find data items with your XRX application.

## Method

Each XRX application that keeps search-able data will have a sub-collection with search features in it. At a minimum this is a search form and a search query. In some cases the search query script is also used to render the search form.

## Motivation

You want to be able to manage all code-tables and selection lists in a consistent way across multiple applications.
Specifically:
* XML files that are exported to external sources should not use numeric codes that are not descriptive of the semantics of a category.
* Any codes that are passed as RESTful parameters should use URL-friendly codes (lowercase and dashes)
* All user views of codes should use "labels" that may be contextual to a specific language
* Role-based access should allow separate forms that only code-table administrators should have rights to modify

## Method

One of the most tedious and time consuming parts of developing many XRX applications is effective management of all of the code-tables within an XML applications. Without a strategic framework to manage codes many projects bet bogged down with the details of inconsistent code-table management.
In general our approach is to treat code-tables and their own data sets. A separate collection which is a child of the main application collection called "code-tables" is used to manage code tables for that application.
Small code-tables are usually stored in XML files with one file per entity. These code table files store a list of all items for that code table including the labels, the value and the definition of that value. According to ISO/IEC 11179 guidelines all code values, like data elements, should have definitions that are approved by a data governance process.

## Motivation

You have data in a form field that you want to validate on the server. For example, you want to validate that a zip code or postal code is valid. You want to perform the validation on the server, because loading the full data set into the web browser for validation would slow down the form loading time.

## Method

Sending data to a remote server and getting the results back without reloading an entire form is a central feature of XForms. The beauty of XRX is that this can be done without writing a single line of JavaScript. We will demonstrate the technique using several components.
* We will create a server-side RESTful component that will return a simple "OK" message if the field passes the server side checks or an error message if it fails.
* We will add an action to the field that will detect if the value in that field changes. This can be done for each character the user types or when the user tabs out of the field.
* This action will trigger a submission to the server and return the result into the model. Both the input parameters to the RESTful service and the results of the service will be stored in separate instance in the model.

## Sample Code

In this example we will check to see if data entered is a valid ZIP Code (a US postal code).
Here is the sample code from the form:

### Input Field

In the following code we add an XForms action to the input. The event we trigger on is the DOMFocusOut which is triggered when the users tab out of the field. We perform two actions.
* We put the value in the outgoing instance using the xf:setvalue function.
* We trigger the RESTful web service.

#### Sample Code Fragement for Input Field and Action
### Submission Element

Here is the additional submission element that is added to the XForms model. The method is HTTP GET which adds all of the parameters in our outgoing "zip-check" instance to the end of the URL. The action is the name of the XQuery script. In this case I use a relative path that is common if the XQuery check is in the same collection as the XQuery script that generates the XForms application.

### Instances for Outgoing Value and Incoming Results

This will cause the results of the Query to be URL paramters.
zip-check.xq?zip-code=55426

### Sample Data File
## Full XForms Example
## Discussion

This technique can be employed even if the data sets are small or the validation checks simple. The form designer must consider the trade-off between storing a validation rule in the form and the overhead of going to and from a service. There are several variations of this pattern. One variation is using the "suggest" pattern to suggest one of several values as the user enters data. In this cast each character that changes may trigger a new list of possible values.

## Motivation

We want to provide a consistent way for users to navigate around in applications and their functions. To do this we provide a standard site navigation breadcrumb view.

## Method

Each site style module has a breadcrumbs function. This function looks at the context of the application in the site and conditionally displays each level of the site as a path of links.
To support this function we will need to create a function that displays the depth we are in the site. We call this the $style:web-depth-in-site variable.
Here is an example of how to calculate it:
This function counts the number of "/" characters that appear in the current uri using the function get-uri. It then does some offset calculations so that the root node of the site has a count of 1.
The $style:site-home is a path to the site home that can be renders in the context of the site. For example you might set it to:
The Application ID and Application Name should also be set in the $style:app-id $style:app-name variables.
This can be extracted from URI and the app-info.xml file.

# Section 3: Sample Applications
## Motivation

You have an XML configuration file that only one person at a time will be editing. You want to make it easy to edit the configuration file so that non-technical users without knowledge of XML or occasional users will not make any mistakes editing the file.
Note that this method may not be appropriate if multiple people might edit the same file or record simultaneously. See the record locking section for more detail on this process.

## Method

We will load the entire file into an single XForms instance, edit it, and save the entire file. This can be done with a single submission in the XForms application and a single store operation in the eXist (or similar) database. This can be done even if the configuration file is very complex, and has many sections and many repeating elements. Regardless of the complexity of the file, you only need a single function call on the server to store the file.

## Program Outline

Let's assume that the file is stored in a single eXist collection such as my-config.xml. To load this file into an XForms application, you simply put the document into an instance within the XForms model:
You can then save the file by adding a submission element to the model that will save the file back to the database once the data has changed in the client.
Note that you will need to use "post" not "put" in this example. The submit element creates a button in your form with the label "Save".

## Building the Forms Application for the Configuration File

There are many ways to "autogenerate" the XForms application that will edit the configuration file in a browser, even if your configuration file is complex and has many repeating elements.
One way is to use a transformation program that transforms an XML Schema to an XForms file. One example of this is the NIEM transform. Although there are other examples of this type of transform, most of these require you to have an XML Schema for your configuration file. If you do not have an XML Schema there are tools that can generate an XML Schema from one or more instance documents.
If you do not have an XML Schema, you can "draw" your XForms client using commercial XForms tools such as IBM Workplace Forms Designer. This drag-and-drop environment makes it easy for non-programmers to build and maintain complex forms.
If you are building a form on a budget, then another option is to use the Orbeon XForms Builder which is an XForms application that will build the form for you.

## Client Side Save

If you have a secure Intranet you can use the HTTP PUT operator to save your configuration file directly to the web file system. Sometimes you will need to be able to authenticate a user before you permit the save. This can be done with a traditional login and session management system or you can create a single script that has the correct permissions.

## Sample Save XQuery

Back: XSLTForms and eXist • Next: Dictionary Editor

## Motivation

You want a simple application that saves one XML file per form. You want multiple users to each be editing individual records without conflict.

## Design

We will put each term in a separate XML file, and the files will be numbered sequentially - 1.xml, 2.xml, and so on. Each file defines a single term, its acronym, and its definition.

## Method

* Create a new eXist collection (aka Folder if you are using a WebDAV tool) called "dictionary"
* Create three collections called "data", "edit", and "views" within the "dictionary" collection.

### data/2.xml

Your XForms application loads the data into an instance:
You pass the ID number to an XQuery "edit.xq" as a parameter in the URI, "id". "edit.xq" uses the ID parameter as a variable, "$id", to build the form.

### Contents of edit/edit.xq

calling format: edit.xq?id=1

### Contents of edit/next-id.xml
## Contents of views/list-terms.xq

As you save more and more terms, you will want to create a list of them. You can create an XQuery that list all terms. For each term you can include a link to view and edit each term.

## edit.xq Header

The edit.xq takes parameters from the URI (i.e. in the form "edit.xq?id=2") and either puts a new element in the instance or it puts an existing element in the instance.

## xforms.css

The following file can be linked into the form for formatting. [And which file might that be?]
Back: Configuration File Editor • Next: Regular Expression Builder

## Motivation

You want to build a form that will allow you to quickly test replacement regular expressions using XQuery's replace function.

## Method

We will use an XForms client that has several controls:
* a test input string
* a regular expression to evaluate
* a new string to be used in the replace
* a "submit" trigger (button)
When the submit trigger is pressed, the three strings are sent to the server and the XQuery replace function will be executed. The result is an output text area that is returned from the server to the web browser.
This tool will allow you to do things such as test your URL-rewrite rules.

## Link to Working Application

Replace Test

## XQuery Replace Tester

If you are using eXist, just place this file on the server in the same folder as your XForms test driver.
In the example above I used a test folder on the localhost:
http://localhost:8080/exist/rest/db/test/replace/replace.xq

## Discussion

This shows that you can quickly build tools to teach yourself complex functions like regular expression handling. You can also use the XQuery match function, which returns true or false if the regular expression matches an input string.
There are two variations of this example that are interesting. The first is where you replace the input form with a large text area for doing global replacements of large blocks of text. The second is where you replace the input box with a selection list with common replacement patterns.

## References

Examples of replacement functions can be found here:
w3c replace examples
Back: Dictionary Editor • Next: Autoincrement File ID

## Motivation

You want to create a new file and automatically create a new identifier for the file.

## Method

Create an XML file with a single counter in it. Use this counter as part of the file name. After you confirm that the file has been saved, increment the counter using the update function.

### Sample XML File to Hold Next ID
## Sample Code for save-new.xq

The following example works with an incoming HTTP POST request.

## Taking into account concurrent access

Same as above but with locking the node holding the identifier.
The following example works with an incoming HTTP POST request.

## Adding and Incrementing an Attribute

Note that the syntax for inserting an attribute is the following:
The keyword attribute must be used and be followed with the attribute name and value.
If you want to store a new id in an attribute the syntax is:
Note: if the attribute already exists in the target node then insert works as replace
And if you are updating the id you can use the replace function with the @ in the path expression:
Back: Regular Expression Builder • Next: Move a Resource

## Motivation

You want to create an XForms front end to an XQuery script that will move a resource from one collection to another collection or you want to move a collection from one location to another location.

## Method

We will build a simple XForms front end to the xmldb:move operator. The syntax of the move operators is the following:
xmldb:move($from-collection, $to-collection, $resource)
Where:
If you are going to move a complete collection the format is:
xmldb:move($old-collection, $new-collection)
On this case the operation:
would result in the bar collection being located inside the foo collection:
To test this application create two test collections in your eXist database such as:

## Sample XForms Client

Create the following xhtml file:

## Sample XQuery on Server

The following XQuery named "move.xq" should be placed in the same collection as the move.xhtml file.

## Discussion

Now that you have the core move code done, you can enhance the program to browse to a specific collection for the source and browse to a specific collection for the destination. You can also create a listing of the resources in the source and destination folders.
Back: Autoincrement File ID • Next: Save File Dialog

## Motivation

You want to allow the user to save form data into a named file in an eXist collection that will not conflict with existing files.

## Method

When the user selects a Save button we will use switch/case to open up a save dialogue. In this dialogue we will list all of the current files in a collection and allow the user to create a new file with a name that does not conflict with any existing file names. If the user selects a file from the list, we will replace the current file name with that file name.

## Using the get-child-resources Function

eXist provides a function that lists the files in a collection. You can get a sorted list of all the files in a collection with the following XQuery
When executed, this XQuery will return the files in a collection. For example here is the URL of an XQuery execution with the collection parameter passed as an argument:
list-files-in-collection.xq?collection=/db/rss
We can then use this XML listing to display a list of existing files and allow the user to select a name that is not on this list.

## Discussion

Back: Move a Resource • Next: Login and Session Management

## Motivation

You want to use an XForms application to get login information and set server session variables.

## Method

The XForms standard has a "secret" attribute for collecting a password. After the user fills out the login form, it is POSTed to the server.
Note that you should not use HTTP GET for passwords since the passwords will appear in the web log files as a URL parameter.
The eXist system has several functions for setting session variables. After a user logs in these session variables should be set and all subsequent XQueries can use these session variables when accessing secure resources.
Note that setting session variables is out-of-scope of the W3C XQuery 1.0 standard and each server may use slight variations of these functions. But the concepts should be very similar.
Most commonly, a session variable is used to associate the user to one or more roles. This is known as role-based access control (RBAC). This allows your XQueries to set conditional behavior based on the user's role, and avoids having to hard-code XQueries based on usernames that may change frequently. A typical role is the "admin" role or the "document-approver" role. eXist uses a UNIX style group that can be associated with a collection or a file. You can use these groups for security if you note that a collection or file can be associated with one-and-only-one group at any time. Users are frequently associated with multiple roles during a session, just as in UNIX a user can be in many groups.

## Sample XForms Login Screen

A sample login XForms application is provided here:
XForms Login Screen
This form may be customized to put in any legal disclaimers about the use of unauthorized systems. It can then be wrapped in an XQuery function such as local:display-login and invoked if the user is accessing a page that they do not have authorization to access.

## XQuery Function to display session information

Once the user is logged in, the following function can be used to display session information in the upper-right corder of the screen.
Back: Save File Dialog • Next: File Locking

## Motivation

You want to put systems in place to avoid the problem of concurrent users writing over each other changes.
Consider the following scenario. Bob loads the data to a configuration file into his client XForms application, makes half of his changes and then goes out to lunch before he does a save back to the server. During lunch Alice opens the same data in her XForms client, makes some changes, and does a save. When Bob gets back from lunch he does a save on the same data and wipes out all of Alice's updates.
This is known as the "Lost Update Problem" and is common when you have many users that may be concurrently editing the same data.

## Two Strategies for Managing Client Locks

There are many strategies to solve this problem, and each of them have some design limitations.
In general you will find two separate locking strategies which can be used together or independently:
The first strategy is to do checksums on the data when you move the data to the client. When you save, you recalculate the checksum on the data and make sure it has not changed. You can also put the last modified timestamp in the client and warn the user if the file has changed since they started editing it. The etag element within the HTML header is frequently used to hold an md5 checksum of the data.
The second strategy is to set some state on the server when a resource is edited and provide reasonable timeouts if the user does not do a save. This method is always more complex because you must deal with unlocking resources and this often involves tools and reports to view locked files.
The strategy presented here is to place a lock on the file when an Edit form is used and unlock the file when a save is performed.
eXist provides some simple functions to lock a file. This lock can be used to prevent the second user from opening up an edit session. The drawback to this approach is that if a file is locked and the user does not do a save, then a tool must be created to permit records to be manually unlocked.

## eXist Locking Functions

Here are some of the locking functions you can use on eXist:

## References

* Locking Grain Design Article from XML.com
* W3C Article on Concurrent Editing
* Java Class for Locking used in eXist
Back: Login and Session Management • Next: Selection List Generator

## Motivation

You want to store all your code tables in a central location and have each form dynamically generate selection lists from these code tables.

## Method

We will create a very simple XML file format to store all our codes. We will store one code table per file and then write a simple XQuery that goes through all these files to build a sample selection list. This selection list will create an instance in the model to hold each selection list value. It will also populate the instance with the first value in the list.
In our sample, we will assume an XRX file naming standard such as /db/apps/app-name/code-tables/my-code-table.xml where each application contains its own code tables for maximum application portability between systems. Applications that share code tables can store these in a location such as /db/shared/code-tables/my-code-table.xml

## Sample XQuery

This query goes through all the files in the XRX application code-tables collection and looks for XML files that have code-table as the root element. It then creates a report that contains all the selection lists inside a working XForms application.
Note that this XQuery uses element constructors to create element names in the instance. It also uses the *:name notation to put data from the null namespace directly into the XForms namespace.
This file also puts the definition of the element directly into the hits of the XForms application. Under some XForms applications such as Firefox the hint appears in a floating ephemeral mode display in the left margin of the form.

## Sample CSS File

Here is the block-form.css file that can be used to make each selection appear on a separate line:
Back: File Locking • Next: Glossary Term Editor

## Motivation

You want a tool to manage your organization-specific business terms including definitions, acronyms, synonyms, broader/narrower terms, see-also terms, definition sources, approval history, versions, and traceability and mappings to ISO/IEC 11179 data elements.

## Method

Create a tool that manages individual business terms using a vocabulary similar to the W3C Simple Knowledge Organization SKOS draft standard. Use one XML file in an eXist collection for each term and have the server assign an ID number as each term is created. Allow each term to belong to one synonym set. We will associate each term with broader terms and use XQuery reports to infer narrower terms.

## Design Steps

To build the glossary we can create an XML Schema for each term and generate an XForms application to manage the Term data. We can then hand-edit the generated form to add specific functionality.

## XForms Application

This is an XQuery that when run with a parameters of new=true or an id=123 will generate an XForms application. It will need to be in the same folder as a new-instance.xml and it will need a save.xq and an update.xq to do the work of saving new instances (with the ids assigned) and updating existing instances, respectively. The update.xq will be responsible for versioning and archiving old values. The update script can also be responsible for creating log files of who changed what files and when.
Note: I have not fixed this yet to use the new pathnames for the Approval and DataElement containers.

## Search Application

Back: Selection List Generator • Next: FAQ Manager

## Motivation

You want a simple tool to manage frequently asked questions for your web site. You want a user-friendly form to allow each user to enter the questions and answers, and to categorize each FAQ into one or more categories.

## Source Code

Link to FAQ Application
Back: Glossary Term Editor • Next: Detecting Duplicates

## Motivation

You want to detect duplicate terms as the user types within a field of a form.

## Method

We will create a form that sends a request to the server each time a letter is typed into a field. The form will call a ReST web service and pass the current term as a parameter.

## Sample XQuery

The following query can be used on the server to detect duplicates.
This query takes a single parameter and returns a true or false element.
$BASENAME/xqueries/term-exists.xq?term-name=Product
If the term exists in the database it will return the following:

## XForms Application

Now we have a simple XForms that calls a web service and returns a true/false record. Our next step is to make this test occur in the background as the user types and display a warning message as a duplicate has been detected.

## Adding Character-by-Character Testing

Now we have two tasks. We need to fire off the event to the server as the user types and we need to bring the information back without interrupting the user.
First we want to add an event to the input field that sends a message each time a character is typed into the input field:
Back: FAQ Manager • Next: Data Element Editor

## Motivation

The core of an ISO metadata data registry is a collection of data elements. These data elements represent the semantics or meaning of a data element within a standard or an organization. Data elements do not necessarily map to a representation of data in a specific data store such as an RDBMS, an Excel spreadsheet, an XML file or a CSV file. Data elements can store mappings to these representations via data maps.
There are two types of data elements in an ISO metadata registry:
Conceptual Data Elements - similar to RDBMS tables, concepts in a taxonomy tree, or object classes without the behavior. Conceptual data elements are really collections for grouping similar properties.
Properties - are similar to a column of a table, a leaf element in a taxonomy, or an simple instance variable in an object class.
As with objects, properties can exhibit inheritance properties. So if a superclass has a property, that property is valid for all subclasses.

## Implementation

Our ISO registry example will have an XForms application for storing both conceptual data elements and properties. Both of these will be called generic data elements and they both share many attributes such as who created them, their definitions, and their mappings. The only difference is that a conceptual data element has no property or data type assignment (representation term).
Each data elements will be stored in a separate XML file in a data element collection. This allows multiple users to independently edit data elements and lock each data elements to avoid lost updates.
Back: Detecting Duplicates • Next: Selection List Management

## Motivation

You want every selection list in your form to be customized to the context of the situation. Selection lists need to be dynamically generated by a series of context aware services on the web server.

## Method

XForms are powerful because they can load all the codes in a form from a single instance in the model.
This for instance, if you would like to customize what selection lists are displayed to a user based on their role or other property in their session, such as what department or group they are associated with.

## Method

This can be done by using session variables stored on the server. You can alternatively store the user in a cookie on the client and then use this information to look up the correct information.
Assume you have an XML file that associates a user with their roles:
These roles can be in a session variable (see session) or you can have a function that looks up the role from the LoginID.
When the forms load, a script can be executed that loads all the code tables into an instance in the model:
Back: Data Element Editor • Next: Customizing Selection Lists

## Motivation

Many times a form or application can use the context of a situation to customize the functionality of the form based on the context of the situation. Context can include the user, group, organization structure, department, time of day, or any other parameter.
Back: Selection List Management • Next: Table Sorting

## Motivation

You have a table of data and you want to change how the results are sorted by clicking on the column.

## Method

We will add a sort parameter to a simple XQuery.

## Sample Data

We will use a sample table of flowers.
http://extjs.com/deploy/dev/examples/grid/plants.xml
Back: Customizing Selection Lists • Next: NIEM Services

## Motivation

You want to create a set of web services based on the National Information Exchange Model.

## Process

We will import the core NIEM data as an XML Schema.
To do this first download the NIEM data model from the NIEM.gov web site. Inside the zip file you will find a niem-core directory with a niem-core.xsd file. Add this to your database and run the following XQuery on it:

## Sample Code

This will return a list of all the NIEM complex types.
This XQuery can in turn be used as a web service to populate an XForms suggestion list similar to the Suggestion example in the XForms cookbook.
Back: Table Sorting • Next: Product Ratings

## Motivation

You want a method for creating a rating system for items, such as a five-star rating for a product or service.

## Method

Each registered user in a system can rate items. A separate collection associates users with ratings. Ratings can be placed anywhere in a form and can associate a user to an item and that association has a numeric value of 1 to 5. Items can then display their average user rating.

## References

Sample Drupal Five Star rating system created with JQuery
Back: NIEM Services • Next: Business Rules Template

## Motivation

You want to create a simple "rules editor" that allows non-programmers to maintain simple business rules for an application.

## Method

Business rules are expressed as a set of conditional statements. Each conditional statement has two parts: a condition and an action. For example, the following is a simple business rule that can check the validity of a date:
The if portion of the rule tests to see if the transaction date is larger than the current date. If it is, then the date is not in the past. The submission of the form data is rejected, and a useful error message is returned to the user.
One of the best examples of a simple rule editor is an email rules editor. This is usually set up as a template such as the following:
To be done...
Back: Product Ratings • Next: Metadata Shopper

## Motivation

You want to allow non-programmers (Business Analysts, Project Managers, Business Units, Subject Matter Experts etc.) to be able to create a precise list of data elements from a metadata registry. This tool has a search function that allows these users to find data elements and then add them to a list that can be saved for future use. This list (called a wantlist) can then be used to generate sub-schemas that are imported into XML exchange documents.
Metadata shoppers are one of the key tools that allow non-programmers to create precise data exchange specifications. Anyone with a few hours of training can now create precise lists of data elements that will be semantically consistent with other data exchanges. In general, shopping carts help the users find the "leaves" on the trees of a data exchange. The exact order of these elements, what elements are required, the nesting structure, and the number of elements in an exchange are not usually considered part of the metadata shopping process. These are considered the "constraints" of the data exchange, not the semantics of the data exchange. The semantics are driven by the wantlist and the constraints are usually incorporated into an XML Schema of the exchange.
This pattern of separating the semantics of a data exchange from the constraints of the exchange is known as Separation of Concerns and is one of the principal forces that allow non-programmers to have increased participation in the creation of data exchanges processes.

## Method

We will create a XForms application that has two "submission" elements. One that gets search results and another that saves a wantlist. When a user sees a search result that they want to keep, it is added to the wantlist. At the end of the session the user typically saves their wantlist in a wantlist registry.
The wantlist created by this program is designed to be used by the subschema generator discussed later in this book.

## Screen Images

Here is a sample screen image of a shopping cart before you begin searching for data elements:
Here is the result of putting a search term such as "last name" in the search field and getting a single hit. After you get this hit you can click the add button and watch the results get added to the wantlist on the right hand side.
Here is a sample screen image showing the shopping cart after several metadata elements have been added to it.

## Data Element Search Results

The metadata shopper depends on a data element search service that will return a list of data elements that match a query.
For example, if the URL of the data element query was the following:
BASENAME/search/search.xq?q=birth
The format of the result set would be the following:
After a search submission is sent to the server, the search result comes back and automatically populates the search results instance in the form. This is done without reloading the form.

## Program Source

The following XQuery dynamically generates an XForms application. We use XQuery to generate the form because we will frequently want to parameterize it with a default wantlist.

## Discussion

You may also want to copy more than a single element into the shopping cart, such as a book title and the price of the book. To do this you can use the new "origin" attribute of the XForms insert to copy not just a single element but an entire complex node into the shopping cart.
Back: Business Rules Template • Next: Subset Generator

## Motivation

You have multiple XML documents and you want the semantics and business rules for all the shared data elements to be driven from a single model.

## Method

We will use two types of XML Schemas. A semantic schema or subset schema is a sequence of all of the elements of a document exchange including the meaning of the enumerated values of the elements. A constraint schema or exchange schema will import the semantic schema and include the document constraints such the order, grouping and what cardinality each of the elements in the document.
We will leverage many of the concepts of ISO/IEC 11179 metadata registry. We will use a single XQuery that takes in a wantlist and generates a semantic subschema from this registry. This assures that all leaf-level elements in a family of XML Schemas have consistent datatypes and precise semantic definitions that all refer back to the metadata registry. This automatic generation of structures from a central data model is known as model-driven design.

## Background on Subset Generation

Subset generation techniques were first developed by the Georgia Institute of Technology in support of the GJXDM and NIEMstandards. The tools took the form of a web site that allowed a user to shop for data elements in the registry and keep a list of those data elements in a file called a wantlist. This wantlist was then used to generate a subset of the GJXDM system that is guaranteed to be consistent with the GJXDM. These tools were carried forward for use in the National Information Exchange Model as well as the Minnesota Department of Revenue subschema generators.

## Method

A subset generator is part two of a three part process.
* Step one: Use a metadata shopping cart to shop for data elements in your registry and to create a wantlist. A shopping cart tool with an integrated search function allows non-programmers to take an active role in schema creation.
* Step two: is to generate a Subset Schema that conforms to the Liskov Substitution Principle using the wantlist generated in part one as the input.
* Step three: Import that subset XML Schema into a Constraint Schema. This can be done my referencing the REST parameters to the wantlist directly in the import or it can be done by saving the subset into a discrete file.

## Wantlist

A Wantlist is a simple enumeration of all the data elements you will place at leaf-elements in your XML Schema. Wantlists do not contain any cardinality (number for repetitions) or complex branch structures. They are much like the grocery list you take shopping in which the quantities of items are not specified.
GTRI Wantlist XML Schema

## Sample Wantlist

The following is a sample wantlist generated from the US NIEM metadata shopping cart tool. Not only is the three-part property specified (ObjectClass, Property, Representation Term) but the isReference indicators are also available.
This wantlist can be saved from the web-shopping-cart tool to your local file system and then reloaded at a future date. In our example, any wantlist can be saved on the eXist server and passed as a parameter to a subset generator. This allows developers to reuse and version wantlists in addition to other XML Schema components.

## XQuery Based Subschema Generator

This XQuery takes as a single argument a wantlist file name stored in a wantlist collection. It iterates through each element in the wantlist and generates the appropriate XML Schema types.
The format of the URL for the Query is:
[WEBSERVER]/db/wantlists/subset.xq?wantlist=WANTLISTNAME
In this case the .xml file extension can be omitted.

## Using an XML Schema to validate your XForms

Some XForms systems allow you to use an XML Schema to validate your form. For example, with Orbeon forms you can do the following:
Back: Metadata Shopper • Next: XForms Generator

## Motivation

You have an XML Schema and you want to automatically generate an XForms application directly from the XML Schema.

## Method

We will write an XQuery that will take the URL of an XML Schema as an input and will generate the XForms edit form as an output.
Note: Some of the functions in this example depend on use of ISO/IEC element naming conventions to "guess" the correct control to place on the XForms application. As an alternative you can add tags to the annotations of the XML Schema to always generate the correct XForms controls from an XML Schema. The downside to this option is that you will be forced to use a text editor rather then a graphical editor for your XML Schemas.

## Steps

Here are the steps used to generate the XForms application
* Parse the XML Schema file looking for a document root
* Start to generate xf:groups for each complex element in the XML Schema
* For each simpleType, guess at the appropriate XForms control to use. Use hints from the XML data type or the element name to guess the correct control type. Leverage ISO/IEC 11179 metadata registry naming conventions and Representation terms whenever possible. Use xf:input for simple text fields, but use xf:select1 for enumerated values. For example, use the textarea control if the suffix of the element name is text, description or note.
* Generate any business rules in the bindings section of the XForms model. Although future XForms clients may be able to automatically infer rules from the XML Schema, today many XForms clients do not fully support XML Schemas. So, to generate a list of all the required fields, a set of binding elements must be generated. Luckily this is only a few lines of XQuery code.
* Generate an instance document for the initial values of the form
We will leverage a large collection of XQuery functions to keep our main XQuery simple. A separate module will be used to store all these functions.
The resulting XForms application can then be customized with specific behavior. Once this is done you must regenerate the XForms application if the XML Schema changes. Merging the customizations and the new XML Schema can be done using an XML merge tool.

## Sample Functions
### Looking for textarea

The following function uses the some construct of XQuery. It is very similar to a for loop, but instead of returning output for each item in a sequence, it only returns a Boolean true or false if one item in a sequence satisfies some criteria. In this case, the criteria is if the suffix of the element name ends in text, note or description, we will use a textarea.

### Adding Date Bindings

To get our XForms application to automatically put calendar pickers in the user interface we need to bind each of the elements with an XML Schema date type.
Here is a sample bindings for date type:
The XQuery to generate these from all the elements in an XML Schema is very simple if you use the appropriate naming conventions and end each element with the suffix "Date". The query to generate all the date bindings is just to use the XQuery function ends-with such as the following:
This will also need to be done for attributes if you store dates in attributes.

### Generating Boolean Bindings

In the same way, you can also look for all elements that end with the suffix "indicator" to turn input controls with the words "true" and "false" into checkboxes.

### Looking for required fields

You can get a list of all the non-optional elements in an XML Schema by just looking for all elements that are not complex and do not permit zero occurrences. If an element is complex, it will have a child element of complexType. Our XPath expression has to remove these by adding a predicate with a not function: xs:element[not(xs:complexType). We must then use a boolean and statement to exclude all elements that do not have a minOccurs='0' attribute.

### Sample Nesting with xs:group Element

You can use the group element to keep track of the context of the data in your form.
For example if the form instance had the following structure:
then you would generate the following xf:group element with nodeset attribute set to the correct context:
You can also style the group using a bounding box similar to the way that the HTML fieldset is styled.

## Resources

* Sample XQuery Module
* Presentation on XForms autogeneration Part 1
* Presentation on XForms autogeneration Part 2 - repeating structures

## References

* HTML to XForms in XSLT 1 A 2006 article written by John Clark on using XSLT to transform XML Schemas into XForms.
Back: Subset Generator • Next: User Manager

## Motivation

You want to be able to generate large XForms using a REST service for doing performance tests for large forms. The primary item being tested is how long does the form take to become "ready" after the form is loaded.

## Method

We will use an XQuery to create XForms files. This XQuery will take a single URL parameter that has a count of the number of elements it will generate. The XForms will have one input field and two select1 fields for each count. Each input control will have its own instance in the model.

## Autogeneration of Select1 Fields

The code tables are stored in a static XML file called "code-tables.xml". The format is as follows:

## Sample Code Tables

Many large forms use large code tables. This example uses two large code tables. One is a list of all the countries in the world and another is a list of all US State Codes.

## Motivation

You want to manage a group of users of your web site, validate their roles on the site, and track user-dependent information. This application will manage a list of users, and associate with the users the number of attempted logins, their session timeout interval, and the roles they are assigned.

## Method

Our application will use Role-Based Access Control (RBAC). We will use several functions to perform user management:
Note that to log the user out, we will change the login to the user "guest."
We will also need to add a new function that will check to see if a given user has a role.
This will return a true if the current user has a given role.

## User Data

The following is an example of a user's information. Note that we do not store the password in this file. The eXist system is used to store the user's password.
In the above example, the user jdoe has the role of ba and ba-admin which means the user is classified as a business analyst and also has the ability to administer the business analyst tools in the system.
So the following function:
will return true

## Login Form

The following is a simplified login form that will allow the user to enter a login and a password and perform an HTTP post operation. Note that this is different from the eXist standard login in that it does not place the password on the URL using an HTTP get. This information is placed in a log file can compromise the security of the system.

## Login Verification Script

The following script takes incoming login data from an HTTP POST operation and performs a login. HTTP POST data arrives from the request:get-data format in the following key-value-pair format:
user=jdoe&pass=mypass&return=/exist/rest/db/xrx/apps/test/view/view-item.xq&id=47
Note that we assume that the user-id is in the first key-value pair and the pass is in the second. If you want a more general interface you can scan for the correct key in all the incoming form key-value pairs.

## Logout Script

The following script logs you out of the system. Technically, it just logs you in as the user that has read-only access.

## Adding an Authorization Function

We will now create an XQuery module that performs an authentication check for a given user.

## Role-Based Conditional Display of Edit Functions

Many screens have links to Edit forms that allow users to change the data. You can conditionally display these Edit links by adding the following code to each page that would normally have an Edit link:

## Checking for Authenticated User

You can also add a function in any page that has sensitive information or functions by checking that the user is logged in. This can be done with a single function called auth:validate-user
Note that typically you want to make it easy to allow the user to bounce back to the screen that they were on. To do this you frequently want to add a parameter to the login.xq XQuery that will redirect the user back to where they came from.
The following is a sample function that can be placed at the top of all pages that require user authentication:
Back: XForms Generator • Next: Content Routing

## Motivation

You would like to add map navigation to your XRX application.
Although map controls were not defined within the original XForms specification, they can be added by using a bit of JavaScript.

## Method

We will use three frameworks.
* XSLTForms - that enables the model, controls and bindings
* JQuery - JQuery UI, JQuery layout - for the user interface. This includes the controls to do pans north, south, east, west
* OpenLayers - for the map navigation, pan and zoom functions
The XForms model will contain the following:
* A default instance that contains a search query with the min and max longitude and latitude (default).
* A place to store the response to the query (response).
* A locate instance (locate)
* A few binding statements
* A submission to get the new map data from the openmap database

## Sample User Interface

This example has a simple map user interface control that allows for panning to the North/South/East/West and zoom and zoom out.
This user interface uses a JQuery object that is associated with XForms input user interface controls.

## Sample Model Source

The following is stored in the XForms model:
Note that the following namespaces are used in this example:

## JavaScript Imports

The Javascript libraries will come from the openstreemap.org site. We will also use some JQuery user interface controls.
Here are the static JavaScript files you will need to add.

### Importing Static JavaScript Libraries
## Inline JavaScript Data

In addition to the above, the following JavaScript data must be used.

## XQuery

The following is a sample of the server-side XQuery code.
will be evaluated at server side for instance:

### Geo XQuery Module
## Credits

All the work was done by Evgeny Gazdovsky. The writeup was done by Dan McCreary.

# Section 4: XRX Patterns
## Motivation

You want all your XForms application to us a single save.xq submission. This makes it easier to autogenerate XForms applications and makes it easier to maintain insert and update operations in a central location.

## Method

Create a single save XQuery that inspects the content of a POST operation. Use the name of the root element or other content patterns within the submitted XML file to process the incoming saved documents. Use a table-driven rule engine to determine if the incoming XML document is a new record (and requires a new ID assigned), an update (and requires versioning), or whether other business rules apply.
Back : User Manager • Next: URL Rewriting

## Motivation

You want the URLs/URIs in your system to reflect the logical structure of a service, not the collection structure of your database.

## Method 1: Use the Jetty Rewrite Handler

Use the Jetty Rewrite Handler that can be installed with the Jetty Server. The RewriteHandler uses an XML configuration file to store the rewrite patterns of a URI. This file can contain regular expressions that allow a single rule to be used rewrite a large number of URIs.

## Method 2: Use an Atom interface

The eXist native XML database has an Atom Publishing Protocol interface. You can use this to create new URL interfaces to existing XQueries.

## Example

Suppose you use XQuery to execute a report of all terms that have changed in the last N days for project P. Using an eXist XQuery the URL might be
http://example.com/exist/rest/db/apps/glossary/views/terms-changed.xq?days=N&project=P/
The URL rewrite might be:
http://example.com/terms/new/days=N/project=P/
This makes the URL become a more stable application program interface and allows you to move the XQuery to another location in the eXist database and change parameter names without impacting your consumers, their bookmarks, or other systems that access this data through a REST interface.

## Example Using Apache Mod Rewrite

The most popular way to implement URL rewriting is to use the Apache web server as a front end to your web application. This allows you to convert "dynamic" URLs into ones that appear to be "static", where there are no question marks or ampersands in the URL string and parameters are passed as though they were folders rather than key-value pairs.
Here is the code that would be added to the Apache configuration file:

## See also

An XForms application to manage Jetty rewrite URLS.

## References

* Wikipedia Article on Rewrite Engine
* Jetty Rewrite Handler
* Tool to help you learn how to write Apache rewrite rules
* Mastering Regular Expressions, Jeffrey E.F. Friedl, Nutshell Handbook Series, O'Reilly & Associates, Inc. 1997,ISBN 1-56592-257-3
* Excellent example of how Drupal handles URL rewrites with their PATH module
Back: Content Routing