apache > cocoon

- Home

# Advanced Control Flow - Flowscript

## Flowscript

Cocoon Flowscript is a JavaScript API to manage control flow based on an extended version of the Mozilla Rhino JavaScript interpreter that supports continuations. This extension has been incorporated into official Mozilla Rhino version and is shipped with Cocoon 2.2.

## Flow Object Model

Cocoon provides a set of system objects for use by Flowscripts. We call this set of objects the Flow Object Model (FOM). The Flow Object Model consists of the following objects:

- Cocoon
- Request
- Response
- Session
- Context
- Cookie
- Log
- WebContinuation

### Cocoon Object

The `Cocoon` object represents the current Cocoon Sitemap. This is the entry point into the FOM. There is one instance of `Cocoon` which you may access in your scripts as the global variable `cocoon`, for example like this:

          var value = cocoon.request.getAttribute("blah");

The `Cocoon` object supports the following properties and functions:

#### request

The current Cocoon request:

Property [Request] `request`

#### response

The current Cocoon response:

Property [Response] `response`

#### session

The current Cocoon session:

Property [Session] `session`

#### context

The current Cocoon application context:

Property [Context] `context`

#### log

A reference to the current logger:

Property [Log] `log`

#### parameters

Any parameters passed to the script by the Cocoon Sitemap

Property `[Object] parameters`

#### sendPage

Function `sendPage([String] uri, [Object] bean)`

Passes control to the Cocoon sitemap to generate the output page.

`uri` is the sitemap URI of the page to be sent back to the client. If the URI starts with a slash, it is resolved starting at the root sitemap, otherwise it is resolved relative to the current sitemap. The URI should not contain a scheme (such as cocoon:).

`bean` is a context object which can be accessed either inside this page to extract various values and place them in the generated page or in the sitemap to use values as parameters for actions or transformers.

Note
Use `value="{flow-attribute:name}"` in any parameter tag in the sitemap to access a value from the bean.

#### sendPageAndWait

Function `[WebContinuation] sendPageAndWait([String] uri, [Object] bean, [Function] postPipelineCode, [Number] timeToLive)`

Passes control to the Cocoon sitemap to generate the output page.

The flow script is suspended after the page is generated and the whole execution stack saved in the WebContinuation object returned from this function.

`uri` is the relative URL of the page to be sent back to the client. If the URI starts with a slash, it is resolved starting at the root sitemap, otherwise it is resolved relative to the current sitemap. The URI should not contain a scheme (such as cocoon:).

`bean` is a context object which can be accessed either inside this page to extract various values and place them in the generated page or in the sitemap to use values as parameters for actions or transformers.

Note
Use `value="{flow-attribute:name}"` in any parameter tag in the sitemap to access a value from the bean.

If provided, the `postPipelineCode` function will be executed after pipeline processing is complete but before the script is suspended. You can use this to release resources that are needed during the pipeline processing but should not become part of the continuation. For example:

    function processPage() {
       var id = ...
       var bizData = ...
       var uri = ...
       var comp = cocoon.getComponent(id);
       // use comp
       ...
       cocoon.sendPageAndWait(uri, bizData, function() {
          cocoon.releaseComponent(comp);
          comp = null;
       });
    }

`timeToLive` is the time to live in milliseconds for the continuation created.

The return value is the continuation object.

#### sendStatus

Function `sendStatus([Number] sc)`

Sends an empty response with the provided HTTP status code.

#### createPageLocal

Function `[Object] createPageLocal()`

Creates a Page Local object. The returned object behaves like a normal JavaScript object, but restores the property values it had when sendPageAndWait was originally called, each time a page is resubmitted (e.g. after hitting the back button). Such objects can be used to associate state with one particular page sent to the browser.

#### processPipelineTo

Function `processPipelineTo([String] uri, [Object] bizData, [java.io.OutputStream] stream)`

Call the Cocoon sitemap for the given URI, sending the output of the eventually matched pipeline to the specified `OutputStream`.

`uri` is the URI for which the request should be generated. If the URI starts with a slash, it is resolved starting at the root sitemap, otherwise it is resolved relative to the current sitemap. The URI should not contain a scheme (such as cocoon:).

`bizData` is the business data object to be made available to the forwarded pipeline

`stream` is an `OutputStream` where the output should be written to.

#### redirectTo

Function `redirectTo([String] uri, [boolean] isGlobal)`

Send a client-side redirect to the browser. The `uri` argument is the URI to which the browser should be redirected.

The `isGlobal` argument, if `true`, causes an HTTP redirect to be sent to the client browser in all cases. When `isGlobal` is `false` and the request is an internal one (using "cocoon:"), the internal request will be redirected. For example, if you have a pipeline called from an aggregation:

    <map:aggregate>
      <map:part src="cocoon:/callflow"/>
    </map:aggregate>

and in some flow function:

    cocoon.redirectTo("http://www.google.com", false);

then the map:aggregate will try to read the content for its part from Google.

#### createWebContinuation

Function `[WebContinuation] createWebContinuation()`

Creates a new "bookmark" WebContinuation object. When invoked it will cause the script to resume right after the call. By calling this function prior to sendPageAndWait() you can be create a "bookmark" which will cause the page to be redisplayed in the browser. Note: the WebContinuation associated with sendPageAndWait() doesn't do this. Rather it resumes execution after the the page is submitted.

For example:

    function processPage() {

      var bkm = cocoon.createWebContinuation();
      var biz = getBizData();
      cocoon.sendPageAndWait("uri",
                             {bookmark: bkm, biz: biz},
                             function() { releaseData(biz); });
    }

#### load

Function `load([String] uri)`

Load the JavaScript script specified by `uri`. The Cocoon source resolver is used to resolve `uri`.

#### getComponent

Function `Object getComponent([String] id)`

Access an Avalon component.

#### releaseComponent

Function `releaseComponent([Object] component)`

Release a pooled Avalon component.

#### createObject

Function `createObject([JavaClass] componentClass)`

Create and setup an object so that it can access the information provided to regular components. This is done by calling the various Avalon lifecycle interfaces implemented by the object.

#### disposeObject

Function `disposeObject([Object] object)`

Dispose an object that has been created using `createObject`.

#### exit

Function exit()

Exit the current flowscript invocation.

There are some flowscript use cases where we want to stop the current flowscript without creating a continuation, as we don't want the user to go back to the script and return from the current function.

An example is a "login" function where the caller function expects this function to exit only if login is successful, but that has to handle e.g. a registration process that includes a "cancel" button.

### Request Object

The `Request` object represents the current Cocoon request. It provides the following functions and properties:

#### get

Function `[String] get([String] name)`

Get the request parameter or attribute with the specified `name`.

#### getAttribute

Function `[String] getAttribute([String] name)`

Get the request attribute with the specified `name`.

#### getAttributeNames

Function `[java.util.Enumeration] getAttributeNames()`

Get an enumeration of request attribute names.

#### setAttribute

Function `setAttribute([String] name, [Object] value)`

Set the value of a request attribute.

#### removeAttribute

Function `removeAttribute([String] name)`

Remove the attribute with the name `name` from this request.

#### getCharacterEncoding

Function `[String]getCharacterEncoding()`

Return the character encoding used by this request.

#### setCharacterEncoding

Function `setCharacterEncoding([String] value)`

Set the character encoding used by this request.

#### getContentLength

Function `[Number] getContentLength()`

Get the content-length of this request

#### getContentType

Function `[String] getContentType()`

Get the content-type of this request

#### getParameter

Function `[String] getParameter([String] name)`

Get the request parameter with the specified `name`.

#### getParameterValues

Function `[Array] getParameterValues([String] name)`

Get an array of request parameters with the specified `name`.

#### getParameterNames

Function `[java.util.Enumeration] getParameterNames()`

Get an enumeration of the parameter names in this request.

#### getAuthType

Function `[String] getAuthType()`

Get the authorization type used in this request.

#### getProtocol

Function `[String] getProtocol()`

Get the protocol used in this request.

#### getScheme

Function `[String] getScheme()`

Get the scheme used in this request.

#### getMethod

Function `[String] getMethod()`

Get the method used in this request.

#### getServerName

Function `[String] getServerName()`

Get the server name of this request.

#### getServerPort

Function `[Number] getServerPort()`

Get the server port of this request.

#### getRemoteAddr

Function `[String] getRemoteAddr()`

Get the remote address of this request.

#### isSecure

Function `[Boolean] isSecure()`

Get the `secure` property of this request.

#### getLocale

Function `[String] getLocale()`

Get the locale of this request.

#### getLocales

Function `[Array [String]] getLocales()`

Get the locales of this request.

#### getCookies

Function `[Array [Cookie]] getCookies()`

Get the cookies associated with this request.

#### getHeader

Function `[String] getHeader([String] name)`

Get the header with `name` from this request.

#### getHeaders

Function `[Array] getHeaders()`

Get the headers associated with this request.

#### getHeaderNames

Function `[java.util.Enumeration] getHeaderNames()`

Get an enumeration of header names from this request.

#### getRemoteUser

Function `[String] getRemoteUser()`

Get the remote user associated with this request.

#### getUserPrincipal

Function `[String] getUserPrincipal()`

Get the user principal associated with this request.

#### isUserInRole

Function `[Boolean] isUserInRole([String] role)`

Returns whether the user associated with this request is in the specified `role`.

#### Properties

`Request` properties map to request parameters, i.e. `request.blah` is equivalent to `request.getParameter("blah")`.

### Response Object

The `Response` object represents the Cocoon response associated with the current request.

The response object contains hooks only to the cookies and to the response headers. Everything else will be controlled by the rest of the cocoon pipeline machinery (like output encoding, for example, which should *NOT* be determined by the flow).

It provides the following functions and properties:

#### createCookie

Function `[Cookie] createCookie([String] name, [String] value)`

Creates a new Cookie.

#### addCookie

Function `addCookie([Cookie] cookie)`

Adds `cookie` to the current response.

#### containsHeader

Function `[Boolean] containsHeader([String] name)`

Returns whether the current response contains a header with the specified `name`.

#### setHeader

Function `setHeader([String] name, [String] value)`

Replaces the value of the header with `name` with `value`.

#### addHeader

Function `addHeader([String] name, [String] value)`

Creates a new header in the current response with the specified `name` and `value`.

#### setStatus

Function `setStatus([Number] sc)`

Sets the status code for this response.

### Session Object

The `Session` object represents the user session associated with the current Cocoon request.

It provides the following functions and properties:

#### getAttribute

Function `[Object] getAttribute([String] name)`

Get the value of the session attribute with the specified `name`.

#### setAttribute

Function `setAttribute([String] name, [Object] value)`

Set the value of the session attribute with the specified `name` to `value`.

#### removeAttribute

Function `removeAttribute([String] name)`

Remove the session attribute with the specified `name`.

#### invalidate

Function `invalidate()`

Invalidate this session, releasing all resources associated with it.

#### isNew

Function `[Boolean] isNew()`

Returns `true` if the client does not yet know about the session or if the client chooses not to join the session. For example, if the server used only cookie-based sessions, and the client had disabled the use of cookies, then a session would be new on each request.

#### getId

Function `[String] getId()`

Returns the unique id associated with this session.

#### getCreationTime

Function `[Number] getCreationTime()`

Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.

#### getLastAccessedTime

Function `[Number] getLastAccessedTime()`

Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.

#### setMaxInactiveInterval

Function `setMaxInactiveInterval([Number] interval)`

Specifies the time, in seconds, between client requests before the contextcontainer will invalidate this session. A negative time indicates the session should never timeout.

#### getMaxInactiveInterval

Function `[Number] getMaxInactiveInterval()`

Returns the maximum time interval, in seconds, that the context container will keep this session open between client accesses. After this interval, the context container will invalidate the session. The maximum time interval can be set with the `setMaxInactiveInterval` method. A negative time indicates the session should never timeout.

#### Properties

`Session` properties map to session attributes, i.e. `session.blah` is equivalent to `session.getAttribute("blah")`.

### Context Object

The `Context` object represents the client context associated with the current Cocoon request.

It provides the following functions and properties:

#### getAttribute

Function `[Object] getAttribute([String] name)`

Get the value of the context attribute with the specified `name`.

#### setAttribute

Function `setAttribute([String] name, [Object] value)`

Set the value of the context attribute with the specified `name` to `value`.

#### removeAttribute

Function `removeAttribute([String] name)`

Remove the context attribute with the specified `name`.

#### getInitParameter

Function `getInitParameter([String] name)`

Get the value of the context initialization parameter with the specified `name`.

#### Properties

`Context` properties map to context attributes, i.e. `context.blah` is equivalent to `context.getAttribute("blah")`.

### Cookie Object

`Cookie` provides the following functions and properties:

#### getName

Function `[String] getName()`

Get the name of this cookie.

#### getVersion

Function `[String] getVersion()`

Get the version of this cookie.

#### setVersion

Function `setVersion([String] version)`

Set the version of this cookie.

#### getValue

Function `[String] getValue()`

Get the value of this cookie.

#### setValue

Function `setValue([String] value)`

Set the value of this cookie.

#### getComment

Function `[String] getComment()`

Get the comment of this cookie.

#### setComment

Function `setComment([String] comment)`

Set the comment of this cookie.

#### getDomain

Function `[String] getDomain()`

Get the domain of this cookie.

#### setDomain

Function `setDomain([String] domain)`

Set the domain of this cookie.

#### getPath

Function `[String] getPath()`

Get the path of this cookie.

#### setPath

Function `setPath([String] path)`

Set the path of this cookie.

#### getSecure

Function `[Boolean] getSecure()`

Get the secure property of this cookie.

#### setSecure

Function `setSecure([Boolean] value)`

Set the secure property of this cookie.

### Log Object

The `Log` object provides an interface to the Cocoon logging system.

It supports the following functions:

#### error

Function `error([String] message, [java.lang.Throwable] exception)`

Log an error message. If `exception` is provided its stack trace will also be logged.

#### debug

Function `debug([String] message, [java.lang.Throwable] exception)`

Log a debug message. If `exception` is provided its stack trace will also be logged.

#### warn

Function `warn([String] message, [java.lang.Throwable] exception)`

Log a warning message. If `exception` is provided its stack trace will also be logged.

#### info

Function `info([String] message, [java.lang.Throwable] exception)`

Log an information message. If `exception` is provided its stack trace will also be logged.

#### isErrorEnabled

Function `[Boolean] isErrorEnabled()`

Returns whether error message logging is enabled.

#### isDebugEnabled

Function `[Boolean] isDebugEnabled()`

Returns whether debug message logging is enabled.

#### isWarnEnabled

Function `[Boolean] isWarnEnabled()`

Returns whether warning message logging is enabled.

#### isInfoEnabled

Function `[Boolean] isInfoEnabled()`

Returns whether information message logging is enabled.

### WebContinuation

A `WebContinuation` represents a continuation of a Flowscript. Because a user may click on the back button in the browser and restart a saved computation in a continuation, each `WebContinuation` becomes the parent of a subtree of continuations.

If there is no parent `WebContinuation`, the created continuation becomes the root of a tree of `WebContinuation`s.

`WebContinuation` objects support the following functions and properties:

#### id

Property `[String] id`

Returns the unique string identifier of this Web Continuation.

#### continuation

Property `[Continuation] continuation`

Returns the JavaScript continuation associated with this Web Continuation.

#### previousBookmark

Property `[WebContinuation] previousBookmark`

Returns a reference to the first bookmark continuation among the pages preceding the one associated with this object, or null if no such bookmark continuation exists. The returned object is the continuation you would invoke to implement a "Back" button.

#### isBookmark

Function `[Boolean] isBookmark()`

Returns `true` if this continuation was not created by sendPageAndWait.

#### getParent

Function `[WebContinuation] getParent()`

Get the parent continuation of this continuation.

#### getChildren

Function `[Array [WebContinuation]] getChildren()`

Get the child continuations of this continuation.

#### invalidate

Function `invalidate()`

Invalidates a `WebContinuation`. This effectively means that the continuation object associated with it will no longer be accessible from Web pages. Invalidating a `WebContinuation` invalidates all the `WebContinuation`s which are children of it.

Errors and Improvements? If you see any errors or potential improvements in this document please help us: View, Edit or comment on the latest development version (registration required).