# 12. Web Application Development

Chapter Contents | Prev | Next
Keyword Search:
www.openlinksw.com
docs.openlinksw.com
Book Home
Contents
Preface
Web Application Development
The HTTP Server
Web Services ACL (Access Control List)
Virtuoso Server Pages (VSP)
VSP Markup & Basic Functions Access Request Information Errors in Page Procedures /INLINEFILE HTTP Server Pseudo-Directory Beyond Basics Long HTTP Transactions Using chunked encoding in HTTP 1.1 Making Simple Dynamic Web Pages Generation of non-HTML output Post VSP XSLT Transformation Mode XML & XSLT Generated VSP Pages
Virtuoso Server Pages for XML (VSPX)
Writing ASP.Net Web Applications
ASMX Web Service Hosting
Blogging & Weblogs
Writing PHP Applications
Writing JSP Applications
Perl Hosting
Python Hosting
Ruby Hosting

## 12.3. Virtuoso Server Pages (VSP)

The Virtuoso Server Pages subsystem is an integral part of the Virtuoso server. A VSP page is a file system or DAV resident resource that contains Virtuoso/PL code intermixed with HTML or other static content.

Figure: 12.3.1. VSP Conceptual Diagram

Virtuoso can serve Web pages to HTTP 1.0 and HTTP 1.1 clients. The HTTP document root is set by the ServerRoot parameter in the [HTTPServer] section of the Virtuoso INI file. By default this is set to vsp sub-directory of the installation. If this parameter is not set, then the default document root will be the server's working directory.

Executing VSP Pages

Directories under the ServerRoot directory, including the root itself are not automatically allowed to execute dynamic pages such as VSP. A virtual directory must first be created with an appropriate VSP user assigned to permit execution of dynamic pages. After this, Virtuoso will execute files with a ".vsp" extension as a VSP page.]

The VSP Stored Procedure

Each VSP page constitutes a Virtuoso stored procedure named after the URI of the page by taking the URI and pre-pending the WS.WS. qualifier and owner. Hence the page /test.vsp becomes the procedure "WS"."WS"."/test.vsp". This is automatically performed when a page is first requested. Subsequent requests to the page will not reference the file. The VSP engine will check for changes in the .vsp source file before calling the procedure and re-compile as required. The ws_proc_def() SQL function can be used to explicitly update the procedure if the .vsp file is changed.

The VSP Transaction

Each URL is executed in its own transaction. All SQL statements in a page procedure, whether on local or remote data, make up one transaction, unless transaction control statements are explicitly used to divide the page into multiple transactions. If the page procedure returns through completing execution or through a return statement or as a result of a 'no data found' condition, the transaction is implicitly committed. If this commit fails, the output is discarded and the error message indicating the commit failure is sent to the HTTP client. If a VSP procedure returns as a result of an error the transaction is rolled back and the output discarded. The client gets the SQL error message as the HTML body of the reply. A VSP procedure can commit or roll back explicitly with the commit work or rollback work PL statements.

If the client closes the connection to the server while server-side processing is taking place this will be detected by the server and the transaction will be eventually interrupted and rolled back in the same way as if an ODBC client had disconnected. To control the server reacting or not on the HTTP client disconnecting the SET HTTP_IGNORE_DISCONNECT = ON/OFF should be used.

Each VSP page-procedure is called with three arguments:

- path - the URI path of the VSP page itself.
- params - the parameters from a previous POST to the server.
- lines - the complete set of headers received from the calling client.

Each VSP procedure runs in a context that implicitly contains the stream to the HTTP client. The arguments of the VSP page procedure are represented as arrays of strings. For example, GETing the URL:

    http://www.test.net/x/y.vsp?arg1=1&arg2=2

would cause the following arguments to be given to the page-procedure WS.WS./x/y.vsp:

    path     ('x', 'y.vsp')
    params   ('arg1', '1', 'arg2', '2')
    lines    ('GET /x/y.vsp?arg1=1&arg2=2 HTTP/1.1', 'Host: www.test.net', ...)

Arrays are marked in parentheses with elements separated by commas. The page procedure is called as a result of either a GET or POST request in either HTTP/1.0 or HTTP/1.1. In the event of a POST request the params contains the post data.

Virtuoso can be configured to proxy certain requests to another web server. This allows using another web server for running cgi-bin's, Java servelets or other web server functions. Virtuoso, however, is capable of hosting many other dynamic engines also, such as PHP, JSP and ASP.Net.

See Also:

HTTP Server Base Configuration

Virtual Directory Administration UI

vhost_define(), vhost_remove()

Virtuoso as a Proxy

### 12.3.2. VSP Markup & Basic Functions

All VSP specific markup is represented as a processing instruction (<? ... ?>).

    <?vsp
      statement ;
      statement ;
      ...
     ?>

This markup introduces Virtuoso PL code to a VSP page, which otherwise may normally contain HTML markup. The code enclosed must begin and end at a statement boundary but a compound statement may begin in one <?vsp tag and end in another. Code outside of these blocks is ignored by Virtuoso and placed directly on the HTTP stream to be sent to the client.

See Also:

The SQL Procedure Language Guide chapter.

Several functions exist to allow VSP code to send data to the HTTP stream. They are basically the same but offer different escaping mechanisms to suit different purposes:

http (in value, varchar, in stream any);

http_value ( in value, any, in tag, varchar, in tag, varchar, in stream any);

http_url ( in value, any, in tag, varchar, in stream any);

These functions output their value argument to the specified stream with varying escaping. The value argument may be any scalar object, i.e. string, date or number and will automatically be cast to varchar before further processing.

http() will print out the contents of value cast to string without any modification.

http_value() will use HTML escapes such that '<' will be output as '&lt;'.

The http_url() function will use URL escapes such that '+' replaces spaces and hex escapes like %25 will replace '%'. If http_value() gets an XML entity returned by a path expression it outputs the serialization of the entity, including children. This is not the string value since this has the entity start and end tags and other markup. The tag argument allows specifying a tag in which the value is to be enclosed. A non-string value, e.g. 0 or null will cause no tag to be put around the value.

The stream argument may be omitted, in which case it defaults to the HTTP client of the calling procedure. If present, a value of integer 0 will mean the http client. If non-0 the value must be an object returned by string_output().

These HTTP functions are commonly combined with sprintf() which allows string composition based on a template. When using sprintf() to compose data to send to the user agent the %V and %U letters can be used to introduce escapes similar to http_value and http_url, respectively.

HTTP Functions

    http (' % <b>')          ' % <b>'
    http_value (' % <b>')    ' % &lt;b&gt;'
    http_url (' % <b>')      '+%25+<b>'
    http_value (12, 'li')    '<li>12</li>'

#### 12.3.2.1. Markup Short-hands

VSP markup short-hands exist for the http_value() and http_url() functions to perform the same task outside of a VSP code block. This can improve readability of VSP pages.

    <?= expression ?>  equiv.  http_value()

    <?/ expression ?>  equiv.  http_url()

These markups are shorthand for substituting values of expressions into the output. The <?= tag accepts a SQL expression and casts the value into a string, which is sent to the output. The <?/ markup sends the value of the expression to the client with HTTP URL escapes.

VSP Markup

Here is a very simple example of making a two column HTML table from the results of a "select" SQL statement. First using normal functions:

    <html>
    <h2>List of Users</h2>
    <table>
    <?vsp
      for (select u_name, u_password from sys_users ) do {
        http('<tr><td>');
        http (u_name);
        http('</td><td>');
        http (u_password);
        http('</td></tr>');
      }
    ?>
          </table>
    </html>

This fragment outputs a table of user names and passwords. We have chosen to not end the code block until the end of the result so we have repeatedly used the http() function to output parts of the table also.

Now the same code but including shorthands:

    <html>
    <h2>List of Users</h2>
    <table>
    <?vsp for (select u_name, u_password from sys_users ) do { ?>
      <tr>
        <td><?=u_name ?></td>
        <td><?=u_password ?></td></tr>
          <?vsp } ?>
          </table>
    </html>

### 12.3.3. Access Request Information

Request information, resulting from an HTTP POST, is available via the params vector. The params vector is always available for the purpose in a VSP context. Similarly the lines and path vectors are available for the HTTP headers and URL path respectively.

Parameters stored in the params vector are stored in keyword-value pairs, such that keywords are stored in the even elements, values in the odd numbered elements. Vectors and arrays can be accessed using the aref() and aset() functions, however, the exact position of parameters is seldom known. The get_keyword() function can be used to return the value of a given parameter. You can specify a default value to return in case the parameter you are looking for is not found.

get_keyword ('param_name', , vector, [, opt_default_value']);

If a default value other than '' (empty-string) is not required then a short-hand can be used instead.

    {?'param_name'}

is equivalent to get_keyword ('param_name', , 'params');

Since get_keyword() returns only strings, you will find that casting or conversion functions such as atoi() are very useful here.

Reading the params Vector

Consider retrieving the following page by means of the URL:

    http://myvirtuoso/test.vsp?arg1=1&arg2=test

    <html>
     <body>
      <h1>Test Params</h1>
      <?vsp
      declare _arg1 integer; --   the underscore helps to differentiate from
      declare _arg2 varchar; --   the keyword name, whereas the varliable names
      declare _arg3 varchar; --   help use remember which is which.

      _arg1 := atoi(get_keyword('arg1', params));
      _arg2 := {?'arg2'};
      _arg3 := get_keyword('arg3', params, 'was empty'};

      ?>
      <p>values returned:</p>
      <p>arg1: <?=_arg1?></p>
      <p>arg2: <?=_arg2?></p>
      <p>arg3: <?=_arg3?></p>
     </body>
    </html>

See Also:

get_keyword()

atoi()

aref()

aset()

cast

Note:

Sometimes a POST can supply a large amount of data, such as from an <INPUT type="file">. When the length of the parameter data exceeds 5,000,000 octets the result is stored as a string session in the params array. In these cases the value should not be copied or converted to a string, it is likely to be truncated. The value should be stored as a BLOB or an external file. When processing possibly large input fields in a form either the fourth parameter to get_keyword()/get_keyword_ucase() should be set to 1 or they should be accessed through aref_set_0().

### 12.3.4. Errors in Page Procedures

VSP pages can declare handlers for errors using the normal handler declaration or whenever ... goto construct. Any unhandled error causes the procedure to be terminated and the error message to be sent to the HTTP client instead of the output. Because terminating the page output at an arbitrary point would probably result in not well formed output all the output up to the point of the error is discarded.

If the SQL state signaled with the error is VSPRT the output generated up to the point where the error was signaled is sent as such to the user agent. This special SQL state is useful together with the http_rewrite function for things like sending a redirect based on a condition detected in the middle of page processing. The http_rewrite function will clear all output buffered so far and signaling VSPRT will make sure that whatever output is generated after http_rewrite goes unmodified to the user agent.

### 12.3.5. /INLINEFILE HTTP Server Pseudo-Directory

This pseudo directory provides a way for a VSP page to have full control over the data sent to the client user-agent, for example to send files to it and to handle the HTTP response attributes.

URIs starting with /INLINEFILE are handled through a VSP procedure instead of being searched for in the HTTP root directory. This special URI has the following syntax:

    /INLINEFILE/some_file_name?VSP=some_vsp&arg1=x&arg2=y.....

Upon receipt of such a URI, Virtuoso will execute the "some_vsp" VSP page with the parameters following the VSP parameter. The VSP page can adjust the HTTP response header attributes using the http_header() function to reflect the content of the HTTP body, such as specifying the encoding through "Content-Encoding" attribute, or a MIME type through "Content-Type" attribute).

Using /INLINEFILE

Here is a simple example for showing JPEG images stored in DAV. The page will list the first ten images found in the DAV resources table as hyper-links. Clicking on them will fetch the content and display using /INLINEFILE.

    <?vsp
      if ({?'getfile'} <> '')
        {
          http_header ('Content-type: image/jpg\t\n');         -- set the header to jpg
          declare image any;
          select RES_CONTENT into image from WS..SYS_DAV_RES
            where RES_ID = atoi({?'id'});                      -- download image from WebDAV
          http(image);                                         -- table and display
          return;
        }
      ?>
    <html>
     <body>
     <h1>Using /INLINEFILE to display images from the database</h1>

     <table>
      <tr>
       <td>

    <?vsp for (select top 10 RES_ID, RES_NAME from WS..SYS_DAV_RES where right(RES_NAME, 3) = 'jpg') do {?>
     <a href="?id=<?=RES_ID?>"><?=RES_NAME?></a><br>
    <?vsp } ?>

       </td>
       <td>
        <p><img src="/INLINEFILE/picture.jpg?VSP=<?/http_path()?>&getfile=yes&id=<?={?'id'}?>"></p>
        <p><a href="/INLINEFILE/picture.jpg?VSP=<?/http_path()?>&getfile=yes&id=<?/{?'id'}?>">download</a></p>
       </td>
      </tr>
     </table>
     </body>
    </html>

Note:

Note the use of the http_path() function to find the full path of the originating VSP file.

Also note the call to http_header() to set the appropriate content type for the returned data. When Virtuoso retrieves files normally, it will consult the system table WS.WS.SYS_DAV_RES_TYPES for types based on the file extension. We do not need to refer to the table in our example because we are making sure that only JPEGs are being returned.

See Also:

http_header()

http_path()

### 12.3.6. Beyond Basics

All output from VSP page procedures is buffered into a local string stream before being sent out. This is done so as to support the HTTP/1.1 required content length and to allow recovery from errors.

http_rewrite ( in stream any);

This clears any previous output to the stream. If the stream is omitted or 0 the stream is the HTTP client stream of the calling procedure.

http_file ( in path varchar);

This function sends a file to the HTTP client as a response to the current request. Any other output that may have been generated by the calling procedure will be discarded and the contents of the file will be the exclusive response to the current HTTP request together with appropriate headers. The file will only be sent after the procedure handling the current HTTP request has returned. The file name is thus not validated until the calling procedure has returned.

http_get( in uri, varchar, out headers varchar);

This function retrieves the document specified by the URI by HTTP and returns the data of the response. The header output parameter is set to be an array with an element for each line of the response's HTTP header. Each line is a varchar object in the containing array. The header parameter is optional.

The URI is of the form host[:port]<path>, e.g 'www.openlinksw.com:80/index.html'. The port, if omitted, defaults to 80. The data following the headers is not processed in any way. No content transfer encodings are decoded but an eventual content transfer encoding header can be found in the header array.

http_flush();

This function generates a response header, flushes a stream and disconnects the client, however, the server will continue with the execution of the PL code in VSP page. The final result will never be sent to the client. This is useful when a page makes a long transaction and we do not wish the client to wait until its end, which may result in a time-out. Suppose we have the retrieval of news from many targets, each a thousand messages. We start from a VSP page process, inside it we put into the internal stream (using http, http_value etc.) redirect code and call http_flush. The client can read the response and go to a status page that can display number of messages retrieved, which may need refreshing a few times.

http_proxy (in host_and_port, varchar, in header_lines, any, in post_parameters any)

The function http_proxy() is used to send request in header_lines and post_parameters to the host_and_port, read the response and send it back to the client. The http_proxy() function can be used inside a VSP page to send a request to an external web server and automatically route the reply sent by this remote server to the client of the VSP page calling http_proxy(). The output which can generated (with http functions, etc.) before and after http_proxy is called will be discarded before sending the result of link retrieval to the user-agent.

Virtuoso Proxy

    ...
    <?vsp
      http ('this never be displayed');
      http_proxy ('www.foo.com', vector ('GET / HTTP/1.0'), NULL);
      http ('and this also');
    ?>
    ...

#### 12.3.6.1. Virtuoso HTTP Server Character Set Settings

When the HTTP server returns the HTTP header to the client it appends charset=xxxx to the Content-Type: HTTP header fields. This informs the client user agent, the web browser, as to the character set of the content to be displayed correctly. It uses the Web server charset to correctly format values resulting from the http_value() function or the VSP equivalent <?= ...>. Wide values and XML entities, resulting from any XML processing functions like xpath_contains, get represented using the "HTML/XML transformation".

The default web server charset is governed by the Charset setting defined in the Virtuoso INI file. If no default charset is specified then Virtuoso will use ISO-8859-1.

The HTTP character set can be changed during an HTTP session using: set http_charset='charset_name';.

The XSLT output encoding can also be specified to over ride the server default setting.

#### 12.3.6.2. Session Management and State Variables

The Virtuoso HTTP session management consists of functions for session variables manipulation and hooks for saving and restoring session variables.

Session management must be enable by setting the flag for persistent session variables in the virtual directory mapping. Virtual directory mappings use the persistent_session_variables flag, which when specified, session variables can be used in a post-process function to determine if the session variables content must be stored on to the session table or not.

The post-processing function hook can be any user-defined Virtuoso/PL procedure, it will be executed every time after processing of the active page.

See Also:

connection_get()

connection_set()

connection_vars()

connection_vars_set()

connection_is_dirty()

### 12.3.7. Long HTTP Transactions

Long running tasks may be invoked by web clients. In such a case, the server should return a page for the user agent much before the tasks's completion in order to provide feedback and avoid timeouts. Also the long running task should not be interrupted by the user agent disconnecting. The http_flush() function will send the reply accumulated thus far to the user agent and then disconnect it. In effect, this is a generic mechanism for starting an asynchronous thread.

Starting long running tasks may lead to denial of service. To prevent this we can use status and stop functions to check processes and kill them if necessary.

We can retrieve the URL, client IP-address, and process status code for all currently running VSP requests, then use this information to isolate and eliminate a process.

http_pending_req() Lists the processes.

http_kill() can be used to kill them.

### 12.3.8. Using chunked encoding in HTTP 1.1

It is sometimes desirable to use the HTTP 1.1 chunked encoding to send data to HTTP clients. Examples of such include status pages or streaming applications. Note that the possiblity of using chunked encoding depends on external factors such as whether the client browser supports chunked encoding. So a server page can request turning on the chunked encoding, but should handle the case should it not be available.

Note that in order to successfully turn on the chunked encoding the page should not be using the http_xslt(). Also all reply headers set by the http_header() are silently ignored after the mode is set.

The http_flush() (with 1 as a value for it"s optional argument) is used to request turning on the chunked encoding. If the client"s user agent supports the encoding, then the data accumulated so far in the server"s output buffer are sent to the client as the first chunk, the request is put in special "chunked mode" and the http_flush() returns a non-zero integer. When in that mode a new chunk is sent to the client either when the internal 4k buffer is filled up or when the client calls http_flush() again to flush the buffer and send it as a chunk. The client disconnection is handled as usual.

### 12.3.9. Making Simple Dynamic Web Pages

The directory where the pages reside must be marked as executable. Use the vhost_define function or the Administration Interface to do this:

    vhost_define (lpath=>'/example_location', ppath=>'/example_location/', vsp_user=>'demo');

The usual way to make an Dynamic page is to make a HTML skeleton and insert Virtuoso/PL code in appropriate places to fill in the rest dynamically. Consider the following example as a demonstration of such technique. Note that the example is made in four steps but in practice this can be one.

Suppose we have a table Demo.demo.Shippers (from the Demo database of the standard distribution). We can make a simple page for editing it.

1. Building The HTML Skeleton

   We define one form for editing and adding entries and a table for listing the existing shippers.

       <HTML>
         <BODY>

           <!-- edit form -->
           <FORM name="ShippersForm" method="POST" action="shippers.vsp">
              <INPUT type="hidden" name="ShipperID" value="">
              <TABLE>
                <TR>
       	   <TD>Company Name</TD>
       	   <TD><input type="text" name="CompanyName" value=""><!-- CompanyName --></TD>
       	 </TR>
                <TR>
       	   <TD>Phone</TD>
           	   <TD><INPUT type="text" name="Phone" value=""><!-- Phone number --></TD>
       	 </TR>
                <TR><TD colspan="2"><input type="submit" name="accept" value="Accept"></TD></TR>
              </TABLE>
           </FORM>
           <!-- end of form -->

           <!-- list of entries -->
           <TABLE>
              <TR><TD>Company Name</TD><TD>Phone #</TD><TD colspan="2">Action</TD></TR>
              <!--TR><TD>CompanyName</TD><TD>Phone</TD><TD>Edit URI</TD><TD>Delete URI</TD></TR-->
           </TABLE>
           <!-- end of list -->
         </BODY>
       </HTML>

2. Filling a List of Entries

   We have added in part 'list of entries' one active part (for select ...). And using <?=...?> shortcut we have made for each row in database table one row in table defined in step 1. Also we have added two useful links 'Edit' and 'Delete' with URL parameter 'EDIT' and 'DELETE' whose value is equal to the primary key value of the row;

       <HTML>
         <BODY>

           <!-- edit form -->
           <FORM name="ShippersForm" method="POST" action="shippers.vsp">
              <INPUT type="hidden" name="ShipperID" value="">
              <TABLE>
                <TR>
       	   <TD>Company Name</TD>
       	   <TD><input type="text" name="CompanyName" value=""><!-- CompanyName --></TD>
       	 </TR>
                <TR>
       	   <TD>Phone</TD>
           	   <TD><INPUT type="text" name="Phone" value=""><!-- Phone number --></TD>
       	 </TR>
                <TR><TD colspan="2"><input type="submit" name="accept" value="Accept"></TD></TR>
              </TABLE>
           </FORM>
           <!-- end of form -->

           <!-- list of entries -->
           <TABLE>
              <TR><TD>Company Name</TD><TD>Phone #</TD><TD colspan="2">Action</TD></TR>
              <!--TR><TD>CompanyName</TD><TD>Phone</TD><TD>Edit URI</TD><TD>Delete URI</TD></TR-->
              <?vsp
                for select ShipperID, CompanyName, Phone from Demo.demo.Shippers do
                 {
              ?>
              <TR>
                <TD><?=CompanyName?></TD>
       	 <TD><?=Phone?></TD>
       	 <TD><a href="shippers.vsp?EDIT=<?=ShipperID?>">Edit</a></TD>
       	 <TD><a href="shippers.vsp?DELETE=<?=ShipperID?>">Delete</a></TD>
              </TR>
              <?vsp
                 }
              ?>
           </TABLE>
           <!-- end of list -->
         </BODY>
       </HTML>

3. Retrieving Parameters and Filling in The Form

   We must retrieve the parameters 'Delete' and 'Edit' from the URL and fill in the form elements

   We have added a section to the top of the page that we use to recognize what operation to perform and do the appropriate action in the database. In the case of editing we use the values input on the form.

       <?vsp
       declare company_name, phone_number varchar;
       declare shipper_id, operation integer;
       declare shipper_info
         cursor for select CompanyName, Phone
           from Demo.demo.Shippers where ShipperID = shipper_id;

       company_name := '';
       phone_number := '';
       operation := 0;

       shipper_id := atoi (get_keyword ('EDIT', params, '0'));

       if (shipper_id > 0)
         {
           whenever not found goto not_found_any;
           open shipper_info (prefetch 1);
           fetch shipper_info into company_name, phone_number;
       not_found_any:
           close shipper_info;
           goto display_page;
         }

       shipper_id := atoi (get_keyword ('DELETE', params, '0'));

       if (shipper_id > 0)
         {
           delete from Demo.demo.Shippers where ShipperID = shipper_id;
           goto display_page;
         }

       display_page:

       ?>

       <HTML>
         <BODY>

           <!-- edit form -->
           <FORM name="ShippersForm" method="POST" action="shippers.vsp">
              <INPUT type="hidden" name="ShipperID" value="<?=shipper_id?>">
              <TABLE>
                <TR>
       	   <TD>Company Name</TD>
       	   <TD><input type="text" name="CompanyName" value="<?=company_name?>"</TD>
       	 </TR>
                <TR>
       	   <TD>Phone</TD>
           	   <TD><INPUT type="text" name="Phone" value="<?=phone_number?>"</TD>
       	 </TR>
                <TR><TD colspan="2"><input type="submit" name="accept" value="Accept"></TD></TR>
              </TABLE>
           </FORM>
           <!-- end of form -->

           <!-- list of entries -->
           <TABLE>
              <TR><TD>Company Name</TD><TD>Phone #</TD><TD colspan="2">Action</TD></TR>
              <!--TR><TD>CompanyName</TD><TD>Phone</TD><TD>Edit URI</TD><TD>Delete URI</TD></TR-->
              <?vsp
                for select ShipperID, CompanyName, Phone from Demo.demo.Shippers do
                 {
              ?>
              <TR>
                <TD><?=CompanyName?></TD>
       	 <TD><?=Phone?></TD>
       	 <TD><a href="shippers.vsp?EDIT=<?=ShipperID?>">Edit</a></TD>
       	 <TD><a href="shippers.vsp?DELETE=<?=ShipperID?>">Delete</a></TD>
              </TR>
              <?vsp
                 }
              ?>
           </TABLE>
           <!-- end of list -->
         </BODY>
       </HTML>

4. Editing Form Logic

   We have a logic in the same initialization part of the page that retrieves a 'ShipperID' parameter, so if this parameter exists in the params array then the operation is to perform an insert, otherwise we must update a record.

       <?vsp
       declare company_name, phone_number varchar;
       declare shipper_id integer;
       declare shipper_info
         cursor for select CompanyName, Phone
           from Demo.demo.Shippers where ShipperID = shipper_id;

       company_name := '';
       phone_number := '';

       shipper_id := atoi (get_keyword ('EDIT', params, '0'));
       -- If the current operation is edit then we retrieve the Company Name and Phone
       if (shipper_id > 0)
         {
           whenever not found goto not_found_any;
           open shipper_info (prefetch 1);
           fetch shipper_info into company_name, phone_number;
       not_found_any:
           close shipper_info;
           goto display_page;
         }

       shipper_id := atoi (get_keyword ('DELETE', params, '0'));

       -- If the operation is delete then delete it (if any error
       -- occurred then HTTP server will handle it)
       if (shipper_id > 0)
         {
           delete from Demo.demo.Shippers where ShipperID = shipper_id;
           shipper_id := 0; -- reset it to prevent submission of wrong shipper id
           goto display_page;
         }

       -- If pressed button Accept then we can recognize the operation
       if ('' <> get_keyword ('accept', params, ''))
         {
           shipper_id := atoi (get_keyword ('ShipperID', params, '0'));
           company_name := get_keyword ('CompanyName', params, 'unknown');
           phone_number := get_keyword ('Phone', params, 'N/A');
           -- the old entry going edited
           if (shipper_id > 0)
               update Demo.demo.Shippers set CompanyName = company_name, Phone = phone_number
       	    where ShipperID = shipper_id;
           else -- this is an new entry
             {
               shipper_id := coalesce ((select max(ShipperID) from Demo.demo.Shippers), 0) + 1;
               insert into Demo.demo.Shippers (ShipperID,CompanyName,Phone)
       	    values (shipper_id,company_name,phone_number);
             }
           company_name := ''; -- we clear all entered data
           phone_number := '';
           shipper_id := 0; -- to prevent setting of wrong shipper id in form
         }

       display_page:

       ?>

       <HTML>
         <BODY>
           <H3>Editing a shipment companies</H3>
           <!-- edit form -->
           <FORM name="ShippersForm" method="POST" action="shippers.vsp">
              <INPUT type="hidden" name="ShipperID" value="<?=shipper_id?>">
              <TABLE>
                <TR>
       	   <TD>Company Name</TD>
       	   <TD><input type="text" name="CompanyName" value="<?=company_name?>"</TD>
       	 </TR>
                <TR>
       	   <TD>Phone</TD>
           	   <TD><INPUT type="text" name="Phone" value="<?=phone_number?>"</TD>
       	 </TR>
                <TR><TD colspan="2"><input type="submit" name="accept" value="Accept"></TD></TR>
              </TABLE>
           </FORM>
           <!-- end of form -->

           <!-- list of entries -->
           <TABLE>
              <TR><TD>Company Name</TD><TD>Phone #</TD><TD colspan="2">Action</TD></TR>
              <!--TR><TD>CompanyName</TD><TD>Phone</TD><TD>Edit URI</TD><TD>Delete URI</TD></TR-->
              <?vsp
                for select ShipperID, CompanyName, Phone from Demo.demo.Shippers do
                 {
              ?>
              <TR>
                <TD><?=CompanyName?></TD>
       	 <TD><?=Phone?></TD>
       	 <TD><a href="shippers.vsp?EDIT=<?=ShipperID?>">Edit</a></TD>
       	 <TD><a href="shippers.vsp?DELETE=<?=ShipperID?>">Delete</a></TD>
              </TR>
              <?vsp
                 }
              ?>
           </TABLE>
           <!-- end of list -->
         </BODY>
       </HTML>

5. Final Remarks

   The page for shippers does not have any specific error-handling. If there are any SQL errors produced the HTTP server will display the error number and the server error message. For example, if we trying to delete an record of a predefined shippers we would have a foreign key violation to which the server would respond:

       'SQL Error S1000 DELETE statement conflicted with
         COLUMN REFERENCE constraint "Orders_Shippers_ShipVia_ShipperID"'

   We can, however, add PL code to handle errors and display a different page.

### 12.3.10. Generation of non-HTML output

VSP pages are not restricted to generating only HTML markup. In order to generate non-HTML markup the VSP page MUST conform to the target format specification, for example if XML output is needed, the markup MUST follow XML syntax rules. The output sent to the user agent is entirely controlled by the scripting on the page, no constant headers beyond the required HTTP ones are added by the serber.

Also it is important when output is not HTML that the HTTP header field 'Content-Type' be set to appropriate MIME type (for example 'text/xml', 'text/plain' etc) using http_header().

XML generation

The following example shows how an XML document can be generated using a VSP page

    	    <?vsp
    	        -- source of the xmldemo.vsp
    	        declare txt varchar;
    		http_header ('Content-Type: text/xml\r\n');
    		txt := 'this is a XML test';
       	    ?><?xml version="1.0" ?>
    	    <document>
    		<para><?= txt ?></para>
    	    </document>

WML generation

The following example shows how a WML page can be generated using a VSP page

    	    <?vsp
    	    	-- source of the wmldemo.vsp
    	        declare txt varchar;
    	    	http_header ('Content-type: text/vnd.wap.wml\r\n');
    		txt := 'this is a WML test';
    	    ?><?xml version="1.0" ?>
    	    <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/wml_1.1.xml">
    	    <wml>
    		<card>
    		    <p><?= txt ?></p>
    		</card>
    	    </wml>

See Also:

WML Tutorials

### 12.3.11. Post VSP XSLT Transformation Mode

The Virtuoso server can perform server-side XSLT transformations on the internal stream data. Suppose we have an XML document, we can tell the HTTP server to invoke XSLT processor before sending the reply to the user agent. We do this by making a call to the http_xslt() function inside VSP or any procedure called from it and pass the URL of the stylesheet and probably some parameters.

http_xslt(in style_sheet_URI, varchar [, in parameters any])

The VSP page will produce an XML document, rather than HTML. The XSL stylesheet will then produce the required output for the user-agent, which could be more XML or HTML.

The XSL stylesheet could also be generated using VSP.

In Server Transformation of XML

    <?vsp
    declare ses any;
    ses := string_output ();
    xml_auto ('select ShipperID, CompanyName, Phone from Demo.demo.Shippers
      for xml auto element', '', ses);

    http ('<list>');
    http (string_output_string (ses));
    http ('</list>');
    http_xslt ('file:/samples/xslt/shippers.xsl');
    ?>

Where shippers.xsl will have the following content:

    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html"/>
    <xsl:template match="/">
    <html>
    <head>
    <title>Shippers list</title>
    </head>
    <body link="#0000b4" vlink="#0000b4" bgcolor="#ffffff">
    <xsl:apply-templates/>
    </body>
    </html>
    </xsl:template>
    <xsl:template match="list">
    <table>
    <tr><td>ID</td><td>Name</td><td>Phone</td></tr>
    <xsl:apply-templates/>
    </table>
    </xsl:template>
    <xsl:template match="Shippers">
    <tr>
    <td><xsl:value-of select="ShipperID"/></td>
    <td><xsl:value-of select="CompanyName"/></td>
    <td><xsl:value-of select="Phone"/></td>
    </tr>
    </xsl:template>
    </xsl:stylesheet>

### 12.3.12. XML & XSLT Generated VSP Pages

The Virtuoso HTTP server provides a special case for producing VSP pages. For this purpose the extensions .vxml and .vxsl are reserved. If the requested document is named dummy.vxml then the HTTP server will try to locate dummy.vxsl. If the dummy.vxsl exists then it will perform an XSLT transformation using .vxml as a target XML document and .vxsl as a XSLT stylesheet. After successful transformation it will compile a result from it in the usual way and then perform execute.

The requirements are: XML document with extension .vxml, XSLT sheet with the same name, location but extension .vxsl. The location of these files must be set to allow execution (see Virtual Directories Support and Execution Privileges).

Executable (V)XSL

Source of portfolio.vxml

    <?xml version="1.0"?>
    <?xml-stylesheet type="text/xsl" href="portfolio.xsl"?>
    <portfolio xmlns:dt="urn:schemas-microsoft-com:datatypes" xml:space="preserve">
    <stock exchange="nyse">
    <name>zacx corp</name>
    <symbol>ZCXM</symbol>
    <price dt:dt="number">28.875</price>
    </stock>
    <stock exchange="nasdaq">
    <name>zaffymat inc</name>
    <symbol>ZFFX</symbol>
    <price dt:dt="number">92.250</price>
    </stock>
    <stock exchange="nasdaq">
    <name>zysmergy inc</name>
    <symbol>ZYSZ</symbol>
    <price dt:dt="number">20.313</price>
    </stock>
    </portfolio>

Source of portfolio.vxsl

    <?xml version='1.0'?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
    <xsl:template match="/">
    <HTML>
    <BODY>
    <TABLE BORDER="2">
    <TR>
    <TD>Symbol</TD>
    <TD>Name</TD>
    <TD>Price</TD>
    </TR>
    <xsl:for-each select="portfolio/stock">
    <TR>
    <TD><xsl:value-of select="symbol"/></TD>
    <TD><xsl:value-of select="name"/></TD>
    <TD><xsl:value-of select="price"/></TD>
    </TR>
    </xsl:for-each>
    </TABLE>
    </BODY>
    </HTML>
    </xsl:template>
    </xsl:stylesheet>

The result of retrieving portfolio.vxml

    <HTML>
    <BODY>
    <TABLE BORDER="2">
    <TR><TD>Symbol</TD><TD>Name</TD><TD>Price</TD></TR>
    <TR><TD>ZCXM</TD><TD>zacx corp</TD><TD>28.875</TD></TR>
    <TR><TD>ZFFX</TD><TD>zaffymat inc</TD><TD>92.250</TD></TR>
    <TR><TD>ZYSZ</TD><TD>zysmergy inc</TD><TD>20.313</TD></TR>
    </TABLE>
    </BODY>
    </HTML>

Previous Web Services ACL (Access Control List) | Chapter Contents | Next Virtuoso Server Pages for XML (VSPX)