Category: Alfresco Developer Series

The Alfresco Developer Series is a set of articles aimed at getting you up-to-speed on the Alfresco platform.

Alfresco Developer Series tutorial source code now on github

The source code for the tutorials in my Alfresco Developer Series has always been available to download as a zip. But for some reason I never put it in a project where we could collaborate on it. That’s fixed now. The code’s now on github. (Note that the source code that accompanies the Alfresco Developer Guide is on Google Code. I don’t intend to maintain that going forward and will instead focus on these github projects).

As part of that I’ve made sure that the content types, behaviors, actions, web scripts, and workflow tutorial code works on 4.0.d and 4.2.c. The original zips referenced in the tutorial PDF still work with the versions they were written for, of course, but if you grab the source from github, they’ll work on the version they are tagged for.

One thing I’ve realized as part of this is that with the actual tutorials in PDF, keeping the written instructions in sync with the code is tough. Maybe I should convert the tutorial text into markdown or something similar and check that into the source code repo as well. Let me know what you think about that idea.

Next step for the code is to convert from the old Ant-based Alfresco SDK to the new Maven-based SDK.

Alfresco Example: Share Dashlet Part Two–Configuration

In my last post I showed a simple example that illustrates the “repository tier data web script/share tier presentation web script” pattern that is used any time you need to create a dashlet in Alfresco Share that reads data from the Alfresco repository. The example I used is called “Get Latest Document” and it does just that–given a folder path, it reads some basic metadata about the most recently modified document and displays it in a dashlet.

That example read the folder path from an XML configuration file that is included as part of the Share tier web script. But what if you wanted to make it easier to configure the dashlet by allowing a Share user to open up a configuration dialog that includes a folder picker? Luckily, Alfresco Share already includes all of the bits and pieces you need to make this possible–it’s just up to you to wire them together. I’ll show you how to do that in this post.

The code that implements this example lives in a Google Code project. I’ve tagged the prior post’s source code–the “XML configuration” code–as “1.0“. The code that goes along with this post is tagged as “2.0“. So if you are following along make sure you are using the appropriate code set.

I’m using Alfresco 4.0.d Community, WAR-only distribution, Lucene for search, two Tomcats, and MySQL. My project is organized following the Share Extras Sample Dashlet project folder structure.

Here’s the Recipe

The goal is to take the 1.0 version of the Get Latest Document dashlet and make it configurable through the UI instead of an XML configuration file. Recall from the prior post that we have a repository tier web script that returns JSON for the most recently modified document in a specified folder path. To make that folder path configurable, nothing at all needs to change on the repository tier. All of the changes are going to take place on the Share tier.

Here’s what has to be created or changed to make this work:

  1. Modify the dashlet markup to include a configuration link
  2. Create a custom client-side JavaScript component to handle the configuration dialog and the folder picker
  3. Write a new Share-tier web script that persists the configuration data

Not too bad, right? Well let’s get after it then.

Modify the dashlet markup to handle configuration

In a minute I’m going to show you the code for the client-side JavaScript component that listens for configuration clicks. For now, I’ll just point out where that client-side object is instantiated within the dashlet’s markup. It is near the top of get-latest-doc.get.html.ftl:

var getLatestDoc = new SomeCo.dashlet.GetLatestDoc("${el}").setOptions(
  "componentId": "${}",
  "siteId": "${!""}",
  "title": "${title}",
  "filterPath": "${filterPath}",
  "filterPathView": "${filterPathView}"

Notice the “SomeCo” object. When creating new client-side objects, you definitely want to steer clear of the “Alfresco” object if you can so that your stuff doesn’t collide with Alfresco’s stuff.

Next, I need an “edit” icon in the dashlet’s title bar. I want it to appear only if the user is a site manager. So I’m going to add a little blurb to the get-latest-doc.get.html.ftl view that does this:

var editDashletEvent = new YAHOO.util.CustomEvent("onDashletConfigure");
                           getLatestDoc, true);
new Alfresco.widget.DashletTitleBarActions("${args.htmlid?html}").
    <#if userIsSiteManager>
      cssClass: "edit",
      eventOnClick: editDashletEvent,
      tooltip: "${msg("dashlet.edit.tooltip")?js_string}"

The first part of this code hooks a YUI “onDashletConfigure” event to the “onConfigGetLatestDocClick” handler in the custom GetLatestDoc client-side JavaScript object. The second part is a FreeMarker conditional that is checking the value of “userIsSiteManager”. The controller will set that value. I’ll show you that shortly. The rest of the view is unchanged from the 1.0 version.

The dashlet needs access to the custom client-side JavaScript component as well as some of Alfresco’s out-of-the-box components that I will leverage to open a dialog and to present a folder picker. I’ve added these to get-latest-doc.get.head.ftl:

<!-- getLatestDoc -->
<@link rel="stylesheet" type="text/css"
  href="${page.url.context}/res/extension/components/dashlets/get-latest-doc.css" />
<@script type="text/javascript"
<!-- Simple Dialog -->
<@script type="text/javascript"
<!-- Global Folder Select -->
<@link rel="stylesheet" type="text/css"
  href="${page.url.context}/modules/documentlibrary/global-folder.css" />
<@script type="text/javascript"

Now take a look at the dashlet’s controller, get-latest-doc.get.js. The biggest change here is to add a call to the repository to find out if the current user is a site manager:

var userIsSiteManager = false,
json ="/api/sites/" + +
  "/memberships/" + encodeURIComponent(;
if (json.status == 200)
  var obj = eval('(' + json + ')');
  if (obj)
    userIsSiteManager = (obj.role == "SiteManager");
model.userIsSiteManager = userIsSiteManager;

The rest of the controller is pretty much the same as 1.0, with the minor addition of checking “args” for values that the configuration service is going to pass in. If they don’t get passed in, the values will be read from the config XML as they were in 1.0.

That’s it for the changes to the dashlet. If you wanted to you could deploy at this point, but clicking the edit button would result in JavaScript errors.

Create a custom client-side JavaScript component

Client-side JavaScript for this example lives in source/web/extension/components in a file called dashlets/get-latest-doc.js. The “source/web” part of the path is dictated by the Share Extras sample project folder layout. I used “extension” to keep my client-side static assets separate from Alfresco’s. You might choose something more unique.

I’m not going to go line-by-line–look at the source for the full detail. The first thing worth noting is at the very beginning of the file: It’s a declaration of the “SomeCo” object. The client-side object I define in this file will live in that namespace. If I had other custom client-side objects I’d declare them as part of that namespace as well. I’ve seen a lot of examples that place their custom client-side objects in the “Alfresco” namespace, which is a bad habit. There’s nothing magical about that Alfresco namespace, so why not make it obvious what’s part of the product and what’s a customization?

if (typeof SomeCo == "undefined" || !SomeCo)
  var SomeCo = {};
  SomeCo.dashlet = {};

Next comes the declaration of the constructor for this new object:

SomeCo.dashlet.GetLatestDoc = function GetLatestDoc_constructor(htmlId)
    "SomeCo.dashlet.GetLatestDoc", htmlId);
   * Register this component
   * Load YUI Components
  Alfresco.util.YUILoaderHelper.require(["button", "container",
    "datasource", "datatable", "paginator", "json", "history",
    "tabview"], this.onComponentsLoaded, this);
  return this;

After calling the superclass’ constructor, I ask the Alfresco ComponentManager to register the class. Then, I use Alfresco’s YUILoaderHelper to declare the components on which my component depends.

After that, the actual definition of the object begins. My GetLatestDoc object is going to extend Alfresco’s Base object, so I use YAHOO.extend to make that happen:

YAHOO.extend(SomeCo.dashlet.GetLatestDoc, Alfresco.component.Base,

What follows are the properties and methods of the GetLatestDoc object. The two big things it takes care of are (1) Responding to the “Configure” click and (2) Displaying the folder picker dialog.

The first method is the onConfigGetLatestDocClick. You’ll remember that from the updates to the view–I hooked up the “configure” link to this method. Here is the declaration followed by specifying the actionUrl. The actionUrl is where the configure form will be posted. In this case it is a web script I’ll walk you through in the next section.

onConfigGetLatestDocClick: function getLatestDoc_onConfigGetLatestDocClick(e)
  var actionUrl = Alfresco.constants.URL_SERVICECONTEXT +
    "modules/someco/get-latest-doc/config/" +

The onConfigGetLatestDocClick method does two things: (a) It defines the dialog that gets displayed when someone configures the dashlet and (b) it defines field validation for the fields on the configure dialog. Here is the dialog definition part:

That templateUrl is where the SimpleDialog module should find the form to use. It looks just like the actionUrl and it is. The actionUrl will be a POST while the templateUrl will be a GET.

The getLatestDoc_onConfig_callback function will be invoked when the configuration form is successfully posted to the config web script. That response object contains the response from that web script, which, in this case, we are returning as JSON.

Here is the part of the method that defines field validation:

This function makes the title mandatory. Note the final two assignments. These are hooking up buttons on the config dialog to events in this client-side component. So, when someone clicks “select path” the folder picker will be launched and when someone clicks “clear path” the selected path will be reset.

Then, the final part of the method simply displays the dialog:

  actionUrl: actionUrl,
  siteId: this.options.siteId,
  containerId: this.options.containerId

So when this method is invoked, Alfresco’s out-of-the-box SimpleDialog component is used to display a pop-up dialog. The dialog will contain the form that we return in the config’s GET web script, and when the user saves the values, the values will be POSTed to the config web script.

As part of the configuration, the user needs to specify a folder path. Alfresco already ships with a folder picker–there is no need to code one from scratch.  The onSelectFilterPath method sets that up:

This method uses the out-of-the-box DoclibGlobalFolder to present a tabbed dialog of folders for the user to navigate and pick. When someone selects a folder, it throws a “folderSelected” event which this code listens for. When it hears it, it grabs the selected folder and nodeRef to save for later.

I’m not sure why Rik, my partner in crime for this little example, chose to append the selected path to the end of the nodeRef with a pipe. It could easily be stored in its own property.

Now, at this point, a logical question in your mind might be, “SimpleDialog and DoclibGlobalFolder look generally useful. How do I find out more about those and other goodies that might be available to my client-side JavaScript in Share?”. The answer is JSDoc. The Share Extras project has generated the JSDoc for all client-side JavaScript in Alfresco. The index for Alfresco 4.0.d lives here, the doc for DoclibGlobalFolder lives here, and the doc for SimpleDialog lives here.

With this client-side JavaScript in place, the “configure” link can now be clicked, but the SimpleDialog will be looking for a config web script that doesn’t exist yet. That’s the last step.

Write a Share-tier web script to handle config

In the previous section you saw that the SimpleDialog needs two web scripts: One returns a form that is rendered in the dialog. The other is the web script that dialog will POST to. These web scripts are Share tier web scripts, so they live in config/alfresco/site-webscripts. The com/someco package structure is used to keep code separate from other add-ons, and, by convention, web scripts that aren’t surf components go under “modules”. Under that I’m using “getLatestDoc” to group web scripts related to that and “config” below that to identify the purpose of these web scripts.

First, the GET web script. It’s kind of boring. There is no controller at all. The web script consists only of a FreeMarker view, a descriptor, and some properties files to localize the labels on the form. If you look at the view, config-get-latest-doc.get.html.ftl, you’ll see what I mean. It doesn’t even need any client-side JavaScript–the buttons were hooked up to methods on the GetLatestDoc component in the prior step.

Next, the POST web script. The SimpleDialog component will be sending JSON representing the form data to this web script. Because it is sending JSON, the web script controller is named That extra little “.json” bit gives me access to the form data in a “json” root-scoped object so I don’t have to fool around with eval.

The logic itself is pretty simple:

var c = sitedata.getComponent(url.templateArgs.componentId);
var saveValue = function(name, value)
{[name] = value;
  model[name] = value;
saveValue("title", String(json.get("title")));
saveValue("filterPath", String(json.get("filterPath")));
saveValue("filterPathView", String(json.get("filterPath")).split("|")[1]);;

What’s going on here? First, the controller grabs a handle to a component using a componentId. The component ID was passed in as an argument by the client-side JavaScript component that told the SimpleDialog which action URL to use. The client-side JavaScript component got the component ID when the dashlet’s view (get-latest-doc.get.html.ftl) instantiated it. So this component is actually the web script that renders the Get Latest Document dashlet.

The saveValue function is just a little helper that sets the properties on the component and the model in one call.

So, given the “json” object that is being passed in from the configuration dialog, all that needs to be done is to read those form field values out of the JSON and stick them onto the component properties and the model.

Now, when the dashlet’s web script is invoked, the framework will pass those properties to it via the args array. If the dashlet’s controller sees the values in the args array, it uses those, otherwise, it uses what it finds in the XML configuration.

Deploy and Test

You can deploy the example by running “ant hotcopy-tomcat-jar”. If you already deployed 1.0 of the code and you are running two Tomcats, you won’t have to restart your repository tier, but you will have to restart your Share tier. Then, go into a site and add the dashlet to the site dashboard. If you click the pencil icon on the dashlet’s title bar, you should see the configuration form pop up:

If you then click “Select Path” the folder browser should be displayed:

On clicking “OK” the new configuration values will be persisted, but you’ll have to refresh the page to see them take effect. Of course you could modify the example further to move the rendering of the metadata to the client-side such that when the configuration data is saved it immediately refreshes the dashlet content, but I’ll save that for another time.

Alfresco Example: Share Dashlets that Retrieve Data from the Repository

If you need to learn how to write an Alfresco Share dashlet, hopefully you’ve already worked through the Hello World dashlets in the Share Extras project on Google Code. The rest of the dashlets in that project are either “mash-up” style dashlets that read data from third-party sites or dashlets that work with data from the Alfresco repository tier, but are of moderate to high complexity. What I think is missing is a dashlet that goes one small step beyond Hello World to show how to read and display a simple set of data from the repository tier. In this post I show you how to do just that.

I created the example I’m going to walk you through in response to a question someone posted in the forum. They asked, “How can I write a dashlet that will show basic metadata from the most recently-modified document in a given folder?”. I think this is something we haven’t explained to people–we show Hello World and we show dashlets from the other end of the spectrum, but nothing to illustrate this basic pattern. So I wrote a quick-and-dirty example. Fellow forum user, RikTaminaars, also got in on the act, making the dashlet configurable, which I’ll show in a subsequent post.

In this post, I’ll create the most basic implementation possible. The result is a simple dashlet that reads a path from a configuration file, asks the repository for the most recently modified document in that folder, then displays some basic metadata. In my next post, I’ll add to it by making the folder path configurable within the user interface.

Developer Setup

First, a bit about my setup. I’m running Alfresco 4.0.d Community, WAR distribution, Lucene for search, Tomcat application server, and MySQL for the database. I’m using Eclipse Indigo, but this implementation requires no compiled code. For organizing the project files I used the Sample Dashlet project structure from Share Extras. I’m using the Share Extras Ant build script to deploy my code from my project folder structure to the Alfresco and Share web applications.

When I’m doing Share customizations I use two Tomcats–one for the repository tier and one for the Share tier. This helps me avoid making assumptions about where my Alfresco and Share web applications are running and it speeds up my development because my Share Tomcat restarts very quickly. To get the Share Extras build script to work with a two Tomcats setup, I’ve added the following to a file in my home directory:


Now the build script will know to put the deployed code in each of my Tomcat servers.

The Data Web Script/Presentation Web Script Pattern

The Alfresco repository runs in a web application called “alfresco” while the Share user interface runs in a separate web application called “share”. Each of these two web applications has its own web script engine. If you aren’t familiar with web scripts, take a look at this tutorial, then come back, or just accept the high-level notion that web scripts are an MVC framework used to bind URLs to code and that web scripts can run on the repository tier as well as the Share tier.

Share dashlets–the “boxes” of content that display in the Share user interface–are just web scripts that return HTML. In fact, everything you see in Share is ultimately a web script. When a dashlet needs to display data from the Alfresco repository, it makes a call over HTTP to invoke a web script running on the repository tier. The repository tier web script responds, usually with JSON. The dashlet gets what it needs from the JSON, then renders outputs HTML to be rendered as part of the page. Because the repository tier web script responds with raw data, you may see these referred to as “data web scripts”.

In the previous paragraph, I was purposefully vague about where the request to the repository tier is made. That’s because there are two options. The first option, and the one we’ll use in this example, is to make the call from the dashlet’s web script controller. This might be called “the server-side option” because once the dashlet’s view is rendered, it has all of the data it needs–no further calls are needed.

The second option is to make AJAX calls from the client browser. To avoid cross-site scripting limitations, these calls typically go through a proxy that lives in the Share application, but their ultimate destination is the repository tier.

Two tier web scripts

You may be wondering about the details of making these remote connections. It’s all taken care of for you. Regardless of whether you make the remote invocation of the repository web script from the Share tier or through AJAX in the browser, all you need to specify is the URL you want to invoke and the framework handles everything else.

Show Me the Code: Repository Tier

Let’s walk through the code. I’ll start with the repository tier. Recall that the requirements are to find the most recently modified document in a given folder and return its metadata. There may be out-of-the-box web scripts that could be leveraged to return the most recently modified document, but this is actually very simple to do and I don’t want to have to worry about those out-of-the-box web scripts changing in some subsequent release, so I’m implementing this myself.

Using the Share Extras project layout, repository tier web scripts reside under config/alfresco/templates/webscripts. The best practice is to place your web script files in a package structure beneath that, so I am using “com/someco/components/dashlets” for my package structure. Yours would be different.

The first thing to think about is what the URL should look like. I want it to be unique and I need it to accept an argument. The argument is the folder path to be searched. For this example, my URL will look like this:


If you’ve worked with web scripts, you know that a “path” pattern could be followed instead of a “query string” pattern but it doesn’t really matter for this example. The descriptor, get-latest-doc.get.desc.xml, declares the URL and other details about authentication and transaction requirements.

The controller performs the search and populates the model with data. This is a GET, so the controller is named get-latest-doc.get.js. Look at the source for the complete listing–I’ll just hit the high points.

First, I grab a handle to the folder represented by the path argument:

var folder = companyhome.childByNamePath(args.filterPathView);

Then I use the childFileFolders() method to get the most recently modified file and stick that in the model:

var results = folder.childFileFolders(true, false, 'cm:folder', 0, 1, 0, 'cm:modified', false, null);
model.latestDoc = files[0];

Obviously, I could have used a search here, but this method is quite handy. It must be new (thanks, Rik!).

The view then takes the data in the model and returns some of the metadata as JSON:

<#macro dateFormat date>${date?string("dd MMM yyyy HH:mm:ss 'GMT'Z '('zzz')'")}</#macro>
<#escape x as jsonUtils.encodeJSONString(x)>
"nodeRef": "${latestDoc.nodeRef}",
"name": "${}",
"title": "${!}",
"description": "${!}",
"created": "<@dateFormat />",
"modified": "<@dateFormat />"

Note the exclamation points at the end of the title and description. That will keep the template from blowing up if those values are not set.

That’s all there is to the repository tier. If you want to add additional metadata, custom properties, or data from elsewhere in the repo, it is easy to do that.

At this point you should be able to deploy (run ant hotcopy-tomcat-jar, for example) and test the repository tier web script by pointing your browser to: http://localhost:8080/alfresco/s/someco/get-latest-doc?filterPathView=/Some/Folder/Path

Show Me the Code: Share Tier

Okay, the back-end is ready to return the data I need. Now for the front-end. The Share Extras project structure puts front-end web scripts in config/alfresco/site-webscripts so following a similar pattern as I did for the repository-tier web scripts, I put my share-tier web scripts into the site-webscripts folder under com/someco/components/dashlets.

The descriptor, get-latest-doc.get.desc.xml, declares a URL for the dashlet and specifies the “dashlet” family. This will make the dashlet appear in the “add dashlets” menu for both the global dashboard and the site dashboard.

I want to make the folder path configurable, so I created get-latest-doc.get.config.xml and used it to specify a title for the dashlet and the default folder path. I’ll read in this configuration from the controller.

As I mentioned, we’re doing everything server-side in this example, so the controller needs to call the web script I deployed to the repository tier to retrieve the JSON. Then it can put that object into the model and let the view format it as it sees fit. The controller lives in get-latest-doc.get.js and starts out by reading the configuration XML:

Then it uses the built-in “remote” object to invoke the repository tier web script and puts the result into the model:

Note that the URL starts with my web script’s URL–it includes nothing about where to find the Alfresco repository. That’s because the “end point” is declared in Share’s configuration (to be precise, it is actually Surf configuration, the framework on which Share is built) and the remote object uses the “alfresco” endpoint by default. I don’t see it used very often, but you can actually define your own end points and invoke them using the remote object.

The last part of this example is the HTML markup for the dashlet itself. The first half of get-latest-doc.get.html.ftl is boilerplate that has to do with the dashlet resizer. For this example, the length of the list is static–it will only ever have one entry. So the resizer is kind of overkill. The bottom half is where the markup for the document’s metadata lives:

If you’ve already worked with web scripts, you know that get-latest-doc.get.head.ftl is used to place resources into “<head>”. In this case, that is a CSS file used to style our dashlet and client-side JavaScript used by the resizer. The strings used in the dashlet are localized through the file.

Test It Out

You should be able to test this out yourself by creating a folder anywhere in the repository, adding one or more files to the folder, specifying that folder path in the get-latest-doc.get.config.xml file, and then using “ant deploy hotcopy-tomcat-jar” to deploy the customizations to the alfresco and share web applications. You’ll need to restart Tomcat to pick up the new JAR (both Tomcats if you are running two). Then, login and click “Customize Dashboard” to add the “Get Latest Document” dashlet to your dashboard. It should look something like this:

Screenshot: Get Latest Document Dashlet


This is a simple example, but it is powerful because it is the same pattern used throughout Share: A dashlet needs data from the repository tier, so its web script controller uses the “remote” object to call a web script on the repository tier. The repository tier web script returns JSON which the Share tier web script then formats into a nice looking dashlet.

In my next post, I’ll show how to make the folder path configurable, so that you can change it at run-time with a folder picker in the Share user interface instead of editing the config XML.

Alfresco tutorial: Advanced Workflows using Activiti

In 2007, I wrote a tutorial on Alfresco’s advanced workflows which I later used as the basis for the workflow chapter in the Alfresco Developer Guide. It showed examples using jBPM and the old Alfresco Explorer web client.

Then, in April of 2011 I posted a short article comparing Alfresco workflows built with jBPM to the same workflows built with Activiti, the new advanced workflow engine embedded in Alfresco 4. The article provided a quick glimpse into the new Activiti engine aimed at those who had heard about the Alfresco-sponsored project.

Today I’m making available the 2nd edition of the advanced workflow tutorial. It combines the SomeCo whitepaper example from 2007 with a few hello world examples to show you how to use the Activiti Process Designer Eclipse plug-in and the Activiti engine to design and run the example workflows, including how to configure your workflows in the Alfresco Share web client.

The accompanying source code builds on the workflow model and associated customizations created in the 2nd editions of the custom content types and custom actions tutorials.

UPDATE 7/18/2013: Thanks to a user on #alfresco who reported a bug in the sample workflows that have a UI. None of those workflows could be started in Alfresco Community Edition 4.2.c. I have corrected the bug. So if you are using 4.2.c, please use this zip instead.

Special thanks go to Joram Barrez and Tijs Rademakers for reviewing the tutorial and providing valuable feedback. Both are on the Activiti team. In fact, Tijs has been working on an Activiti book called Activiti in Action which should be out soon, so keep an eye out for that.

Anyway, take a look and let me know what you think.

Alfresco Tutorial: Custom actions including Share configuration

I’ve published a revision of my original Alfresco custom actions tutorial. The second edition greatly expands on the first by adding a UI action example. The original included only a rule action example. Just like the second edition of the content types tutorial, I’ve added instructions on how to configure the actions in Alfresco Share. The Alfresco Explorer steps are still there–they’ve been moved to the Appendix.

The code that accompanies the tutorial builds on the content types tutorial, so it includes the SomeCo content model and the user interface configuration needed to expose that to the Alfresco Share and Alfresco Explorer user interface.

This should be helpful to anyone who read the first edition who now wants to learn how to do the same thing using Alfresco Share, including some of the new extension points available in Alfresco 4.

Take a look and tell me what you think.

Alfresco tutorial: Custom content types including Share config and CMIS

UPDATE (2014): I’ve moved the tutorial and the source code to GitHub. The HTML version of the tutorial is here. It has been updated for Maven and AMPs.

It is hard to believe that the original version of my “Working With Custom Content Types” tutorial for Alfresco is almost five years old. That page has had over 37,000 unique visits since it was posted. It makes sense that it would be popular–creating a content model, exposing it to the user interface, and then performing CRUD functions against the repository through code are the first steps for most Alfresco development projects.

The fundamentals of content modeling haven’t changed since 2007, but since the original tutorial was posted the Alfresco Share web client has replaced Alfresco Explorer as the preferred user interface and the Content Management Interoperability Services (CMIS) API has become the first choice for writing remote code against the repository. That, combined with the influx of newcomers to the platform and a continued demand for how-to’s on the basics motivated me to revise the tutorial.

The second edition moves the Alfresco Explorer configuration to the Appendix and replaces it with steps for doing the same thing in Alfresco Share. I also moved the Java Web Services API to the Appendix and replaced that with Java examples that leverage the Apache Chemistry OpenCMIS API to create, update, query, and delete content in the repository. I’m executing the same queries as the first edition, just implemented using CMIS, so if you want to compare Lucene queries to CMIS Query Language, this is one place to do it.

I tested the document and the %

New Tutorial: Getting Started with CMIS

I’ve written a new tutorial on the proposed Content Management Interoperability Services (CMIS) standard called, “Getting Started with CMIS“. The tutorial first takes you through an overview of the specification. Then, I do several examples. The examples start out using curl to make GET, PUT, POST, and DELETE calls against Alfresco to perform CRUD functions on folders, documents, and relationships in the repository. If you’ve been dabbling with CMIS and you’ve struggled to find examples, particularly of POSTs, here you go.

I used Alfresco Community built from head, but yesterday, Alfresco pushed a new Community release that supports CMIS 1.0 Committee Draft 04 so you can download that, use the hosted Alfresco CMIS repository, or spin up an EC2 image (once Luis gets it updated with the new Community release). If you don’t want to use Alfresco you should be able to use any CMIS repository that supports 1.0cd04. I tried some, but not all, of the command-line examples against the Apache Chemistry test server.

Once you’ve felt both the joy and the pain of talking directly to the CMIS AtomPub Binding, I take you through some very short examples using JavaScript and Java. For Java I show Apache Abdera, Apache Chemistry, and the Apache Chemistry TCK.

For the Chemistry TCK stuff, I’m using Alfresco’s CMIS Maven Toolkit which Gabriele Columbro and Richard McKnight put together. That inspired me to do my examples with Maven as well (plus, it’s practical–the Abdera and Chemistry clients have a lot of dependencies, and using Maven meant I didn’t have to chase any of those down).

So take a look at the tutorial, try out the examples with your favorite CMIS 1.0 repo, and let me know what you think. If you like it, pass it along to a friend. As with past tutorials, I’ve released it under Creative Commons Attribution-Share Alike.

[Updated to correct typo with Gabriele’s name. Sorry, Gab!]

Alfresco Developer Guide source reorg and 3.2 Community update

[UPDATE: Added a link to the source code that works with 3.2 Enterprise]

I originally wrote the Alfresco Developer Guide source code for Alfresco 2.2 Enterprise and Alfresco 3 Labs. The code was pretty much the same regardless of which one you were running. For things that did happen to be different, I handled those with separate projects: one for community-specific stuff and one for enterprise-specific stuff. This was pretty much limited to minor web script differences for the “client extensions” projects and LDAP configuration differences for the “server extension” project.

With the release of 3.2 Community, I realized:

  • The number of different flavors of Alfresco any given reader might be running are going up, not down. Who knows when 2.2 Enterprise will be sunset.
  • It is no longer as easy as “Enterprise” versus “Labs/Community” because multiple releases of the same flavor are prevalent (2.2E, 3.0E, and 3.1E, for example).
  • Tagging my code in Subversion by Chapter alone is no longer enough–I need to tag by Chapter and by Alfresco version.
  • Sending the publisher the code one chapter at-a-time and expecting them to manage updates and deciding how to organize all of the chapter code was a bad idea.

So, I’ve done some work to make this better (reorg the projects, restructure the download files). I’ve also tested the example code from each chapter against the latest service packs for all releases since 2.2 Enterprise. That includes making some small updates to get the examples running on 3.2 Community.

You can now download either all of the source for every version I tested against, or, download the source that works for a specific version. It may take the official download site at Packt a while to get the new files, so here are links to download them from my site:

Alfresco Developer Guide example source code for…

  • Alfresco 2.2 Enterprise (~5.3 MB, Download)
  • Alfresco 3.0 Labs (~5.6 MB, Download)
  • Alfresco 3.0 Enterprise (~5.7 MB, Download)
  • Alfresco 3.1 Enterprise (~5.6 MB, Download)
  • Alfresco 3.2 Community (~5.7 MB, Download)
  • Alfresco 3.2 Enterprise (~5.9 MB, Download)
  • All of the above, combined (~28.1 MB, Download)

Hopefully this makes it easier for you to grab only what you need and makes it clear that each Eclipse project contains only what’s needed to work with that version of Alfresco. Deployment is easier too. Most of the time, it’s just the “someco-client-extensions” project that you deploy.

Now that I’ve got everything structured like I want it, as new versions of Alfresco are released, it should be much easier to keep up.

Keeping your Alfresco web scripts DRY

One of my teammates thoroughly drenched our under-the-desk development server with a giant cup of coffee once. Somehow, disaster was avoided, although the client’s carpet had a nice coffee-stain outline of the server’s footprint long after the app rolled out which afforded the rest of us endless opportunities to mercilessly haze the clumsy coder.

Keeping your Alfresco web scripts DRY is actually not about making your developers use spill-proof travel mugs, or better yet, virtual machines. DRY is a coding philosophy or principle that stands for Don’t Repeat Yourself. There are all kinds of resources available that go into more detail, and the principle is more broad than simply avoiding duplicate code, but that’s what I want to focus on here.

There are three techniques you should be using to avoid repeating yourself when writing web scripts: web script configuration, JavaScript libraries accessed via import, and FreeMarker macros accessed via import.

Web Script Configuration

Added in 3.0, a web script configuration file is an XML file that contains arbitrary settings for your web script. It’s accessible from both your controller and your view. Building on the hello world web script from the Alfresco Developer Guide, you could add a configuration script named “helloworld.get.config.xml” that contained:

<title>Hello World</title>

You could then access the “title” element from a JavaScript controller using the built-in E4X library:

var s = new XML(config.script);

And, you could also grab the title from the FreeMarker view:


The web script configuration lets you separate your configuration from your controller logic. And because you can get to it from both the controller and the view, you don’t have to stick configuration info into your model.

This example showed a script-specific configuration, but global configuration is also possible. See the Alfresco Wiki Page on Web Scripts for more details.

JavaScript Import

If your web script controllers are written in JavaScript, at some point you will find yourself writing JavaScript functions that you’d like to share across multiple web scripts. A common example is logic that builds a query string, executes the query, and returns the results. You don’t want to repeat the code that does that across multiple controllers. That’s what the import statement is for.

The syntax is easy:

<import resource="classpath:alfresco/extension/scripts/status.js">

This needs to be the first line of your JavaScript controller file. This example shows a JavaScript library being imported from the classpath, but you can also import from the repository by name or by node reference. See the Alfresco JavaScript API Wiki Page for more details.

FreeMarker Import

Of the three this is the one I see ignored most often. Let’s take the Optaros-developed microblogging component for Share. Its basic data entity is called a “Status” object. So web scripts on the repository tier return JSON that might have a single Status object or a list of Status objects. That’s two different web scripts and two different views, but the difference between a list of objects and a single object is really just the list-related wrapper–in both cases, the individual Status object JSON is identical. I’ve seen people simply copy-and-paste the FreeMarker from the single-object template to the list template and then just wrap that with the list markup. That’s bad. If you ever change how a Status object is structured, you’ve got to change it in (at least) two places. (Or it’ll be someone that comes after you that has to do it which makes it even worse. If you aren’t following the analogy, your redundant code is the coffee stain).

Instead of duplicating the logic, use a FreeMarker import and define a macro that formats the object. Then you can call the macro any time you need your object formatted. Here’s how it works for Status.

A FreeMarker file called “status.lib.ftl” contains the macros that format Status objects. It lives with the rest of the web script files and looks like this:

<#assign datetimeformat="EEE, dd MMM yyyy HH:mm:ss zzz">
Renders a status node as a JSON object
<#macro statusJSON status>
<#escape x as jsonUtils.encodeJSONString(x)>
"siteId" : "${["optStatus:siteId"]!''}",
"user" : "${["optStatus:user"]!''}",
"message" : "${["optStatus:message"]!''}",
"prefix" : "${["optStatus:prefix"]!''}",
"mood" : "${["optStatus:mood"]!''}",
"complete" : ${(["optStatus:complete"]!'false')?string},
"created" : "${["cm:created"]?string(datetimeformat)}",
"modified" : "${["cm:modified"]?string(datetimeformat)}"
Renders a status node as HTML
<#macro statusHTML status>
SiteID: ${["optStatus:siteId"]!''}<br />
User: ${["optStatus:user"]!''}<br />
Message: ${["optStatus:message"]!''}<br />
Prefix: ${["optStatus:prefix"]!''}<br />
Mood: ${["optStatus:mood"]!''}<br />
Complete: ${(["optStatus:complete"]!'false')?string}<br />
Created: ${["cm:created"]?string(datetimeformat)}<br />
Modified: ${["cm:modified"]?string(datetimeformat)}<br />

There’s one macro for JSON and another for HTML. It still bothers me that the same basic structure is repeated, but at least they are both in the same file and it feels better knowing that this is the one and only place where the data structure for a Status object is defined.

The FreeMarker that returns Status objects as JSON resides in status.get.json.ftl and looks like this:

<#import "status.lib.ftl" as statusLib/>
"items" : [
<#list results as result>
<@statusLib.statusJSON status=result />
<#if result_has_next>,</#if>

You can see the import statement followed by the JSON that sets up the list, and then the call to the FreeMarker macro to format each Status object in the list.

When someone posts a new Status, the new Status object is returned. Rather than repeat the JSON structure for a Status object, the view simply calls the same macro that got called from the GET:

<#import "status.lib.ftl" as statusLib/>
"status" : <@statusLib.statusJSON status=result />

Now if the data structure for a Status object ever needs to change, it only has to be changed in one place.

Don’t Repeat Yourself

Take a look at your web scripts. Eliminate your duplicate code. And keep a lid on your mocha frappuccino.

Curl up with a good web script

Curl is a useful tool for all sorts of things. One specific example of when it comes in handy is when you are developing Alfresco web scripts. On a Surf project, for example, you might divide into a “Surf tier” team and a “Repository tier” team. Once you’ve agreed on the interface, including both the URLs and the format of the data that goes back-and-forth between the tiers, the two teams can start cranking out code in parallel.

If you’re on the repo team, you need a way to test your API, and you probably don’t have a UI to test it with (that’s what the other team’s working on). There are lots of solutions to this but curl is really handy and it runs everywhere (on Windows, use Cygwin).

This post isn’t intended to be a full reference or how-to for curl, and obviously, you can use curl for a lot of tasks that involve HTTP, not just Alfresco web scripts. Here are some quick examples of using curl with Alfresco web scripts to get you going.

Get a ticket

It’s highly likely that your web script will require authentication. So the first thing you do is call the login web script to get a ticket.

curl -v "http://localhost:8080/alfresco/service/api/login?u=admin&pw=somepassword"

Alfresco will respond with something like:

<?xml version="1.0" encoding="UTF-8"?>

Now you can take that ticket and append it to your subsequent web script calls.

Any web script you’ve got that accepts GET can be tested using the same simple syntax.

Post JSON to your custom web script

If all you had were GETs you’d probably just test them in your browser. POSTs, PUTs and DELETEs require a little more doing to test. You’re going to want to test those web scripts so that when the front-end team has their stuff ready, it all comes together without a lot of fuss.

So let’s say you’ve got a web script that the front-end will be POSTing JSON to. To test it out, create a file with some test JSON, then post it to the web script using curl, like this:

curl -v -X POST "http://localhost:8080/alfresco/service/someco/someScript?alf_ticket=TICKET_e46107058fdd2760441b44481a22e7498e7dbf66" -H "Content-Type: application/json" -d @/Users/jpotts/test.json

By the way, did you know that starting with 3.0, if you name your controller with “.json” before the “.js” the JSON will be sitting in a root variable called “json”?  So in this case instead of naming my controller “” I’d name it “” and then in my JavaScript, I can just eval the “json” variable that got created for me automatically and start working with the object,  like this:

var postedObject = eval('(' + json + ')');
logger.log("Customer name:" + postedObject.customerName);

Run a CMIS query

With 3.0 Alfresco added an implementation of the proposed CMIS spec to the product. CMIS gives you a Web Services API, a RESTful API, and a SQL-like query language. Once you figure out the syntax, it’s easy to post CMIS queries to the repository. You can wrap the CMIS query in XML:

<cmis:query xmlns:cmis="" >
<cmis:statement><![CDATA[select * from cm_content where cm_name like '%Foo%']]></cmis:statement>

Then post it using the same syntax as you saw previously, but with a different Content-Type in the header, like this:

curl -v -X POST "http://localhost:8080/alfresco/service/api/query?alf_ticket=TICKET_e46107058fdd2760441b44481a22e7498e7dbf66" -H "Content-Type: application/cmisquery+xml" -d @/Users/jpotts/cmis-query.xml

Alfresco will respond with ATOM, but it’s a little verbose so I won’t take up space here to show you the result. Also, I noticed this bombed when I ran it against 3.1 Enterprise but I haven’t drilled down on why yet.

Create a new object using CMIS ATOM

Issuing a GET against a CMIS URL returns ATOM. But CMIS URLs can also accept POSTed ATOM to do things like create new objects. For example, to create a new content object you would first create the ATOM XML:

<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="" xmlns:cmis="">
<title>Test Plain Text Content</title>
<summary>Plain text content created via CMIS POST</summary>
<content type="text/plain">SGVyZSBpcyBzb21lIHBsYWluIHRleHQgY29udGVudC4K</content>
<cmis:propertyString cmis:name="ObjectTypeId"><cmis:value>document</cmis:value></cmis:propertyString>

Note that the content has to be Base64 encoded. In this case, the content is plain text that reads, “Here is some plain text content.” One way to encode it is to use OpenSSL like “openssl base64 -in <infile> -out <outfile>”. The exact syntax of ATOM XML with CMIS is the subject for another post.

Once you’ve got the XML ready to go, post it using the same syntax shown previously, with a different Content-Type in the header:

curl -v -X POST "http://localhost:8080/alfresco/service/api/node/workspace/SpacesStore/18fd9821-42a5-4c6a-86d3-3f252679cf7d/children?alf_ticket=TICKET_e46107058fdd2760441b44481a22e7498e7dbf66" -H "Content-Type: application/atom+xml" -d @/Users/jpotts/testCreate.atom.xml

The node reference in the URL above is a reference to the folder in which this new child will be created. There’s also a similar URL that uses the path instead of a node ref if that’s more your thing.

Refreshing Web Scripts from Ant

One of the things you do quite frequently when you develop web scripts is tell Alfresco to refresh its list of web scripts. There are lots of ways to automate this, but one is to create an Ant task that uses curl to invoke the web script refresh URL. This lets you deploy your changes and tell Alfresco to refresh the list in one step (and makes sure you and your teammates never forget to do the refresh).

<target name="deploy-webscripts" depends="deploy" description="Refreshes the list of webscripts">
<exec executable="curl">
<arg value="-d"/>
<arg value="reset=on"/>
<arg value="http://${alfresco.web.url}/service/index"/>

In this example, the “deploy” ant task this task depends on is responsible for copying the web scripts to the appropriate place in the exploded Alfresco WAR. (Thanks to my colleague Eric Shea ( for this tip).

So there you go. It’s not Earth-shattering but it might give you a productivity boost if you don’t already have curl or an alternative already in your bag of tricks.