On almost every topic
Using CMIS in Alfresco 4.0 Web Scripts

Through an email Jeff Potts commented on my recent post Processing CMIS with Freemarker. In his email Jeff suggested to have a look at the ‘cmis’ root object that is available in Alfresco Community 4.0. I assume it will also be available in the upcoming Alfresco Enterprise 4.0.

Note: Jeff warned that the cmis root object appears to be broken in the current Community release 4c, but it might be fixed in the upcoming release 4d.

Basic Example

To test it in my Alfresco Community 4b release I created a new Web Script in Alfresco Share similar to the one I used to test the approach described in the Freemarker related tutorial. It retrieves a file by path and displays the properties. 

The first step is to create the Web Script descriptor. Create a file called ‘sample-opencmis.get.desc.xml’ with the following contents:

<webscript>
<shortname>Open CMIS example</shortname>
<description>Open CMIS Example</description>
<url>/sample/opencmis</url>
</webscript>

The next step is to create the controller. We start with a simple example to test the root object. It simply retrieves the root folder and adds it to the model. Create a file called ‘sample-opencmis.get.js’ with the following contents:

var cmisConnection = cmis.getConnection();
var cmisSession = cmisConnection.getSession();

folder = cmisSession.getRootFolder();

model.folder = folder;

Finally create the view by adding a file called ‘sample-opencmis.get.ftl’ with the following contents:

<h2>${folder.name}</h2>

Now when you refresh your Web Scripts at http://localhost:8080/share/service/index.html you should see a new Web Script called ‘sample/opencmis’. When you run this script using the URL http://localhost:8080/share/page/sample/opencmis, you should see a page similar to this:

Retrieving a Document

You can also use the cmis root object to retrieve content by path or to execute queries. For example to get a file ‘sample.txt’ located in the Company Home folder, you can add the following lines to the JavaScript controller:

doc = cmisSession.getObjectByPath("/sample.txt");
model.doc = doc;

You can then use the document in your view, for example to print the name and list the properties:

<h2>${doc.name}</h2>
<ul>
<#list doc.properties as p>
<li>${p.definition.displayName}: ${p.valuesAsString}</li>
</#list>
</ul>

This will output the following information:

You can for example also access a number of properties directly like the creationDate, createdBy or versionLabel. To access a property by queryName or id, you can use the following method:

${doc.getPropertyValue("cmis:objectTypeId")}

Next Steps

Within the next couple of days I hope to find some time to further explore the features and limitations of the cmis root object, for example how to execute queries, how to set up a remote connection, or even how to create or update content, folders, properties and aspects.

References

The cmis root object does not seem to be extensively documented in the alfresco documentation. Exploring the documentation of the Alfresco OpenCMIS Extension can be very helpful to lookup the available objects and methods. You can adjust them to meet the conventions of either the JavaScript controller or the Freemarker view.

Updates

  • February 2, 2012: added accessing properties by name.

References

Processing CMIS with Freemarker in Alfresco

Since its release in version 2.1 Alfresco Web Scripts proved to be extremely useful as a framework to build data oriented services and UI Components. They are even used to develop complete application integrations. Thanks to Web Scripts Alfresco was for example able to deliver one of the first CMIS implementations.

Officially Web Scrips are now part of the Spring Surf Framework, but the Spring community never embraced Surf and it will not surprise me if the maintenance and development of the framework returns to Alfresco in the near future. I think the limited tool support also contributed to the lack of success.

I have always been a great fan of Web Scripts. It is a simple yet powerful MVC framework that allows you to build services with just a couple of simple files. You implement the controller using Server Side JavaScript and the view using Freemarker, a very powerful templating language that can output any text oriented data wheter it is HTML, JSON or some XML based format.

Remote Client

In Alfresco Explorer you have direct access to model objects, but with Alfresco Share this is not the case. Alfresco Share is a remote client that requires you to collect data from the Alfresco backend using a service layer. You can write your own backend services with Web Scripts, but you can also use CMIS or one of the other backend services provided out of the box.

The problem with CMIS is that each request returns an XML response and XML and JavaScript are not a great marriage. With the upcoming CMIS 1.1 you can use JSON as an alternative binding. To some extend you can use the Abdera JavaScript client, but Abdera focuses on Atom entries and as far as I know there is no extension that allows easy access to all the CMIS specific properties.

After writing a lot of lines of code in JavaScript (click here for an example from Alfresco’s 3.4 documentation), I got tired of coding and decided to use a more simple approach by consuming the CMIS data using Freemarker. I am aware that it is the responsibility of the controller to deliver an easy to use model to the view, but Freemarker provides proper support for XML including XPath support.

Example Web Script

The following example Web Script shows how you can pass the CMIS response to the view in the controller layer and use the data within the Freemarker template.

The first step is to define a new Web Script in Alfresco Share. Navigate to the ‘tomcat/shared/classes/alfresco/web-extension/site-webscripts’ folder and create the Web Script. A Web Script consists of a Web Script descriptor, an optional JavaScript controller and a Freemarker template for the view. First create a folder ‘samples’ for the example Web Scripts. In this folder create a file called ‘sample-cmis.get.desc.xml’ with the following contents:

<webscript>
<shortname>XML example</shortname>
<description>XML Example</description>
<url>/sample/cmis</url>
</webscript>

The next step is the controller. In the same folder create a file ‘sample-cmis.get.js’ with the following contents:

var connector = remote.connect("alfresco");
var result = connector.get("/cmis/p/sample.txt");
model.doc = stringUtils.parseXMLNodeModel(result.getText());

This script first creates a connection with the Alfresco backend. The connection is then used to execute a CMIS request. The request ‘/cmis/p/sample.txt’ retrieves the object data by path for a file called ‘sample.txt’ located in the Company Home root space. I simply created a plain text file in Alfresco with some dummy content and name, title, author and description properties. The CMIS response is then passed to the Freemarker template as an XML document using the parseXMLNodeModel method available in the root scoped object stringUtils (see here).

In order to retrieve values from the model in Freemarker you can now use the XML document. Create a file called ‘sample-cmis.get.ftl’ and add the following lines:

<#ftl ns_prefixes={ "D":"http://www.w3.org/2005/Atom" }>
<p>${doc.entry.title}</p>

Since CMIS uses namespaces to combine several schema’s, you need to register the prefixes of the namespaces. In the example above only the default ‘atom’ namespace is registered. Freemarker uses a D as a prefix for the default namespace. If you do not register the namespaces, including the default namespace, Freemarker will not retrieve any values and throw an exception.

In order to register the Web Script in Share you can visit http://localhost:8080/share/service/index.html and click the refresh button. If you then visit the page http://localhost:8080/share/page/sample/cmis you should see a page with the name of the document.

Tip: if you set the mode of Share to ‘development’ in ‘surf.xml’ you do not need to refresh the Web Scripts every time you make changes. You can find the file in ‘tomcat/webapps/share/WEB-INF’.

Adding namespaces

In order to, for example, print the icon of the document, we need to add the Alfresco namespace. Freemarker requires the use of square brackets when selecting elements with prefixes because otherwise the colon would confuse the Freemarker engine. The following template outputs the icon and name of the document:

<#ftl ns_prefixes={ "D":"http://www.w3.org/2005/Atom",
"alf":"http://www.alfresco.org" }>
<p><img src="${doc.entry["alf:icon"]}" />${doc.entry.title}</p>

When you revisit the page you should see a page similar to this:

Using XPath

You can also use XPath to select values from the CMIS document. The following template retrieves the Alfresco author property using an XPath expression:

<#ftl ns_prefixes={ "D":"http://www.w3.org/2005/Atom",
"alf":"http://www.alfresco.org",
"cmis":"http://docs.oasis-open.org/ns/cmis/core/200908/" }>

<p><img src="${doc.entry["alf:icon"]}" />${doc.entry.title}</p>
<p>Author: ${doc["//cmis:propertyString[@propertyDefinitionId = 'cm:author']/cmis:value"] </p>

You can parse a date value in order to reformat the date like this:

<p>Updated: ${doc.entry.updated?date("yyyy-MM-dd'T'HH:mm:ss")?string("yyyy-MM-dd HH:mm:ss")}</p>

In order to retrieve the value, a third namespace prefix was registered to select elements from the ‘cmis’ namespace.

Using The List Directive

You can also retrieve multiple propeties using XPath. The following template lists all the CMIS property display labels and values:

<#ftl ns_prefixes={ "D":"http://www.w3.org/2005/Atom",
"alf":"http://www.alfresco.org",
"cmis":"http://docs.oasis-open.org/ns/cmis/core/200908/" }>
<p><img src="${doc.entry["alf:icon"]}" />${doc.entry.title}</p>
 <ol>
<#list doc["//cmis:properties/*/cmis:value"] as p>
<li>${p?parent.@displayName}: ${p}</li>
</#list>
</ol>

In order to include the properties of aspects, you can for example use the XPath local-name() function:

<#list doc["//*[local-name() = 'properties']/*/cmis:value"] as p>
<li>${p?parent.@displayName}: ${p}</li>
</#list>

When you revisit the page, the result should look simliar to this:

Building a model

To make things easier to process in your template you can write a function that returns a map of name and propety values. You can then use the map as you are used to in backend Web Scripts. The following function retrieves the properties and adds them to a map using the property name as a key:

<#function properties doc>
<#assign s = "{"> <#list doc["//*[local-name() = 'properties']/*/cmis:value"] as p>
<#assign s = s + "\"${p?parent.@propertyDefinitionId}\":\"${p}\"">
<#if p_has_next> <#assign s = s + ","> </#if> </#list>
<#assign s = s + "}">
<#return s?eval>
</#function>

This is just a basic function that works fine for non-repeatable fields. You can execute the function and use the properties for example in a list directive:

<#assign props = properties(doc)>
<ol>
<#list props?keys as key>
<li>${key}: ${props[key]}</li>
</#list>
</ol>

You can of course also get individual properties by property name. The following line outputs the description of the document:

<p>Description: ${props["cm:description"]}</p>

The following listing shows the complete Freemarker template using the function:

<#ftl ns_prefixes={ "D":"http://www.w3.org/2005/Atom",
"alf":"http://www.alfresco.org",
"cmis":"http://docs.oasis-open.org/ns/cmis/core/200908/" }>
<#function properties doc>
<#assign s = "{">
<#list doc["//*[local-name() = 'properties']/*/cmis:value"] as p>
<#assign s = s + "\"${p?parent.@propertyDefinitionId}\":\"${p}\"">
<#if p_has_next>
<#assign s = s + ",">
</#if>
</#list>
<#assign s = s + "}">
<#return s?eval>
</#function>
<p><img src="${doc.entry["alf:icon"]}" /> ${doc.entry.title}</p>

<#assign props = properties(doc)>
<ol>
<#list props?keys as key>
<li>${key}: ${props[key]}</li>
</#list>
</ol>

When you visit the example page again you will see a listing of all the property names and values:

Conclusion

Although from a design point of view this approach might not be perfect, it provides a means to consume CMIS responses in just a couple of lines of code. If you have other suggestions to consume CMIS documents in Web Scripts, please let me know.

The Learning by Example page from the Freemarker Manual can be a useful resource when processing XML documents with Freemarker.

Updates

  • Made some minor updates on January, 26

References

Spring Surf with an Alfresco backend

Spring Surf is actively under development. Recently authentication against Alfresco was added to the Surf Quick Start application making it very simple to add an Alfresco backend to your Surf application. To get an idea in what direction this is heading to, I added a page to the example application that displays blog posts from Alfresco Share. The page requires authentication.

Note: this tutorial demonstrates Spring Surf features that are not stable yet.

Environment

I have an Alfresco Enterprise 3.2r backend running on http://localhost:8080/alfresco and will run Jetty on my Surf project. I guess it will also work with Alfresco Community. Make sure that you have Maven installed.

Download Spring Roo

The first step is to download and install Spring Roo from the Spring Source Community download page at http://www.springsource.com/download/community. Spring Roo is a rapid application development tool for Java developers focusing on productivity and ease of use.

The next step is to download the latest snapshot for the Spring Surf Roo Addon from http://www.springsurf.org/downloads.html. Of course you can also create a new build. Check the Spring Source Development Guide for instructions on how to do this. In order to build from source you need a Subversion client and Maven. Add the snapshot for Roo to the dist directory of your Roo installation (on my Windows machine it is C:\Apps\spring-roo-1.0.2.RELEASE\dist). It might be useful to open the Surf Roo Command Index as a reference.

Create a project

We are now ready to create a new project with Roo. From the command line navigate to a directory where you want to create your application, create a new directory for your Surf application and start the Roo shell:

c:\projects>mkdir surf-alfresco

c:\projects>cd surf-alfresco

c:\projects\surf-alfresco>roo

Your Roo shell looks similar to this:

We are now ready to start coding. First create a new project:

roo>project --topLevelPackage com.example.surf

Tip: roo supports completion using the TAB key, so if you type project and then TAB roo will suggest to add the topLevelPackage argument.

Now install Surf:

roo>surf install

When you install Surf, Roo creates an example application to get you started. We will add authentication to this application and a new page showing blog posts from an Alfresco Share site called Company.

Enable authentication

In order to to enable authentication against the Alfresco repository, open the file surf.xml in the src/main/webapp/WEB-INF directory and comment out the following line:

<user-factory>webframework.factory.user.alfresco32</user-factory>

In addition I made some changes to the file login.ftl in the src/main/webapp/WEB-INF/templates/sample directory. I changed these lines:

<input name="success" type="hidden" value="/"/>
<input name="failure" type="hidden" value="/type/login"/>

To:

<input name="success" type="hidden" 
  value="${url.context}/sample/userinfo"/>
<input name="failure" type="hidden" 
  value="${url.context}/sample/login"/>

This will show the user information on a successful login and the login page when the login is not successful. The templates for login, logout and the user information are already added as example templates.

Test the application

You can now test the application. To do this exit roo and run Jetty:

roo>exit
c:\apps\surf-allfresco>mvn jetty:run

Make sure Alfresco is also running and visit the Surf application by visiting http://localhost:8180/

You should see the following page. This is the example application we created by installing Surf:

Now visit the page http://localhost:8180/sample/login. You should see a page like this:

Type an Alfresco user name and password en click Log In. The system should now display the login details.

You are now able to authenticate, so the next step is to add a page that requires the user to login. To stop Jetty you can simple type Ctrl-C.

Note: you are not required to stop Jetty, you can also open a new command shell. Jetty will notice changes and do a reload.

Create a new component

We start with creating a new Surf component. Surf components basically are Web Scripts. If you are not familiar with Web Scripts, you might want to read some documentation first. You can find it here.

First we create a folder called posts under the WEB-INF/webscripts directory. We then create a new file called posts.get.desc.xml with the following content:

<webscript>
  <shortname>Company Posts</shortname>
  <description>Company Posts</description>
  <url>/news/posts</url>
  <authentication>user</authentication>
</webscript>

This is the descriptor for our new component. It provides a name and description and a URL to provide access to the resource. We also set the authentication to user, since we require the user to be authenticated when he/she requests blog posts. By default authentication is set to none.

The next step is to create the controller. The controller knows what to do when the user requests the resource (in this case showing the blog posts stored in Alfresco). The controller is implemented using JavaScript. Create a file called posts.get.js with the following contents:

var connector = remote.connect("alfresco");
var result = connector.get("/api/blog/site/company/blog/posts");
logger.log(result);
var posts = eval('(' + result + ')');
model.posts = posts;

The connector’s get method retrieves the blog posts from a site called company. You can change company with the name of any Alfresco Share site. If you do not have a site yet, you can create one and add some blog posts to it.

The final part of the component is the view. The Web Scripts Framework uses Freemarker as the default template engine. Create a file called posts.get.html.ftl and add the following contents:

<div>
<#if posts.items?exists>
  <#list posts.items as post>
    <h2>${post.title}</h2>
    ${post.content}
  </#list>
<#else>
There are no posts.
</#if>
</div>

I must admit that this template is not going to return a stunning web page, but for now it will work just fine.

One final change I made is to forward the user to the news page on a succesful login in stead of the user information by editing the login.ftl once more:

<input name="success" type="hidden" value="${url.context}/news" />

Create a new page

We now have to revisit Roo to create a new page, add the required components to the page including our blog posts component and to add the page to the site navigation. To do this start Roo and first create the page:

roo> surf page create --id news --template home

We create a new page based on the existing template for the Home Page. Next we add the blog posts to the main region of the page:

roo> surf component create --page news --region main
  --url /news/posts

We can then run a report to see if we need to add addditional components:

roo> surf report page --id news
-----------------------------------------------------------
Report on Page news

-----------------------------------------------------------
Basic Information

Id: news
Name: news
Path: pages\news\news.xml
Instance: home
Template: home
-----------------------------------------------------------
Page Scoped Components

Region: main Url: /news/posts
Region: side Scope: page Configued: false

-----------------------------------------------------------
Template Scoped Components

Region: header Url: /company/header
Region: horznav Url: /navigation/horizontal
Region: footer Url: /company/footer

-----------------------------------------------------------
Global Scoped Components

-----------------------------------------------------------
Page Associations

-----------------------------------------------------------

It seems that the component for the side region is missing, so we simply add the same component as the one used for the home page. I simply looked it up in the file pages/home/home.xml and it is the component /home/side:

roo> surf component create --page news --region side 
  --url /home/side

The last thing we need to do is to add our new page to the horizontal navigation by creating an association between the page home and our new page called news:

code>roo> surf page association create --sourceId home 
  --destId news

We can now exit Roo:

roo>exit

Before starting Jetty again, visit the page news.xml and set authentication to user instead of none. Save the file and run Jetty again.

c:\projects\surf-alfresco>mvn jetty:run

Test the new page

Now test the application by visiting http://localhost:8180 again. You should see a news button added to the horizontal navigation:

When you click the news page, the system shows the login page again and returns to the news page on a successful login:

We now have added a page to Surf’s Quick Start application that enables the user to authenticate against Alfresco and read blog posts stored in the backend repository.

Conclusion

Spring Surf and Spring Roo provide a very promising development approach enabling the Java developer to focus on getting things done without having to create huge amounts of code and a lot of configuration files. The built-in support for Alfresco makes Surf a perfect framework to build your Alfresco front-end application. With the upcoming CMIS (Content Management Interoperability Services) standard we will even have a standard interface to access content repositories.