Implementing Alfresco JavaScript API Functionalities

Exclusive offer: get 50% off this eBook here
Alfresco 3 Cookbook

Alfresco 3 Cookbook — Save 50%

Over 70 recipes for implementing the most important functionalities of Alfresco

$35.99    $18.00
by Snig Bhaumik | July 2011 | Open Source

The JavaScript API is a unique model for writing programs and services using JavaScript (ECMA Script) 1.6 compatible files. The API enables developers to write scripts that can access, modify, or create various Alfresco Repository objects such as users, nodes, groups, tags, categories, and so on.

In this article by Snig Bhaumik, author of Alfresco 3 Cookbook, we will cover:

  • Adding/Changing the contents of a document
  • Creating a backup copy of a document
  • Adding a tag to a document
  • Assigning Permissions to a User
  • Debugging Alfresco JavaScript

 

Alfresco 3 Cookbook

Alfresco 3 Cookbook

Over 70 recipes for implementing the most important functionalities of Alfresco

        Read more about this book      

(For more resources on Alfresco, see here.)

The reader can benefit from the previous article on Alfresco 3: Writing and Executing Scripts.

 

Add/Change contents of a document

Let’s explore some example JavaScript. In the following example scripts, you will be able to witness the APIs and functionalities.

Getting ready

We will store the JavaScript files in the Company Home>Data Dictionary>Scripts>Cookbook folder (this folder does not exist in your repository and create this folder).

And will run the sample scripts against a document – Test_JS_API.txt in the folder Company Home>InfoAxon>Chapter 8. I have uploaded this text file with a simple line of text: A sample Document created to investigate in JavaScript API. and used our custom content type iabook:Product.

if (document.hasPermission("Write"))
{
if (document.mimetype == "text/plain")
{
if (!document.hasAspect("cm:versionable"))
document.addAspect("cm:versionable");
var wcopy = document.checkout();
var cnt = wcopy.content;
cnt += "\r\nThis line is added using the JavaScript.";
wcopy.content = cnt;
wcopy.checkin("Sample Line added via JS");
}
}

How to do it...

  1. Create a new script file in the Company Home>Data Dictionary>Scripts>Cookbook folder and save this code; let’s say the file is named changecontent.js
  2. Execute the script using Run Action on the document Test_JS_API.txt in the Chapter 8 folder.
  3. After running the script, a new version of the document will be created and a new line will be added in the document.

    Alfresco 3 Cookbook

  4. Thus each time you run the script for this document, a line will be appended at the end of the content and a new version will be created.

How it works...

The document object here automatically refers to the current document, in our case, it is Test_JS_API.txt, since we have executed the script against this document.

First we have checked whether we have proper permission to perform the write operation on the document. If the permission is there, we check the mimetype of the document, since the textual content writing operation is possible only for a few mimetypes such as text, html, and so on.

After that, we check whether the document is versionable or not, by default, any content you upload in the repository is not versionable. So we add the cm:versionable aspect in case it is not there already.

Then we checkout the document and append the line of text we want in the working copy. After updating the content, we checking the working copy with a commit comment. This comment is visible in the Version History of the document.

Though it is not always mandatory to check for the required permissions, it is a good practice to confirm for the relevant permissions, otherwise Alfresco may throw runtime errors in case the required permissions are not available.

 

Creating a backup copy of a document

In this recipe, we will write a script to create a backup copy of a particular document.

How to do it...

  1. Create a new script file in the Company Home>Data Dictionary>Scripts>Cookbook folder and add the following code. Let’s say the file is named createbackup.js

    var back = space.childByNamePath("Backup");
    if (back == null && space.hasPermission("CreateChildren"))
    {
    back = space.createFolder("Backup");
    }

    if (back != null && back.hasPermission("CreateChildren"))
    {
    var copied = document.copy(back);
    if (copied != null)
    {
    var backName = "Backup of " + copied.name;
    copied.name = backName;
    copied.properties.description = "This is a Backup copy created
    by JS";
    copied.save();
    }
    }

  2. Execute the script using Run Action on the document Test_JS_API.txt in the Chapter 8 folder.
  3. After executing the script, a new folder named Backup will be created (if it does not exist already) and a copy of this document (named Backup of Test_JS_API.txt) will be created in the backup folder.

(Move the mouse over the image to enlarge.)

How it works...

The space object here automatically refers to the current space. In our case, it is Chapter 8, since we have executed the script against a document from this folder.

The document object here automatically refers to the current document. In our case, it is Test_JS_API.txt, since we have executed the script against this document.

First we have checked whether a space already exists there with the name Backup under Chapter 8. If not, we create the space. This is the space where we intend to create our backup copy.

After that, we check whether we have the proper permission to create a new document in the backup folder. We do this by checking the CreateChildren permission.

If we have the proper required permission, we create a copy of the document in the backup folder. Then we change a few properties of the copied document – we change the name and description, for instance. After changing the properties, we save the changes.

Note that you do not need to save after changing the content of a document. However, you need to do this in case you change any property of the content item.

 

Adding a tag to a document

In this recipe, we will write a script that can be used to tag a document.

How to do it…

  1. Create a new script file in the Company Home>Data Dictionary>Scripts>Cookbook folder and add the following code; let’s say the file is named addtag.js

    if (!document.hasAspect("cm:taggable"))
    document.addAspect("cm:taggable");

    document.addTag("test");

  2. Execute the script using Run Action on the document Test_JS_API.txt in the Chapter 8 folder.
  3. The document will not be taggable, and a new tag has been added with the document – test. This is reflected in the property sheet of the document.

    Alfresco 3 Cookbook

  4. Now, you can also add more tags using the property editor dialog.

Alfresco 3 Cookbook

How it works...

The code we presented is rather simple in this case. As usual, the document object here automatically refers to the current document. In our case, it is Test_JS_API.txt, since we have executed the script against this document.

First we have checked whether the document already has the cm:taggable aspect associated with it, if not we add this aspect.

Then it is just about adding a tag – we added a tag test.

You can also add multiple tags at a time using the addTags method (we have used the addTag method to add a single tag in our example).

 

Alfresco 3 Cookbook Over 70 recipes for implementing the most important functionalities of Alfresco
Published: July 2011
eBook Price: $35.99
Book Price: $59.99
See more
Select your format and quantity:

 

        Read more about this book      

(For more resources on Alfresco, see here.)

Assigning permissions to a user

We will see in this recipe how to assign various permissions to a particular user.

How to do it…

  1. Create a new script file in the Company Home>Data Dictionary>Scripts>Cookbook folder and save this code. Let’s say the file is named assignpermission.js.

    var qry = "@cm\\:name:\"Test_JS_API.txt\"";
    var docs = search.luceneSearch(qry);

    if (docs.length > 0)
    {
    var doc = docs[0];
    if (doc.hasPermission("ChangePermissions"))
    {
    var usr = people.getPerson("snig.bhaumik");
    if (usr != null)
    {
    doc.setPermission("Write", "snig.bhaumik");
    doc.setPermission("Delete", "snig.bhaumik");
    doc.setPermission("AddChildren", "snig.bhaumik");
    doc.setPermission("Execute", "snig.bhaumik");
    }
    }
    }

  2. Execute the script using Run Action on the document Test_JS_API.txt in the Chapter 8 folder.
  3. Upon executing the script, the user snig.bhaumik will have write, delete, and execute the permission of this document.
  4. Let’s examine what happened behind the scenes. This was the original permission set of this document.

    As you can see, apart from the default privileges, no other permissions are set. When the user snig.bhaumik logs in, here is what he can do with this document.

    Alfresco 3 Cookbook

  5. However, after the execution of the script, this is the permission set of the document.

  6. And, when the user snig.bhaumik logs in, here is what he can now do on this document.

    Alfresco 3 Cookbook

  7. Thus you can see proper permissions have been assigned to the user snig.bhaumik on this document.

How it works...

There are a few things we have used in this script.

First of all, we have searched for the document named Test_JS_API.txt using Lucene. Although we could have done this using the document object, since we are executing the script on this document only, we have used Lucene search here, just to demonstrate the search operations.

As a result, we can now execute this script on any content item (not limited to only the Test_JS_API.txt document), and the permissions will affect this document only. Here, we have searched for documents in the repository with the name Test_JS_API.txt, the search results as JavaScript array in the docs variable. We have used only the first element of this array. Thus if there are multiple documents in the repository by this name, only the first element will be affected by this code.

However, if we want our code to affect only the current document, you use our good old document object, no need to search for documents. Here is the code for this:

if (document.hasPermission("ChangePermissions"))
{
var usr = people.getPerson("snig.bhaumik");
if (usr != null)
{
document.setPermission("Write", "snig.bhaumik");
document.setPermission("Delete", "snig.bhaumik");
document.setPermission("AddChildren", "snig.bhaumik");
document.setPermission("Execute", "snig.bhaumik");
}
}

After that, we find whether there is a user with the name snig.bhaumik. If the user exists, we assign the required permissions to this user.

 

Debugging Alfresco JavaScript

As you have seen, using Alfresco JavaScript you write scripts which execute in your server, not at your client browser end. You cannot write user interactive JavaScript code such as alert, inputbox, and so on. As a developer, this makes things a bit complex in terms of debugging and troubleshooting your code.

However, Alfresco comes to your rescue yet again.

There are two ways to debug your code.

  1. Using the Logging API:
    Like other root level APIs, Alfresco provides a logger object which exposes two methods to log your debug code in your console logger.
    • isLoggingEnabled: This helps to identify whether console logging is enabled or not. By default, it is disabled.
    • log: You pass your log string value into this method. And if logging is enabled, you get your messages logged in console output.
  2. Using the JavaScript Debugger:
    This is another advanced user interface Alfresco offers for debugging, which allows step-by-step execution and debugging in the JS code.

It must be executed on the same machine as the Alfresco Server — remote debugging is not yet supported.

How to do it...

Here, we will see how to debug the script using the JavaScript Debugger.

  1. As an administrator, you can enable or disable the debugger by this URL (assuming localhost as the server and 8080 is the server port).
    http://localhost:8080/alfresco/service/api/javascript/debugger
  2. The following web page will appear. You can use the button to enable the debugger.

    Alfresco 3 Cookbook

  3. A debugger window will appear and is ready to debug your scripts.

  4. Now, try to again execute a script. The debugger will automatically catch up and you can debug your code line-by-line.

  5. In this example, I have executed the assignpermission.js script.
  6. After debugging completes, you should disable the debugger by clicking on the disable button.

    Alfresco 3 Cookbook

How it works…

The debugger is a Swing client application which executes in the Java VM of the server where Alfresco is deployed.

Right now, it must be executed in the same machine as the Alfresco server, as remote debugging is not yet supported up to version 3.4.

Summary

In this article we took a look at some example recipes to implement the various Alfresco Javascript API functionalities.


Further resources on this subject:


Alfresco 3 Cookbook Over 70 recipes for implementing the most important functionalities of Alfresco
Published: July 2011
eBook Price: $35.99
Book Price: $59.99
See more
Select your format and quantity:

About the Author :


Snig Bhaumik

Snigdhendu Bhaumik is the Technical Director of InfoAxon Technologies Ltd, based in India. He is also the Director of Open Source Innovation and Heads the Knowledge Management Practice at InfoAxon – India’s first and pioneer Open Source Integration company.

A computer engineer by education and developer at heart, Snigdhendu has 10 years of experience in various technologies such as Alfresco, Liferay, Pentaho, and Microsoft .NET. An open source enthusiast and regular community participant, Snigdhendu was the original contributor of Alfresco Calendar component. He specializes in Knowledge Management and Business Intelligence domains, and is responsible for designing and architecting KM and BI solution offerings.

Books From Packt


Alfresco 3 Records Management
Alfresco 3 Records Management

Alfresco 3 Web Content Management
Alfresco 3 Web Content Management

Alfresco 3 Web Services
Alfresco 3 Web Services

Alfresco 3 Business Solutions
Alfresco 3 Business Solutions

Liferay Portal 6 Enterprise Intranets
Liferay Portal 6 Enterprise Intranets

CMS Made Simple 1.6: Beginner's Guide
CMS Made Simple 1.6: Beginner's Guide

CMS Design Using PHP and jQuery
CMS Design Using PHP and jQuery

CMS Made Simple Development Cookbook
CMS Made Simple Development Cookbook


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
8
V
F
X
i
4
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software