Web Scripts (restructuring sandbox 3)

From alfrescowiki

Jump to: navigation, search

<start -------------------------------------------------->

Contents

Description document

(from 3.1) The content of a Web Script Description document is defined as follows (Note: this demonstrates all possible settings):

<webscript>
  <shortname>Blog Search</shortname>
  <description>Find all blog entries whose content contains the specified search term</description>
  <url>/sample/blog/search?q={searchTerm}</url>
  <url>/sample/blog/search.atom?q={searchTerm}</url>
  <url>/sample/b/s?q={searchTerm}</url>
  <url>/sample/b/s.atom?q={searchTerm}</url>
  <format default="html">extension</format>
  <authentication>guest</authentication>
  <transaction>required</transaction>
</webscript>

Where:

  • shortname is a human readable name for the Web Script
  • description (optional) is documentation for the Web Script
  • url (one or more) is a URL Template to which the Web Script is bound; variants of the url template which specify a format do not need to be registered, however, they are useful for documentation purposes
  • format (optional) is how the required response content-type is declared on the url; valid values (optional) are:
    • argument specifies the required content-type is declared via the format url argument e.g. /search?q=tutorial&format=atom
    • extension specifies the required content-type is declared via the url extension e.g. /search.atom?q=tutorial
    • any specifies either of the above is supported
    • Note: if not specified, the default value is any
    • Note: if the URL does not specify a required content-type at all, the default content-type is taken from the (optional) default attribute of the format element. By default, if not set, the 'html' format is assumed. In some cases, a URL may decide upon a response content-type at runtime. For these URLs, specify an empty format e.g. format=""
  • authentication (optional) is the required level of authentication; valid values are:
    • none specifies that no authentication is required at all
    • guest specifies that at least guest authentication is required
    • user specifies that at least named user authentication is required
    • admin specifies that at least a named admin authentication is required
    • Note: if not specified, the default value is none
  • transaction (optional) is the required level transaction; valid values are:
    • none specifies that no transaction is required at all
    • required specifies that a transaction is required (and will inherit an existing transaction, if open)
    • requiresnew specifies that a new transaction is required
    • Note: if not specified, the default value is none if authentication is also none, otherwise the value is requires

The description provides Alfresco with all the necessary information to bind the Web Script to one or more URLs. It also provides enough to document the Web Script.

</start -------------------------------------------------->

<start ------------------------------------------------------>

(3.1.1) URL Templates

A URL template is simply a URL containing tokens which may be substituted with actual values. The URL template syntax is minimal and simple. Common forms of URL template include:

/content/a/b/c/d.txt
/blog/search?q={searchTerm}
/blog/search?q={searchTerm}&amp;n={numResults}
/blog/category/{category}?n={itemsperpage?}
/user/{userid}

A token of the form {<name>?} means it is optional. Typically, tokens are used for URL arguments, but may also be used for path segments.

Note the third example passes two parameters to the Web Script. Normally an ampersand (&) is used to separate parameters, though in your template one must use the escaped literal "&amp;" instead.

For now, Web Scripts do not enforce mandatory arguments. However, it's still useful to provide a full URL template for documentation purposes.

URL templates are specified relative to http://<host>:<port>/alfresco/service.

Which part of the URL is used for binding?

When a URL request is made, Alfresco locates the appropriate Web Script by finding the closest match to a URL template in a Web Script Description document. The part of the URL template that's used for matching is the static part. This is from the start of the URL template up to either the URL arguments or the first path token, whichever comes first. For example, the above URL templates are matched on:

/content/a/b/c/d.txt (exact match)
/blog/search (starts with match)
/blog/category (starts with match)
/user/ (starts with match)

The following URLs match one of the above:

/content/a/b/c/d.txt
/blog/search
/blog/search?q=tutorial
/blog/category
/blog/category/web20
/user/fred

however, the following do not:

/content/a/b/c/d.txt.plain
/blog
/usr/fred

</start ------------------------------------------------------------>

<start ------------------------------------------------------------>

Alfresco JavaScript API

(from 3.2)

The full Alfresco JavaScript API is available within Web Scripts. However, there are some differences with regards to available root objects.

  • document (not available)
  • space (not available)
  • script (not available - TODO: fix this: should be available if script held in repo)
  • companyhome (only available if authenticated)
  • person (only available if authenticated)
  • userhome (only available if authenticated)


Web Scripts also have access to the following additional root objects:

argsM
an associative array of any URL parameters (where each key is a parameter name and each value is an array containing the parameter values, even if only one is supplied) - complements the root object args. See example. [sorry, available 2.1 Enterprise onwards].
url
provides access to the URL (or parts of the URL) that triggered the Web Script.
formdata
provides access to multipart/form-data requests allowing the upload of files via Web Scripts. [sorry, available 2.1 Enterprise onwards].
model
An empty associative array which may be populated by the JavaScript. Values placed into this array are available as root objects in Web Script "response" templates.
roothome
The Repository root node.
guest
A boolean indicating whether the Web Script is executing as "Guest".
server
An associative array of meta-data properties describing the Repository server hosting the Web Script.

</start ------------------------------------------------------------>

<start ------------------------------------------------------------>

Alfresco Template API

(from 3.3)

The full Alfresco Template API is available within Web Scripts. However, there are some differences with regards to available root objects.

  • document (not available)
  • space (not available)
  • template (not available - TODO: fix this: should be available if template held in repo)
  • companyhome (only available if authenticated)
  • person (only available if authenticated)
  • userhome (only available if authenticated)


Web Scripts also have access to the following additional root objects:

argsM
an associative array of any URL parameters (where each key is a parameter name and each value is an array containing the parameter values, even if only one is supplied) - complements the root object args. See example. [sorry, available 2.1 Enterprise onwards].
guest
A boolean indicating whether the Web Script is executing as "Guest".
date
A date representing the date and time of the Web Script request.
server
An associative array of meta-data properties that describe the hosting Alfresco server.
roothome
The Repository root node.
url
An object providing access to the URL (or parts of the URL) that triggered the Web Script.
webscript
An associative array of meta-data properties that describe this Web Script.

And remember, the template also has access to any root objects created by the "execute" script , if one has been associated with the Web Script.


Web Script templates also have access to the following additional methods:

absurl(url)
Returns an absolute URL representation of the passed url. Useful when rendering links within ATOM (and similar formats).
xmldate(date)
Returns an ISO8601 formatted result of the passed date. Useful when rendering dates within XML.
scripturl(queryString)
Returns a url that references this Web Script. The passed queryString is added to the url. System arguments such as guest and format are automatically added. Note, this method is particularly useful for protection against the runtime environment within which the Web Script is executing. In some environments (such as a Portal) the url may be encoded.
clienturlfunction(funcName)
Generates a client-side javascript function that can generate a URL back to this Web Script.

</start ------------------------------------------------------------>

<start -------------------------------------------------------------------------->

Status Response Template

(from 3.4)

Web Script specific template named <scriptid>.<method>.<format>.<code>.ftl 
located in the same folder as the Web Script description document and used for the specified status code only
e.g. /org/alfresco/sample/blogsearch.get.html.400.ftl
Web Script specific template named <scriptid>.<method>.<format>.status.ftl 
located in the same folder as the Web Script description document used for any status code
e.g. /org/alfresco/sample/blogsearch.get.html.status.ftl
Package level template named <format>.<code>.ftl 
this template is first located in the package of the Web Script, but if not found, is searched for in the parent package hierarchy, up to the root package
e.g. /org/alfresco/sample/html.400.ftl
Package level template named <format>.status.ftl 
this template is first located in the package of the Web Script, but if not found, is searched for in the parent package hierarchy, up to the root package
e.g. /org/alfresco/sample/html.status.ftl
Default template named <code>.ftl 
located in the root package and always renders html
e.g. /400.ftl
Default template named status.ftl 
located in the root package (provided out-of-the-box) and always renders html
e.g. /status.ftl

Status Response templates have access to the same root objects as standard Web Script response templates with the addition of the 'status' object. The exception is that the default templates /<code>.ftl and /status.ftl only have access to the root objects 'url', 'status', 'server' and 'date'.

To provide a custom "Bad Request" status response for our blog search we create the following file in the same folder as the Web Script Description document

blogsearch.get.html.400.ftl

whose content is

<html>
  <body>
    ${status.message}
  </body>
</html>

We can also provide a meaningful response for atom requests which can be machine read:

blogsearch.get.atom.400.ftl
<?xml version="1.0" encoding="UTF-8"?>
<response>
  <code>${status.code}</code>
  <codeName>${status.codeName}</codeName>
  <codeDescription>${status.codeDescription}</codeDescription>
  <message>${status.message}</message>
</response>

Remember, these templates are optional, as the search for an appropriate status template will always eventually find the default template /status.ftl.


</start -------------------------------------------------------------------------->

<start --------------------------------------------------->

(4.3) HTTP Method Tunneling

Not all clients can issue all HTTP methods. In the most severe case, a client may be restricted to GET and POST only. In this situation, Web Scripts provide two mechanisms for issuing any HTTP method via POST:

HTTP Request Header 'X-HTTP-Method-Override'
URL parameter 'alf_method
Note: this approach takes priority over the Request Header, if both specified

In either case, the value is set to the HTTP method name to be invoked.

For example, if the HTTP DELETE method is not supported by a client, but the client wishes to delete a blog entry, the following may be issued:

POST X-HTTP-Method-Override=DELETE /alfresco/service/sample/blog/2007/03/04/new-release
POST /alfresco/service/sample/blog/2007/03/04/new-release?alf_method=DELETE

</start --------------------------------------------------->

<start --------------------------------------------------->

(4.3) HTTP Method Tunneling

Not all clients can issue all HTTP methods. In the most severe case, a client may be restricted to GET and POST only. In this situation, Web Scripts provide two mechanisms for issuing any HTTP method via POST:

HTTP Request Header 'X-HTTP-Method-Override'
URL parameter 'alf_method
Note: this approach takes priority over the Request Header, if both specified

In either case, the value is set to the HTTP method name to be invoked.

For example, if the HTTP DELETE method is not supported by a client, but the client wishes to delete a blog entry, the following may be issued:

POST X-HTTP-Method-Override=DELETE /alfresco/service/sample/blog/2007/03/04/new-release
POST /alfresco/service/sample/blog/2007/03/04/new-release?alf_method=DELETE

</start --------------------------------------------------->

<start --------------------------------------------------->

(4.4) Forcing Success Response Status

Not all clients can gracefully handle non-success HTTP Responses e.g. the Flash runtime player - the runtime for Adobe Flex applications.

In this situation, Web Scripts provide a mechanism to force all HTTP Responses to indicate success in their Response Header. However, the Response body will still represent the content as if a non-success status had occurred.

To force HTTP Response Header success set the following HTTP Request Header:

alf-force-success-response = true

</start --------------------------------------------------->

<start --------------------------------------------------->

(4.5) JSON Callbacks

If your Web Scripts provide JSON responses, it's likely they'll be invoked directly from within a Web Browser via the XMLHttpRequest object. However, due to security reasons, you may run into cross-domain issues, a restriction that requires you to proxy your requests on the server side. Typically, to "workaround" these issues, public services such as Yahoo! JSON Services provide a callback mechanism.

Web Scripts also provide this mechanism which is invoked by adding the following URL parameter on JSON URL requests:

alf_callback=function

where function is the name of a client-side javascript function to be invoked.

The following simple HTML page demonstrates this:

<html>
  </body>
    <script>
      function showTitle(res)
      {
        alert(res.feed.title);
      }
    </script>
    <script src="http://localhost:8080/alfresco/service/sample/blog/category/web20.json&alf_callback=showTitle"/>
  </body>
</html>

</start --------------------------------------------------->

<start --------------------------------------------------->

(4.6) Cache Control

(sorry, available 2.1 Enterprise onwards)

A Web Script may specify how its response is cached. See example. Each Web Script Runtime may or may not adhere to the caching requirements of the Web Script; if the runtime does not support caching, the requirements are just ignored. Alfresco 2.1 caching is only supported by the Servlet Runtime, by virtue of caching built into the Web Browser or a Proxy server.

</start --------------------------------------------------->

<start --------------------------------------------------->

(4.6.1) Definition-time Cache Control

Definition-time cache control is optionally specified via the Web Script Description. An example follows:

<webscript>
  ...
  <cache>
    <never>false</never>
    <public/>
    <mustrevalidate/>
  </cache>
</webscript> 

Where:

  • never (optional) specifies whether caching should be applied at all; valid values (optional) are:
    • true (default) specifies the Web Script response should never be cached
    • false specifies the Web Script response may be cached
    • Note: If never is not specified, the default is true
  • public (optional) specifies whether authenticated responses should be cached in a public cache; valid values (optional) are:
    • true (default) specifies the Web Script authenticated response may be cached in a public cache
    • false specifies the Web Script authenticated response may not be cached in a public cache
    • Note: If public is not specified, the default is false
  • mustrevalidate (optional) specifies whether a cache must re-validate its version of the Web Script response in order to ensure freshness; valid values (optional) are:
    • true (default) specifies that validation must occur
    • false specifies that validation may occur
    • Note: If mustrevalidate is not specified, the default is true

</start --------------------------------------------------->

<start --------------------------------------------------->

(4.6.2) Run-time Cache Control

Run-time Cache control is optionally specified via the root object cache which is available to the Web Script "Execution" script. At run-time, expiry criteria may be set, and definition-time controls may be overridden.

</start --------------------------------------------------->

<start --------------------------------------------------->

(5.3.1) Mock Web Server

Just start the TestWebScriptServer application (it supports a main entry point) and interact with it via the one of the following commands:

   ##
   ##  Meta commands 
   ## 
   
   ok> help 
   
       List this help. 
   
   ok> r 
   
       Repeat last command. 
   
   ok> user [<userName>] 
   
       Switch to specified <userName>.  If <userName> is omitted, the currently 
       selected user is shown.
       
       A ticket may be specified instead of username. 
   
   ok> quit | exit
   
       Quit this Web Script server.
   
   ## 
   ##  HTTP Requests
   ## 
   
   ok> get <path>
   
       Issue a HTTP GET request to the Web Script located at <path>.  The response
       is dumped to the console.
       
       <path> URL relative to /alfresco/service
       
       e.g. get /blog/search?q=tutorial
   
   ok> put <path>
   
       Issue a HTTP PUT request to the Web Script located at <path>.  The response
       is dumped to the console.
       
       <path> URL relative to /alfresco/service
       
   ok> post <path>
   
       Issue a HTTP POST request to the Web Script located at <path>.  The response
       is dumped to the console.
       
       <path> URL relative to /alfresco/service
   
   ok> delete <path>
   
       Issue a HTTP DELETE request to the Web Script located at <path>.  The response
       is dumped to the console.
       
       <path> URL relative to /alfresco/service
       
   ok> tunnel <encoding> <method> <path>
   
       Tunnel a request via POST.
       
       The actual <method> is encoded as either the URL parameter named alf:method or 
       the request header named X-HTTP-Method-Override as specified via the <encoding>
       parameter:
       
       param - encode method as URL parameter
       header - encode method in Request Header
       
       e.g. to tunnel 'get /index' via post (where method is encoded in header) issue
       
       tunnel header get /index
      
   ## 
   ##  Request Header Commands 
   ## 
   
   ok> header 
   
       Show all defined headers. 
   
   ok> var <headerName>=<headerValue> 
   
       Define or update a header value. 
   
       <headerName> header name 
       <headerValue> header value 
   
       e.g. 
   
       header alf-force-success=true 
   
   ok> header <headerName>= 
   
       Delete an existing header value. 
   
       <headerName> header name 
       
   ## 
   ##  end 
   ## 

For example (to invoke our example blog search Web Script):

 ok> get /blog/search?q=tutorial
   <html>
    <body>
      <img src="/alfresco/images/logo/AlfrescoLogo32.png" alt="Alfresco" />
      Blog search: tutorial
      <br>
      <table>
       <tr>
         <td><img src="/alfresco/images/filetypes/_default.gif"/>
         <td><a href="/alfresco/download/direct/workspace/SpacesStore/d0ea49aa-cda3-11db-a118-718e716a085b/Alfresco-Tutorial.pdf">Alfresco-Tutorial.pdf</a>
       </tr>
      </table>
    </body>
  </html>
 78ms

</start --------------------------------------------------->

<start --------------------------------------------------->

(5.3.2) Unit Test Helper Methods

Within a unit test, the following pattern may be used:

 // retrieve an instance of the test server
 TestWebScriptServer server = TestWebScriptServer.getTestServer();
 
 // submit a request
 MockHttpServletResponse res = server.submitRequest("get", "/blog/search?q=tutorial");
 
 // process response
 byte[] content = res.getContentAsByteArray();
 String contentAsString = res.getContentAsString();

</start --------------------------------------------------->

<start --------------------------------------------------->

(6) Appendix A: Web Script Root Objects

(6.1) formdata

A host object providing access to multipart/form-data requests allowing file upload from a Web Script. See example. (sorry, 2.1 Enterprise onwards).

hasField
boolean indicating the existence of a named form field in the multipart request
fields
an array of formfield where each entry represents a field within the multipart request

(6.1.1) formfield

A host object providing access to a form field within a multipart/form-data request.

name
the name of the form field (Note that form fields may not be uniquely named)
isFile
boolean indicating whether this field represents a file (content)
value
string representing the field value (in the case of isFile is true, a best effort conversion is attempted)
content
a ScriptContent representing the content of the field
mimetype
the mimetype of the content (or null, if isFile is false)
filename
the filename of the source file used to provide the content (or null, if isFile is false, or a filename was not provided)

(6.2) url

A host object providing access to the URL (or parts of the URL) that triggered the Web Script.

context
Alfresco context path e.g. /alfresco
serviceContext
Alfresco service context path e.g. /alfresco/service
service
Web Script path e.g. /alfresco/service/blog/search
full
Web Script URL e.g. /alfresco/service/blog/search?q=tutorial
args
Web Script URL arguments e.g. q=tutorial
match
The part of the Web Script URL that matched the Web Script URL template
extension
The part of the Web Script URL that extends beyond the match path (if there is no extension, an empty string is returned)


For example, imagine a Web Script URL template of

/user/{userid}

and a Web Script request URL of

/alfresco/service/user/fred?profile=full&format=html

The url root object will respond as follows:

  • url.context => /alfresco
  • url.serviceContext => /alfresco/service
  • url.service => /alfresco/service/user/fred
  • url.full => /alfresco/service/user/fred?profile=full&format=html
  • url.args => profile=full&format=html
  • url.match => /user/
  • url.extension => fred

(6.3) status

An associative array of response status properties that allow control over the status and content of the Web Script Response.

code
(read/write) status code (primarily a HTTP status code, but can be any number)
codeName
(read) human readable status code name
codeDescription
(read) human readable status code description
message
(read/write) status message
redirect
(read/write) a boolean indicating whether to redirect to a status specific "response" template
exception
(read/write) the exception (if any) which has caused this status

(6.4) cache

An associative array of cache control properties that allow control over how the Web Script Response is cached. See example. (sorry, 2.1 Enterprise onwards).

neverCache
(read/write boolean) control whether Web Script Response should be cached at all; true means never cache
isPublic
(read/write boolean) control whether Web Script Response should be cached by public caches
mustRevalidate
(read/write boolean) control whether cache must re-validate its version of the Web Script Response to ensure freshness
maxAge
(read/write long) specifies the maximum amount of time (in seconds, relative to the time of request) that the response will be considered fresh
lastModified
(read/write date) specifies the time that the content of the response last changed
ETag
(read/write string) specifies a unique identifier that changes each time the content of the response changes

(6.5) server

An associative array of meta-data properties that describe the hosting Alfresco server.

versionMajor
server major version number e.g. 1.2.3
versionMinor
server minor version number e.g. 1.2.3
versionRevision
server revision number e.g. 1.2.3
versionLabel
server version label e.g. Dev
versionBuild
server build number e.g. build-1
version
server version e.g. major.minor.revision (label)
edition
server edition e.g. Enterprise
schema
server schema e.g. 10

(6.6) webscript

An associative array of meta-data properties describing the Web Script.

id
The Web Script Id
shortName
The Web Script short name
description
The Web Script description
defaultFormat
The default response format if none explicitly specified in Web Script URL
formatStyle
The accepted ways of specifying the format in the Web Script URL
URIs
A (string) array of URL templates
method
HTTP Method
requiredAuthentication
required level of authentication
requiredTransaction
required level of transaction
storePath
the path of the persistent store where the Web Script is stored
scriptPath
the path (within storePath) of Web Script implementation files
descPath
the path (within storePath) of the Web Script description document

</start --------------------------------------------------->

Personal tools
Download and go
© 2012 Alfresco Software, Inc. All Rights Reserved. Legal | Privacy | Accessibility