XForms(Orbeon), REST, CMIS and Alfresco – part 2 Files

To keep things simple this example uses basic authentication – to see how to handle authentication in more detail see part 1 here

This is a relatively straightforward example of how to upload a file into Alfresco from Orbeon using CMIS over REST.

I’m not going to cover the details of how the REST interface works (as usual POST for create, PUT for update) or go into depth about how to use CMIS as this is covered elsewhere e.g. ECM Architect article on CMIS

Starting from the standard example of how to upload a file in Orbeon the changes to make are:

  • Instead of posting a multi-part mime message by using the method form-data-post use a normal post and encode the file using xxforms:doc-base64
  • Use the test: (echo: in 3.9) action – after this has been done the file will be uploaded to the server in a temporary directory
  • Create a second submission to post the file to Alfresco

An alternative way to encode the file would be to use the technique described here with a serialized element replacing the media element. This is simpler but less instructive.

For the second submission I use a template file containing a blank CMIS entry and fill in the appropriate fields, you can populate any aspect data fields here. I’ve either used xforms:setvalue or xslt as part of an xpl pipeline depending on what I’m doing – here I’m keeping it simple and just using setvalue.

The contents of the xforms:dispatch element are used to control the parameters to set as part of the upload submission (you’ll see that the file is sent to a test directory in this example) – there are a very limited set of parameters here but it’s easy enough to add more.

(I haven’t done any error handling although you can see what to do using the ins-cmis-rest-control instance)


  • According to the atom spec the contents of the atom:content are treated differently according to the value of the type attribute – it’s therefore safer to use cmisra:content instead
  • If there’s an error in Alfresco, e.g. trying to create two files with the same name, then Alfresco will return text/html not text/xml even if you ask it nicely.

It’s worth noting that if you try and POST the same file twice you will get a 500 response – if you try and upload the same file twice via Share then you get a second file with the suffix (1)

This covers the basics of how to upload a file from Orbeon to Alfresco using the CMIS REST interface.

Updating a file, using PUT or deleting are fairly straightforward after this. (Note that the metadata and file contents are different things so are updated separately.)

Enough talking – here’s the example

 <html xmlns:xforms="http://www.w3.org/2002/xforms"


<title>Spike Upload</title>

<xforms:model id="cmis-rest-model">
    <xxforms:variable name="alfresco-uri"
        as="xs:anyURI" />
    <xxforms:variable name="alfresco-username"
        as="xs:string" />
    <xxforms:variable name="alfresco-credentials"
        as="xs:string" />
    <xforms:instance id="ins-cmis-rest-control">
            <status />

    <xforms:instance id="ins-cmis-rest-create-file">
        <xi:include href="create-file.xml" xxi:omit-xml-base="true" />
    <xforms:instance id="ins-cmis-rest-create-file-result">
        <atom:entry />
    <xforms:instance id="ins-upload">
        <upload xmlns="">
            <summary />
            <media filename="" mediatype="" size=""
                                            xsi:type="xs:anyURI" />
            <category>term="foo"; scheme="bar"; label="baz"</category>

    <xforms:instance id="ins-upload-template">
        <upload xmlns="">
            <summary />
            <media filename="" mediatype="" size=""
                                            xsi:type="xs:anyURI" />
            <category>term="foo"; scheme="bar"; label="baz"</category>

    <xforms:submission id="sub-background-upload"
        ref="instance('ins-upload')" method="post" replace="none"
        resource="test:" validate="false" />



        <xforms:action ev:event="xforms-submit-done">
            <xxforms:variable name="media-entry"
            <xxforms:variable name="file-uri"

            <xforms:dispatch target="cmis-rest-model"
                <xxforms:context name="fr:media-entry"
                <xxforms:context name="fr:media-title"
                <xxforms:context name="fr:media-type"

                <xxforms:context name="fr:file-content"    
                          select="xxforms:doc-base64($file-uri)" />

            <xforms:insert nodeset="instance('ins-upload')"
                         origin="instance('ins-upload-template')" />
            <xforms:send submission="sub-get-feed" />

    <xforms:instance id="ins-post-response">
        <foo xmlns="" />

    <xforms:submission id="sub-get-feed" method="get"
        instance="ins-feed" serialization="none"
        xxforms:password="{$alfresco-credentials}" replace="instance">

    <xforms:instance id="ins-feed">
        <atom:feed />

    <xforms:send ev:event="xforms-model-construct-done"
        submission="sub-get-feed" />

    <xforms:action ev:event="cmis-rest-upload-file">
        <xxforms:variable name="media-type"
        <xxforms:variable name="content"
            nodeset="instance('ins-cmis-rest-create-file')/atom:entry/*" />
            at="last()" position="after" />

            value="event('fr:media-title')" />

            value="$content" />

            value="$media-type" />

            value="$media-type" />

        <!-- You can set any values you like here
               e.g. a custom document type or aspect properties -->
        <xforms:send submission="cmis-rest-create-file-submission" />

    <xforms:submission ref="instance('ins-cmis-rest-create-file')"
        id="cmis-rest-create-file-submission" method="post"
        xxforms:password="{$alfresco-credentials}" replace="instance"
        <!-- This doesn't actually help for errors,
                    e.g. 2 files with the same name, as Alfresco
              always returns a 500 with Content-Type: text/html  -->
        <xforms:action ev:event="xforms-submit-error">
                value="'fail'" />
            <xforms:message level="modal"
                value="concat('An error occurred while creating
                 a file in Alfresco. Please inform an administrator.
                         (error-type:',event('error-type'), ')')" />
        <xforms:action ev:event="xforms-submit-done">
    <xforms:setvalue ref="instance('ins-cmis-rest-control')//status"
                value="'ok'" />


    <h1>Spike Upload</h1>

    <xforms:group ref="instance('ins-upload')">


            <!-- Upload field -->
            <xforms:upload ref="media" xxforms:size="60">
                <xforms:label>Upload file: </xforms:label>
                <xforms:filename ref="@filename" />
                <xforms:mediatype ref="@mediatype" />
                <xxforms:size ref="@size" />

            <xforms:output value="media" appearance="xxforms:download">
                <xforms:filename ref="@filename" />
                <xforms:mediatype ref="@mediatype" />


            <xforms:textarea ref="summary">
                <xforms:label>Summary: </xforms:label>


        <xforms:submit submission="sub-form-data-post">
            <xforms:label>Submit (form-data-post)</xforms:label>

    <hr />

    <fr:datatable paginated="false">
                <th fr:sortable="true" fr:resizeable="true">File Name</th>
                <th fr:sortable="true" fr:resizeable="true">Published</th>
                <th fr:sortable="true" fr:resizeable="true">Author</th>
            <xforms:repeat id="rep-media"
                    <td><xforms:output ref="atom:title" /></td>
                    <td><xforms:output ref="atom:published"
                            xxforms:format="format-dateTime(., '[Y0001]-[M01]-[D01]')" /></td>
                    <td><xforms:output ref="atom:author/atom:email" /></td>
                    <td><xforms:output ref="atom:summary" /></td>


The template file:

 <?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
    <summary>A sample whitepaper named Sample A</summary>


XForms (Orbeon), CAS and CMIS (Alfresco) – Part 1 – Authentication

I thought I’d write about my experience of using the Alfresco CMIS interface as a backend to a custom XForms application.
There’s a natural fit here as the atom based syntax of CMIS fits very nicely with XForms however there are a few little wrinkles to work through.


The first issue to decide on is how to handle the authentication of the CMIS service – this will very much depend on your application requirements and architecture. As you will see from earlier posts we are running behind CAS with both our Alfresco and Orbeon apps using CAS authentication (Orbeon via Spring Security).

Due to the application requirements I am using two different authentication strategies – a well known generic user and proxy authentication using the logged in user.

Basic Auth

This is the easiest to set up and use

The way I’ve done this is to define some configuration properties to set the user name etc and assign these to variables within the model


<xxforms:variable name="alfresco-uri"
<xxforms:variable name="alfresco-username"
<xxforms:variable name="alfresco-credentials"
<xxforms:variable name="is-send-alfresco"

Retrieving information is then via a straightforward submission using xxforms:username and xxforms:password (obviously you need to set the path of the action appropriately)

<xforms:submission id="cmis-rest-get-file-record" method="get"
  action="{$alfresco-uri}service/cmis/p/User Homes/TestUser/children"

This uses basic auth which will work with an out of box Alfresco but does have the limitations of basic auth i.e. it’s not very secure unless you use https

Proxy Auth

First thing to note in following on is that this has to be done using https as otherwise CAS won’t like it.

The complication here is that the requests to the Alfresco server are being sent from Orbeon not directly from the user so although the user is logged into both Orbeon and Alfresco the CMIS requests will not be authenticated.

The way I’ve chosen to do this is to implement a servlet filter to obtain an Alfresco authentication ticket which can then be passed through to Orbeon as part of the request and appended to the CMIS request.

You will see here that the code uses HttpClient 3.1 (because I’m still using Orbeon 3.8) but it should be fairly trivial to upgrade.

I also use JNDI to retrieve the name of the Alfresco service e.g. <Environment name=”alfrescoApp” type=”java.lang.String” value=”https://alfresco/alfresco”/> – you may want to do this differently.

package org.aelfric.demo.security;

import java.io.IOException;

import javax.naming.NamingException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

 * @author iwright
public class AlfrescoCASFilter implements Filter {

  private Log log = LogFactory.getLog(this.getClass());

  public static final String ALFRESCO_TICKET = "alf_ticket";

  public void doFilter(ServletRequest request,
                          ServletResponse response,
                          FilterChain chain)
                       throws IOException, ServletException {
    if (request instanceof HttpServletRequest &&
                        response instanceof HttpServletResponse) {
                        (HttpServletResponse)response, chain);
    } else {
        new ServletException("only HTTP request and responses are
                                         supported by this filter");

  public void doHttpFilter(HttpServletRequest request,
    	           HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
    log.debug("request inbound");

    HttpClient client = new HttpClient();
    String ticket = null;
    try {
	ticket = AlfrescoCASFilter.getAlfrescoTicket(request, client);
    } catch (NamingException e) {
	log.error("Need to set JNDI variable alfrescoApp if using Alfresco", e);
    if (ticket != null) {
	request.setAttribute(ALFRESCO_TICKET, ticket);
    log.debug("alfresco ticket:" + ticket);
    chain.doFilter(request, response);

    log.debug("response outbound");

  public static String getAlfrescoTicket(HttpServletRequest req,
                                                 HttpClient client)
            throws UnsupportedEncodingException, IOException, HttpException,
            ServletException, NamingException {

    HttpSession httpSess = req.getSession(true);

    // Get CAS information
    Assertion assertion = (Assertion) httpSess
    if (assertion == null) {
       return "";
    String username = assertion.getPrincipal().getName();
        // Read out the ticket id
    String ticket = null;
    String alfrescoWebAppURL = LookupJNDI.<String> getEnvEntry(ALFRESCO_WEBAPP_URL_CONFIG);
    if (alfrescoWebAppURL == null) {
       return (null);
    String proxyticket = assertion.getPrincipal().getProxyTicketFor(

    if (proxyticket == null) {
      return (null);
    String casLoginUrl = alfrescoWebAppURL + "/service/api/logincas?u="
                + URLEncoder.encode(username, "UTF-8") + "&t="
                + URLEncoder.encode(proxyticket, "UTF-8");

    GetMethod method = new GetMethod(casLoginUrl);
    method.setRequestHeader("cookie", req.getHeader("cookie"));
    int statusCode = client.executeMethod(method);
    // Read back the ticket
    if (statusCode == 200) {
      InputStream is = method.getResponseBodyAsStream();
      // do something with the input stream
      BufferedReader in = new BufferedReader(new InputStreamReader(is));
      String line;
      String responseText = "";
      while ((line = in.readLine()) != null) {
        responseText += line;
      ticket = responseText;

   } else {
      if (log.isDebugEnabled()) {
        log.debug("Authentication failed, received response code: "
                        + statusCode);
   return ticket;

The next step is to configure the servlet filter in your web.xml for any URLs where you want to proxy authenticate.


Once you’ve done this then the request will contain an attribute with the Alfresco ticket.

Now for the Orbeon part.

For information I hold cmis-rest as a separate model but I’m trying to simplify the examples by leaving that out.

When the model is contructed the requested attribute is held in a control instance.

<xforms:instance id="ins-cmis-rest-control">

<xforms:instance id="ins-cmis-rest">

<!-- Note that this has to be done as part of the
                              xforms-model-construct-done stage -->
<xforms:action ev:event="cmis-rest-get-ticket">
   <xforms:setvalue ref="instance('ins-cmis-rest-control')//ticketAuth"

<xforms:action ev:event="xforms-model-construct-done">
      <xforms:dispatch name="cmis-rest-get-ticket"/>

So now when the submission is sent the Alfresco ticket can be appended to the URL

So the equivalent submission but with proxy authentication is:

 <xforms:submission id="cmis-rest-get-file-record" method="get"
{$alfresco-uri}service/cmis/p/User Homes/
mediatype="application/atom+xml" replace="instance"
instance="ins-cmis-rest-create-file" serialization="none"/>

XForms select using an XML Schema (XSD)

As I’m using schema based validation for my XForms (using Orbeon) I thought it would be a nice idea to generate the select options from the xsd (as well as saving some work!).

As an advanced feature we can also select the value for a second select based on the value of the first.

This is a collection of ideas from different places on the Orbeon wiki and mailing list together with my own thoughts to bring it together.

First the set up:

Load the schema into an instance in this case it’s called study-info-resources – note that this needs to be in a directory where it is not protected by any security – not because of this code but so it can be used for validation.

Next we set up a resources file – this is going to be used for the labels – as well as nice labels we also get multi language support. This resources file will be used to define the relationship between the first and second selects.

 <xforms:instance id="study-info-resources"
    In your XForms model, load resources.xml in an instance.
    Make sure to make that instance read-only and cacheable: this
    way the instance will only be stored once in memory
   (it will be shared by all the users) and using a more efficient
   (because read-only) representation in memory.

    xxforms:readonly="true" xxforms:cache="true"
    <xforms:instance id="all-resources"
    NOTE: Here we point to a local file with the oxf: protocol.
    This is usually yields more performance than using http:,
    because oxf: will reach a local file on disk.
    However, in the online version, we use the http:,
    because we want to load the resource from an online server!

    Define an instance used to store the current language,
       e.g. en or fr.
 <xforms:instance id="language"><language>en</language></xforms:instance>
 <xforms:instance id="iterator"><key></key></xforms:instance>
    Define a variable ($resources), which points to <resources>
       for the current language.
    You will use this variable as a shortcut in your view
       to point to specific resources.
<xxforms:variable name="resources"
select="instance('all-resources')/resource[@xml:lang = instance('language')]"/>

Next write the schema elements

 <xs:simpleType name="tradeName">
     <xs:restriction base="xs:string">
       <xs:enumeration value="" />
       <xs:enumeration value="fred" />
       <xs:enumeration value="bert" />
       <xs:enumeration value="Other" />
 <xs:simpleType name="manufacturer">
   <xs:restriction base="xs:string">
     <xs:enumeration value="" />
     <xs:enumeration value="acme" />
     <xs:enumeration value="ernie" />
     <xs:enumeration value="Other" />

Now we set up the resources to get our labels

 <?xml version="1.0" encoding="UTF-8" ?>
    <resource xml:lang="en">
        <tradeName>Trade Name</tradeName>
                    <tradeName ref="" />
                    <tradeName ref="fred">Frederick</tradeName>
                    <tradeName ref="bert">Albert</tradeName>
                    <tradeName ref="Other">Unlisted</tradeName>
            <manufacturer ref="" tradeName=""></manufacturer>
            <manufacturer ref="fred" tradeName="fred">acme</manufacturer>
            <manufacturer ref="bert" tradeName="bert">ernie</manufacturer>
            <manufacturer ref="Other" tradeName="Other">Other</manufacturer>

Now to write our control – as you can see the itemset is populated by looking at the enumeration values from the schema. Looking up the labels from the resources is slightly trickier (of course you can just use the value from the enumeration as the label and not do this look up)

The xforms-value-changed action is only used for the next part so you can usually leave it out.

<xforms:select1 ref="tradeName" appearance="minimal">
    <xforms:label class="fixed-width" model="mod-study-info"

    <xforms:itemset model="mod-study-info"
         <xforms:label ref="for $currentItemName in @value
             return $resources//tradeName[@ref = $currentItemName]"/>
        <xforms:value ref="@value"/>
    <xforms:action ev:event="xforms-value-changed">

      <xforms:insert ref="instance('binding-control')//rebuild"
      <!--  the rebuild is what should make it work however
                           it's actually the previous statement....
      <xforms:rebuild model="mod-study-dashboard" />

For the final part of this example we are going to create a second select control which is populated based on the value of the first.

Here you can see that if we know the trade name (it’s not ‘Other’) then we can populate the manufacturer based on the mappings held in the resources file. If we don’t know then trade name then this functions just like a normal select box – the only thing necessary to set this up is to create a binding.

The trick to making this work as expected (in Orbeon 3.8) is to use the action specified above – it seems that the insert triggers a model rebuild (if the xforms:rebuild is called then it appears to calculate the binding based on the value of the select prior to the change rather than after the change)

 <xforms:bind nodeset="manufacturer[not(../tradeName = 'Other')]"
            for $currentItemName in ../tradeName
               xxforms:instance('all-resources')//manufacturer[@tradeName = $currentItemName]/@ref
         " />


<xforms:select1 ref="manufacturer" appearance="minimal">  
   <xforms:label class="fixed-width" model="mod-study-info"
   <xforms:itemset model="mod-study-info"
      <xforms:label ref="for $currentItemName in @value
            return $resources//manufacturer[@ref = $currentItemName]"/>
      <xforms:value ref="@value"/>

The binding control instance is just a bit bucket used to trigger the rebuild

  <xforms:instance id="binding-control">
        <bc xmlns="">