JavaScript API Cookbook

From AlfrescoWiki

Jump to: navigation, search

This page is the central page for examples for the JavaScript API. Feel free to add your examples to this.

Example scripts can be found in the Company Home/Data Dictionary/Scripts folder in a default Alfresco installation.

Contents

[edit] Create Backup of a Document

Creates a backup of a document as it is added to a space:

// find the backup folder - create if not already exists
var backupFolder = space.childByNamePath("Backup");
if (backupFolder == null && space.hasPermission("CreateChildren"))
{
   // create the folder for the first time
   backupFolder = space.createFolder("Backup");
}
if (backupFolder != null && backupFolder.hasPermission("CreateChildren"))
{
   // copy the doc into the backup folder
   var copy = document.copy(backupFolder);
   if (copy != null)
   {
      // change the name so we know it's a backup
      copy.name = "Backup of " + copy.name;
      copy.save();
   }
}

[edit] Create Backup of a Document And Log Doc Properties

Creates a backup of a document and logs the doc properties to a log text file:

// find the backup folder - create if not already exists
var backupFolder = space.childByNamePath("Backup");
if (backupFolder == null && space.hasPermission("CreateChildren"))
{
   // create the folder for the first time
   backupFolder = space.createFolder("Backup");
}
if (backupFolder != null && backupFolder.hasPermission("CreateChildren"))
{
   // copy the doc into the backup folder
   var copy = document.copy(backupFolder);
   if (copy != null)
   {
      // change the name so we know it's a backup
      var backupName = "Backup of " + copy.name;
      copy.name = backupName;
      copy.save();
   }
   
   // record the time of the backup to a log file
   var logFile = backupFolder.childByNamePath("backuplog.txt");
   if (logFile == null)
   {
      logFile = backupFolder.createFile("backuplog.txt");
   }
   if (logFile != null)
   {
      logFile.content += "File: " + backupName +
                         "\tDate: " + new Date().toGMTString() +
                         "\tSize: " + copy.size + "\r\n";
   }
}

[edit] Append Copyright Line To File

Appends a copyright line of content to plain text and HTML files:

if (document.hasPermission("Write"))
{
   if (document.mimetype == "text/plain")
   {
      document.content += "\r\n\r\nCopyright (C) 2006";
   }
   else if (document.mimetype == "text/html")
   {
      document.content += "<br><br><small>Copyright &copy; 2006</small>";
   }
}

[edit] Add Aspects

Adding several aspects to a document:

var props = new Array(1);
props["cm:template"] = document.nodeRef;
document.addAspect("cm:templatable", props);

props = new Array(1);
props["cm:lockIsDeep"] = true;
document.addAspect("cm:lockable", props);

props = new Array(1);
props["cm:hits"] = 1;
document.addAspect("cm:countable", props);

[edit] Find All Documents using Lucene Search

Finds all the documents containing the text 'Alfresco' using a Lucene search and records the results to a log file:

// log the docs that currently contain the word 'Alfresco' to a log file
var logFile = userhome.childByNamePath("alf docs.txt");
if (logFile == null)
{
   logFile = userhome.createFile("alf docs.txt");
}
if (logFile != null)
{
   // execute a lucene search across the repo for the text 'alfresco'
   var docs = search.luceneSearch("TEXT:alfresco");
   var log = "";
   for (var i=0; i<docs.length; i++)
   {
      log += "Name: " + docs[i].name + "\tPath: " + docs[i].displayPath + "\r\n";
   }
   logFile.content += log;
}

[edit] Return Result Value

Returning a result value. This is useful for scripts that are processed using URLs via the Script Command Servlet, as the results are returned as the HTML response from the servlet:

function result()
{
   return "The name of my home space is: " + userhome.name;
}
result();

The following solution will also return a value if placed at the end of a script:

// script here
// ...
var result = "some results...";
result;

[edit] Create Document, Make it Versionable, Modify It

Creates a document, makes it versionable, checks it out, modifies the content of the working copy, checks it in again and then repeats the process but checks in the document with a version history note and as a major version increment:

// create file, make it versionable
var doc = userhome.createFile("checkmeout.txt");
doc.addAspect("cm:versionable");
doc.content = "original text";

// check it out and update content on the working copy
var workingCopy = doc.checkout();
workingCopy.content = "updated text 1";

// check it in
doc = workingCopy.checkin();

// check it out again
workingCopy = doc.checkout();
workingCopy.content = "updated text 2";

// check it in again, but with a version history note and as major version increment
doc = workingCopy.checkin("a history note", true);

[edit] Change Mime Type of a Document

Changes the mimetype of a document after setting the content:

var file = userhome.createFile("testfile.html");
file.content = "some <b>HTML</b> here";
file.mimetype = "text/html";

[edit] Create Document and Transform it

Creates document content and converts it to new formats using the transformation API:

// create a plain text doc and convert to PDF, generated file will be placed in same space as original
var doc1 = userhome.createFile("transform_me1.txt");
doc1.mimetype = "text/plain";
doc1.content = "This is plain text";
var trans1 = doc1.transformDocument("application/pdf");

// create an HTML doc and convert to plain text, generated file will be created under the companyhome space
var doc2 = userhome.createFile("transform_me2.html");
doc2.mimetype = "text/html";
doc2.content = "This is an <b>HTML</b> <font color=blue><i>document</i>!</font>";
var trans2 = doc2.transformDocument("text/plain", companyhome);

// create an HTML doc and convert to flash swf file, generated file will be created under the companyhome space
var doc3 = userhome.createFile("transform_me3.html");
doc3.mimetype = "text/html";
doc3.content = "This is an <b>HTML</b> <font color=blue><i>document</i>!</font>";
var trans3 = doc3.transformDocument("application/x-shockwave-flash", companyhome);

Converts an image document to other formats:

// convert an image document to GIF format and place it in company home
var gifImage = document.transformImage("image/gif", companyhome);

// convert an image to JPG format and resize to thumbnail image
var thumbImage = document.transformImage("image/jpeg", "-resize 120");

[edit] Execute Freemarker Template

Executes a template from the repository against the current Document node:

var template = companyhome.childByNamePath("/Data Dictionary/Presentation Templates/doc_info.ftl");
if (template != null)
{
   var result = document.processTemplate(template);
   // output result to the console - could just as easily save the content into a new node...
   logger.log(result);
}

Builds a FreeMarker template directly in the script, also builds up an argument list for the template. The result of the template is saved to a new node as the content:

var template = "<h3>Document name is ${document.name}</h3>" +
               "The ID argument: ${args['id']}";
var args = new Array()
args["id"] = "01234-56789";
var result = document.processTemplate(template, args);
// save the template result content to a new node in my home space
var outputFile = userhome.createFile("output.txt");
outputFile.content = result;

[edit] Display the permissions current set on the userhome space

var permissions = userhome.permissions;
var result = "";
for (var i=0; i<permissions.length; i++)
{
   result += permissions[i] + "<br>";
}
result;

[edit] Include two other javascripts, one from the classpath and the other from the repository

<import resource="classpath:alfresco/extension/myutils.js">
<import resource="/Company Home/Data Dictionary/Scripts/mylib.js">

// your script here
// ...

[edit] Creating different child node types, including via a specific named child association and with default properties

var node1 = userhome.createNode("create test1.txt", "cm:content");
node1.content = "node1 content";

var node2 = userhome.createNode(null, "sys:base");

var props = new Array();
props["cm:name"] = "create test3.txt";
var node3 = userhome.createNode(null, "cm:content", props);

props["cm:name"] = "node name4.txt";
props["cm:title"] = "node title4";
var node4 = userhome.createNode(null, "cm:content", props, "cm:contains");

var result = "nodes created ok";
result;

[edit] Iterating values using JavaScript syntax for each and for each in

// example iterating array indexes using 'for .. in'
var out1 = "";
for (i in userhome.children)
{
   out1 += userhome.children[i].name + "<br>";
}

// example iterating array values using 'for each .. in'
var out2 = "";
for each (n in userhome.children)
{
   out2 += n.name + "<br>";
}

var out = out1 + "<br><br>" + out2;
out;

[edit] Create and Removing Target Associations

Example of creating and removing target assocations:

var sourceNode = userhome.createNode("testassocsfile.txt", "cm:content");
sourceNode.content = "the original text";
sourceNode.addAspect("cm:transformable");

var destNode = userhome.createNode("translation1.txt", "cm:content");
destNode.content = "the translation of the original text";
sourceNode.createAssociation(destNode, "cm:formats");

var tempNode = userhome.createNode("dummy.txt", "cm:content");
tempNode.content = "dummy";
sourceNode.createAssociation(tempNode, "cm:formats");

// get the nodes at the end of the 'cm:formats' association
var translations = sourceNode.assocs["cm:formats"];

sourceNode.removeAssociation(tempNode, "cm:formats");
tempNode.remove();

[edit] Use AVM API to Process Webproject Store

Example using the AVM API to process a webproject store - the store name is passed as store on the url arguments:

if (args["store"] == null)
{
   logger.log("ERROR: 'store' argument not specified.");
}
else
{
   main();
}

function main()
{
   var storeRootNode = avm.lookupStoreRoot(args["store"]);
   if (storeRootNode != null)
   {
      var path = storeRootNode.path + "/ROOT/admin/index.html";
      var node = avm.lookupNode(path);
      if (node == null)
      {
         return "ERROR: unable to find path: " + path;
      }
      
      var store = avm.lookupStore(args["store"]);
      if (store == null)
      {
         return "ERROR: unable to lookup store: " + args["store"];
      }
      var rootNode = store.lookupRoot();
      if (rootNode == null)
      {
         return "ERROR: unable to find root node for store: " + store.name;
      }
      
      var out = "";
      var results = store.luceneSearch("TEXT:tomcat");
      for (var i=0; i<results.length; i++)
      {
         out += results[i].path + "<br>";
      }
      return out;
   }
}

[edit] Find out what repository Actions are available

function result()
{ 
   return (actions.registered); 
} 
result();

Output will be something like:

[transform-image, mail, copy-to-web-project, extract-metadata, counter, check-in, simple-workflow, script, transform, remove-features, specialise-type, import, add-features, link-category, blog-post, move, copy, check-out]

[edit] Find all XML Forms of a Specific Type and Return the XML content

You can use the E4X module of Javascript to parse XML.


var store = avm.lookupStore("test");
var results = store.luceneSearch("wca\\:parentformname:Press Release");
var pressreleases = new XML();
pressreleases = <pressreleases></pressreleases>
for (var i=0, len=results.length; i<len; ++i){
	var str = new String(results[i].content);	
	//Javascript E4X module has problems with XML header
		if ( str.substr(0,5).indexOf("?xml") != -1 ) {
		positionRootElement = str.indexOf("<", 10);//get first real tag
		str = str.substr( positionRootElement, str.length - 1 ); 
	}
	var pressrelease = new XML(str);
	pressreleases.pressrelease = pressrelease;
}
model.pressreleases = pressreleases.toXMLString();

You can then return the XML using this:

${pressreleases}


IMPORTANT NOTE:

When using in a workflow definition XML, a Javascript "//" comment style stops following code from executing as linebreaks are removed before processing. Use the "/* ... */" comment format instead. Also, the "<" signs need to be escaped. So the previous fragment becomes:


/* Javascript E4X module has problems with XML header */
			if ( str.substr(0,5).indexOf('&lt;?xml') != -1 ) {
				positionRootElement = str.indexOf('&lt;', 5); 
				str = str.substr( positionRootElement, str.length - 1 ); 
			}