Appendix D. Repository JavaScript API Reference

The Alfresco Repository JavaScript API lets you develop JavaScript (ECMAScript) 1.6–compatible files to access, modify, and create Alfresco repository objects, such as nodes, aspects, and properties.

OBJECT-ORIENTED LEVEL APIs

This appendix details the Alfresco JavaScript API for JavaScript files that execute in the Alfresco Web client and for Web scripts that execute JavaScript within the repository.

You can use scripts to perform various functions, such as:

  • Finding nodes

  • Performing searches

  • Walking node hierarchies

  • Modifying the value of properties, aspects, and associations

  • Transforming and manipulating content

  • Processing WCM Web projects and AVM objects

  • Creating groups, people, and modify permissions

  • Creating new files, folders, or nodes

  • Copying, moving, and deleting nodes

  • Creating, modifying, and removing child and target associations between nodes

  • Including (or importing) other scripts

Note

Web applications built on the Alfresco Surf platform use Web scripts, but they do not execute directly within the context of an Alfresco repository. Instead, they execute within a remote presentation tier (for example, an entirely new Web application running on a separate Web tier).

For information about the API available to JavaScript-based Web scripts on the presentation tier, see Online Appendix B.

SCRIPT FILES

Script files can be stored on the classpath (for example, in alfresco/extension/myscripts) or in a repository store. Scripts are generally stored in the default repository in the following location:

Company Home/Data Dictionary/Scripts

In this location, users can access scripts directly using the Execute a Script action. Users can access scripts in any repository location through a REST URL with the appropriate read permissions on the script document. Scripts on the classpath can be imported into other scripts but not executed directly in the Alfresco Explorer Web client.

Importing Scripts

This feature allows libraries of scripts to be built and used by other scripts at runtime. The syntax to import the scripts is specific to Alfresco and not a feature of standard JavaScript. For example, the <script src='...'> syntax you may be familiar with, as supported by most web browsers, is not part of standard ECMA JavaScript and will not work in Alfresco.

The syntax to import other scripts is very strict and must be followed exactly or the import may fail. Import directives must be the first lines in the JavaScript file; no code or comments are allowed above those lines. Only the following syntax variants are supported:

  • Import a script from the repository using a name-based path:

    <import resource="/Company Home/Data Dictionary/Scripts/library.js">
  • Import a script from the repository using a NodeRef reference:

    <import resource="workspace://SpacesStore/6f73de1b-d3b4-11db-80cb-
    112e6c2ea048">
  • Import a script from a Java classpath location:

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

THE SCRIPTING API

The Alfresco JavaScript API provides a rich set of scriptable Java objects. Many root scope objects are provided by default, such as access to the user home folder, company home folder, WCM Web projects, search, People API, and logging functionality. You can also configure in additional root scope objects for use by your own scripts.

Root-Scoped Objects

Within the JavaScript API, the common Alfresco repository concepts, such as nodes, aspects, associations and properties, are provided by ScriptNode objects. They also provide access to common services through an object-oriented API.

The objects available by default in the root scripting scope vary depending on how the script engine is accessed. If the script is processed through a rule/action (for example, Execute Script) in the Web client or through the Script Command Processor, the following objects are available:

  • companyhome—The Company Home ScriptNode.

  • userhome—The current user's Home Space ScriptNode.

  • person—The ScriptNode representing the current user's Person object.

  • space—The current space ScriptNode, if any. For a script executed as part of a rule, the space object is the space in which the rule resides. If the rule is inherited, this may not be the expected space.

  • document—The current document ScriptNode, if any.

  • script—The ScriptNode representing the script object itself. This is only available if the script is loaded from the Java classpath.

  • args—An associative array of any URL parameters passed using the Script Processor Servlet.

  • search—A host object providing access to the various Alfresco search interfaces such as FTS-Alfresco, Lucene, XPath and Saved Search results.

  • people—A host object providing access to and manipulating Alfresco person objects and groups.

  • actions—A host object providing invocation of registered Alfresco actions.

  • logger—A host object providing access to console logging facilities for script debugging.

  • session—Session-related information, such as the current authentication ticket.

  • classification—Access to the root elements of the Classification API.

  • utils—Access to a library of helper functions that are not provided as part of generic JavaScript.

  • webprojects—The root of the WCM JavaScript API providing access to Web projects, sandboxes, WCM assets, and project membership.

  • invitations—The root of the Invitations API providing access to invitations for Web sites.

  • groups—The root of Group authorities providing access to advanced authority APIs for manipulating groups and zones.

Note

The default model objects can be accessed directly from the root of a script scope and follow the standard JavaScript pattern of property dot notation–style syntax; For example:

var name = userhome.properties.name.

Here, the variable name is populated by accessing the properties property and the name value within it.

The node children/association/aspect model is built dynamically as required. For example, you can write statements to walk multiple node collections:

userhome.children[1].children[0].children[2].name

The ScriptNode API

The companyhome, userhome, document, space, and person objects represent Alfresco node objects and provide access to common Alfresco concepts (such as properties, aspects, and associations).

The following properties are available to use within scripts:

  • properties—An associative array (map) of the properties for the node. For example:

    userhome.properties.name

    Note

    Each property is keyed by model QName, which can be written in the fully qualified namespace form, the short form (for example, cm:content), or just the property name if the default content model namespace is assumed (for example, content). Therefore, all the following statements are equivalent:

    var name1 = userhome.properties.name
    var name2 = userhome.properties["name"];
    var name3 = userhome.properties["cm:name"];
    var name4 = userhome.properties["{http://www.alfresco.org/
    model/content/1.0}name"];

    Properties of type d:noderef are automatically converted into another ScriptNode object, letting you dynamically walk the object hierarchy for a node. For example, if a document node has a NodeRef property called locale, you could execute the following to retrieve the name of the node that the property references:

    var locale = document.properties.locale.properties.name;

    To retrieve the NodeRef value for a d:noderef property, the following code will work:

    var localeNoderef =
    document.properties.locale.nodeRef;

    In addition, any properties of type d:content are converted to special ScriptContent objects that feature an API to get or modify the content, MIME type, size, and URL for the content property.

    var mimetype = document.properties.content.mimetype;
    var content = document.properties.content.content;

    As most documents derive from the default content model type cm:content, shortcut APIs provide for content, MIME type, size, and URL for the cm:content property.

    document.content = "some new text content";
    var mimetype = document.mimetype;
    var url = document.url;
  • children—A read-only JavaScript array of the child nodes. For example:

    mynode.children[0]
  • assocs—A read-only associative array of the target associations of the node. For example:

    mynode.assocs["cm:translations"][0]
  • sourceAssocs—A read-only associative array of the source associations to the node. For example:

    mynode.sourceAssocs["cm:translations"][0]
  • childAssocs—A read-only associative array of the child associations of the node. For example:

    myforumnode.childAssocs["fm:discussion"][0]
  • parentAssocs—A read-only associative array of the parent associations of the node. Each named entry in the children, assocs, sourceAssocs, childAssocs, and parentAssocs arrays contain an array of the ScriptNode objects on the end of the association. For example:

    mynode.parentAssocs["cm:contains"][0]
  • aspects—A read-only array of the aspects as fully qualified QName strings applied to the node

  • isContainer—Returns true if the node is a folder node; otherwise, it is false.

  • isDocument—Returns true if the node is a content node; otherwise, it is false.

  • content—The content of the node on the default cm:content property as a string value that can be modified to update the content of the node

  • url—A read-only URL to the content stream for this node

  • downloadUrl—A read-only URL to the content stream for this node as an HTTP1.1 attachment object

  • mimetype—The MIME type encoding for content on the default cm:content property attached to this node

  • size—A read-only size in bytes of content on the default cm:content property attached to this node

  • displayPath—A read-only display path to this node

  • qnamePath—A read-only QName type path to this node

  • icon16—A read-only small icon image for this node

  • icon32—A read-only large icon image for this node

  • isLocked—Returns true if the node is locked; otherwise, it is false.

  • id—GUID for the node

  • nodeRef—NodeRef as a string for the node

  • name—Shortcut access to the cm:name property

  • type—Fully qualified QName type of the node

  • typeShort—Prefix string or short QName type of the node

  • parent—The primary parent node. This will be null if this is the root node.

    Note

    Take care when accessing the parent node if the current user does not have permissions to view it. The parent and parents nodes can always be obtained to allow application of a hasPermission() check before accessing its properties in a script.

  • parents—An array of the parent nodes

  • isCategory—Returns true if this is a category node; otherwise, it is false.

The following methods are available:

  • childByNamePath(path)— Performs a path-based query on the name property of the nodes; returns a node found at the specified path relative to the current node, else, null is returned. For example:

    var testingFolder =userhome.childByNamePath("QA/Performance/Testing");
  • childrenByXPath(xpath)—Performs an XPath-based query relative to the current node; returns an array of the nodes found or an empty array if no results are matched. For example:

    var nodes = userhome.childrenByXPath("*[@cm:name='Finance Documents']/*");
  • activeWorkflows—Returns an array of all active workflows of which this node is involved, or returns null if the node is not part of an active workflow

  • isScriptContent(obj)—Returns true if the supplied node property value is a ScriptContentData object

  • hasAspect(type)—Returns true if an aspect was applied to the node. For example:

    var isTemplatable = document.hasAspect("cm:templatable");
  • specializeType(type)—Specializes the type of a node where the type name supplied is a subtype of the current type as defined in the Data Dictionary; returns true on success, otherwise, it is false.

  • isSubType(type)—Determines if this node is a subtype of the specified type; returns true if this node is a subtype of the specified type.

Modifying and Creating the API

Most of the available ScriptNode APIs return read-only values; however, the real power of the Scripting API lies in its support for writable objects and access to Alfresco repository services. The ScriptNode object allows modification of properties, addition of new properties and aspects, creation of new files, folder, and custom type nodes, and the updating and setting of the text content stream for a node. In addition, it is possible to perform powerful features, such as deleting nodes, transforming content, executing templates, and modifying the associations for a node.

The following properties are available:

  • properties—The property array can be modified to update or add new properties. For example:

    // change the name of this document
    document.properties.name = "Backup of " + document.properties.name;
    // add a new property string
    document.properties["cm:locale"] = mylocalenode;
    // save the property modifications
    document.save();

    Note

    The node.save() API call is required to persist the property modifications; all other modifications using the API take immediate effect, such as content or adding aspects. JavaScript objects are different from native repository Java objects. Property values in the repository must be the correct object type as defined in the Data Dictionary and exposed by the content model. This means that a string property value expects a Java string, and a multi-valued property expects a list. The Alfresco JavaScript API converts most object types between JavaScript and Java, such as array (for a multi-value property), numbers, dates, Boolean, and strings. The conversion code handles all common type conversions and recursive lists of those types.

  • name —A helper property to get/set the name. This is a shortcut for properties.name.

  • content—A property to modify the text content of a node. For example:

    mynode.content = mynode.content + "append some text";

    This is very powerful, as it allows the content of a node to be changed from within a script. It is recommended that nodes with binary content should not be manipulated this way.

The following methods are available:

  • createFile(name)—Creates a new file (cm:content) node with the specified name as a child of this node; returns the newly created node as the result of the function or throws an exception if the creation failed. For example:

    var myfile = userhome.createFile("newfile.txt");
  • createFolder(name)—Creates a new folder (cm:folder) node with the specified name as a child of this node; returns the new node as the result of the function or throws an exception if the creation fails. For example:

    var myfolder = userhome.createFolder("New Folder");
  • createNode(name, type)—Creates a new node of the specified type as a QName in either full or short form. For example:

    var node = userhome.createNode("myfolder", "cm:folder");
  • createNode(name, type, assocType)—Creates a new node of the specified type as a child of the current node with the given child association type. The assocType parameter is the QName of the child association type to create. For example:

    var node = myforum.createNode("My Discussion", "fm:forum", fm:discussion");
  • createNode(name, type, properties)—Creates a new node as a child of the current node with the specified properties

  • createNode(name, type, properties, assocType)—Creates a new node of the specified type as a child of the current node with the given child association name and properties with that child association type

  • createNode(name, type, properties, assocType, assocName)—Creates a new node as a child of the current node containing the specified child association name, properties, and the given child association type and name

  • addNode(node)—Adds an existing node as a child of this node

  • removeNode(node)—Removes all parent-child relationships between two nodes; the child node will be cascade deleted if one of the associations was the primary association (the one with which the child node was created)

  • createAssociation(target, assocType)—Creates a new target association to the specified node with the given association type Qname

  • removeAssociation(target, assocType)—Removes the association to the specified node with the given association type Qname

  • remove()—Deletes the node discarding any variable or references to the ScriptNode. Returns true on success; otherwise, it is false. For example:

    mynode.remove();
  • copy(destination)—Copies the node to the specified destination node (excluding children of the source node); returns the newly copied ScriptNode instance on success or null if the copy fails

  • copy(destination, deepCopy)—Copies the node to the specified destination node (copies all child nodes of the source if the deepCopy argument is true; otherwise, only copies the source node itself); returns the copied ScriptNode instance on success or null if the copy fails reason. For example:

    var docCopy = document.copy(userhome);
  • move(destination)—Moves the node to the new parent destination; returns true on success or false on failure to move.

  • addAspect(aspect)—Adds a new aspect to the node where the type is a QName of the aspect to add in either fully qualified or short name form; returns true if the aspect was added successfully; returns false otherwise. For example:

    document.addAspect("cm:translatable");
  • addAspect(aspect, properties)—Adds a new aspect and properties to the node, allowing mandatory aspect properties to be supplied when the new aspect is applied. For example:

    var props = new Array(1);
    props["cm:template"] = myTemplateNode.nodeRef;
    document.addAspect("cm:templatable", props);
  • removeAspect(aspect)—Removes the specified aspect from the node

The ScriptContent API

The ScriptContent API provides several methods and properties related to node properties of type d:content; for example: document.properties.content

The following properties are available:

  • content—A read/write value representing the content as a string

  • mimetype—A read/write string value representing the MIME type of the content

  • encoding—A read/write string value representing the encoding of the content, such as "UTF-8"

  • size—A read-only long value representing the size in bytes of the content

  • url—A read-only string representing the download URL for the content

  • downloadUrl—A read-only string representing the download (as attachment) URL for the content

The following methods are available:

  • write(content)—Copies the content from the specified ScriptContent

  • guessMimetype(filename)—Guesses and applies the MIME type to the content based on the given file name

The Permission and Security API

The Permission and Security ScriptNode API features several methods and properties related to permissions in the repository. It is common to check for the appropriate user permissions on a node before it is accessed or modified.

The following property is available:

  • owner — The owner property of the node (as a UID)

The following methods are available:

  • hasPermission(permission)—Checks for permissions on the node; returns true if the user has the specified permission on the node.

  • getPermissions()—Returns a string of the permissions attached to a node in the format [ALLOWED|DENIED];[USERNAME|GROUPNAME];PERMISSION. For example: ALLOWED;kevinr;Consumer can be easily tokenized on the semicolon (;) character.

  • inheritsPermissions()—Returns true if the node currently inherits its permissions from the parent space, or false to indicate the permissions are set specifically on the node.

  • setInheritsPermissions(inherit)—Indicates that the node should inherit permissions from the parent node when set to true, or false to break the inheritance chain.

  • setPermission(permission)—Applies a permission for all users to the node.

  • setPermission(permission, authority)—Applies a permission for the specified authority (such as username or group) to the node.

  • removePermission(permission)—Removes a permission for all users from the node.

  • removePermission(permission, authority)—Removes a permission for the specified authority (such as username or group) from the node.

  • setOwner(userId)—Sets the owner of the node.

  • takeOwnership()—Takes ownership of the node.

  • getOwner()—Gets the owner of the node (as a UID).

The Check In/Check Out API

The Check in/Check out ScriptNode API provides methods for checking out, checking in, and cancelling the check-out of working copies.

Note

To record version history when using these methods, first add the cm:versionable aspect to a node.

The following methods are available:

  • checkout()—Performs a check-out operation of the node; returns the resulting working-copy node

  • checkout(destination)—Performs a check-out operation of the node to the specified destination; returns the resulting working copy node

  • checkin()—Performs a check-in operation on a working-copy node (copies the current state of the working copy to the original node, including any content updated in the working node); returns the original node that was previously checked out

  • checkin(description) —Performs a check-in operation on a working-copy node, applying the specified version history note text; returns the original node that was previously checked out

  • checkin(description, majorVersion) —Performs a check-in operation on a working-copy node, applying the specified version history note text and version (major or minor) increment; returns the original node that was previously checked out

  • cancelCheckout()—Cancels the check-out of a working-copy document, deleting the working copy and any changes made to it; returns the original node that was previously checked out

The Versions API

The Versions ScriptNode API provides several methods and properties for managing and retrieving the versions of a document.

The following properties are available:

  • isVersioned—A read-only Boolean property to determine if the document versioned

  • versionHistory—A read-only property for listing all versions of the document (in descending version-created date order)

  • createdDate—A read-only property representing the date on which the version was created

  • creator—A read-only property representing the username of the person who created the version

  • label—A read-only property representing the version label

  • type—A read-only property representing the version type (MAJOR, MINOR)

  • description—A read-only property representing the description (history comment) of the version

  • nodeRef—A read-only property representing the node reference of the document that was versioned

  • ScriptNode node—A read-only property representing the node as it was versioned

The following methods are available:

  • getVersion(label)—Retrieves a specific version of a document identified by label, or null if the label does not exist

  • createVersion(description, major)—Creates a version snapshot of the current document

The Transformation API

The following methods use the document transformation services available in Alfresco.

Note

The OpenOffice server is required for some document transformations.

  • transformDocument(mimetype)—Transforms a document to a new document MIME type format; returns the transformed document node if successful, or null if the transformation failed

  • transformDocument(mimetype,destination)—Transforms a document to a new document MIME type format; returns the transformed document node if successful, or null if the transformation failed

The following methods use the image transformation services available in Alfresco.

Note

To use the image transformation services, the ImageMagick components must be correctly installed and working. Please refer to the ImageMagick Web site for more-detailed information.

  • transformImage(mimetype)—Transforms an image to a new image format; returns the transformed image node if successful or null if the transformation failed

  • transformImage(mimetype,options)—Transforms an image to a new image format, applying the supplied ImageMagick options; returns the transformed image node if successful or null if the transformation failed

  • transformImage(mimetype,destination)—Transforms an image to a new image format; returns the transformed image node if successful or null if the transformation failed

  • transformImage(mimetype,options,destination)—Transforms an image to a new image format, applying the supplied ImageMagick options; returns the transformed image node if successful or null if the transformation failed

The following methods use the FreeMarker template-processing services available in Alfresco:

  • processTemplate(template)—Executes a FreeMarker template file against the node; returns a string as the result of the template execution

  • processTemplate(template,args)—Executes a FreeMarker template file against the node, passing the supplied array of name/value pair arguments to the template; returns a string as the result of the template execution

Note

The node is used as the context to the template. If this node is a document, it is set up as the document context object for the template with the parent space as the space context object for the template. If the node is a folder, it is set up only as the space context object for the template. An argument list can also be passed to the template and is available as the args object.

The Search API

The Search API provides direct access to repository-level search results and Saved Search results through the search root scope object. You can perform local searches using the ScriptNode APIs childByNamePath and childByXPath. Like the various node objects, the search object is part of the root scope.

The following methods are available:

  • luceneSearch(query)—Returns an array of ScriptNode objects found by the Alfresco repository full-text search. For example:

    var nodes = search.luceneSearch("TEXT:alfresco");
  • luceneSearch(store, query)—Returns an array of ScriptNode objects found by the Alfresco repository full-text search in the given store. For example:

    var nodes = search.luceneSearch("workspace://sitestore", "TEXT:site");
  • luceneSearch(query, sortColumn, asc)—Returns an array of ScriptNode objects satisfying the search criteria sorted by the specified sortColumn (the property name to sort on), and asc (true => ascending order, false => descending order). For example:

    var nodes = search.luceneSearch("TEXT:alfresco", "@cm:modified", false);

    Note

    The @ character is significant for the sortColumn parameter, and must be supplied as a prefix to the attribute name.

  • luceneSearch(store, query, sortColumn, asc)—Returns an array of ScriptNode objects satisfying the search criteria and sorted in the given store

  • xpathSearch(xpath)—Returns an array of ScriptNode objects found by the Alfresco repository XPath search

  • xpathSearch(store, xpath)—Returns an array of ScriptNode objects found by the Alfresco repository XPath search in the given store

  • savedSearch(node)—Returns an array of ScriptNode objects found by executing the Saved Search referenced by the supplied node object

  • savedSearch(noderef)—Returns an array of ScriptNode objects found by executing the Saved Search referenced by the supplied noderef string

  • findNode(NodeRef noderef)—Returns a single ScriptNode object as specified by the NodeRef object for that node or null if the search failed

  • findNode(noderef)—Returns a single ScriptNode object as specified by the string form of the NodeRef for that node, or returns null if the search failed

  • findNode(referenceType, reference)—A helper to convert a Web script request URL to a NodeRef. The ReferenceType can be node, path, or qname. The reference elements supplied depend on the reference type:

    • node{store_type}/{store_id}/{node_id}—Resolve to node through its node reference

    • path{store_type}/{store_id}/{path}—Resolve to node through its display path

    • qname{store_type}/{store_id}/{child_qname_path}—Resolve to node through its child QName path

  • ISO9075Encode(value)—A helper to encode a value into ISO9075-encoded format for encoding Lucene PATH statements

  • ISO9075Decode(value)—A helper to decode a value from ISO9075-encoded format

  • tagSearch(store, tag)—Returns an array of ScriptNode objects representing the nodes within the store that have the given tag applied; uses the default store (SpacesStore) if null value is supplied

  • query(search)—Returns an array of ScriptNode objects representing the search results

This interface supports multi-column sorting and any of the Alfresco search languages. Future versions of the API will allow the search definition objects to be extended with additional properties while maintaining backward compatibility.

The People API

The People API provides access to Alfresco people and groups.

The following methods are available:

  • createPerson(username)—Creates a person (cm:person) with the given user name; returns the person node created, or null if the user name already exists

  • createPerson(firstName, lastName, emailAddress, createUserAccount, setAccountEnabled)—Creates a person (cm:person) with a generated user name; returns the person node created, or null if the user cannot be created

  • getPerson(username)—Returns a single (cm:person) node associated with the specified user name, or null if the person does not exist

  • getGroup(groupname) —Returns a single (usr:authorityContainer) node associated with the specified group name, or null if the group does not exist

  • deleteGroup(group) —Removes a group from the system

  • createGroup(groupName)—Creates a new top-level group where groupName is the unique group name to create (do not prefix with GROUP_)

  • createGroup(parentGroup, groupName)—Creates a new group as a child of the specified parent group node (can be null for a top-level group)

  • addAuthority(parentGroup, authority) —Adds an authority (user or group) to the specified parent group

  • removeAuthority(parentGroup, authority) —Removes an authority from a group

  • getMembers(group)—Returns an array of person nodes belonging to the specified group (including all subgroups)

  • getMembers(group, recurse)—Returns an array of person nodes belonging to the specified group; only returns people of subgroups if recurse is specified as true

  • getContainerGroups(person)—Gets the groups that contain the specified authority

  • isAdmin(person)—Returns true if the specified user is an administrator authority

  • changePassword(oldpassword, newpassword)—Changes the password for the current user only (the old password must be supplied)

  • setPassword(userName, password)—Sets the password for the given user by an administrator authority

The Actions API

A root-level actions object is provided that allows invocation of Alfresco actions registered with the repository.

The following property is available:

  • registered—Returns an array of string objects representing the names of all registered actions

The following method is available:

  • create(name)—Returns the action for the given action name, or null if the action name is not registered

The ScriptAction API

A ScriptAction represents an Alfresco action registered within the repository.

The following properties are available:

  • name—Returns the name of the action

  • parameters—An associative array (map) of the parameters for the action. For example:

    mail.parameters.subject

The following method is available:

  • execute(node)—Executes the action against the specified node

    You can reuse the action and its parameters against many nodes by repeatedly invoking execute. Between invocations, the parameters of the action may be changed. The following is an example of executing the mail action:

    // create mail action
    var mail = actions.create("mail");
    mail.parameters.to = "[email protected]";
    mail.parameters.subject = "Hello from JavaScript";
    mail.parameters.from = "[email protected]";
    mail.parameters.template = root.childByNamePath(
    "Company Home/Data Dictionary/Email Templates/notify_user_email.ftl");
    mail.parameters.text = "some text, in case template is not found";
    // execute action against a document
    mail.execute(doc);

The Logging API

A root-level logger object provides the following methods to help debug scripts.

  • isLoggingEnabled()—Returns true if console logging is enabled.

  • To enable console logging, set the Log4J category of log4j.logger.org.alfresco.repo.jscript.ScriptLogger to DEBUG. This is in the log4j.properties file (Tomcat), or log4j.xml file (JBoss) on the Alfresco server.

  • log(string)—Logs a string message to the console.

The Session API

A root-level session object is provided to access the current logged-in user session ticket as a string value.

The following property is available:

  • ticket —Gets the current authentication ticket

The Classification API

The Classification API has two parts: manipulating classifications and manipulating the categories they contain. A root-level classification object is provided to return category nodes.

The following methods are available:

  • getAllCategoryNodes(aspect)—Gets an array of all the category nodes in the given classification

  • getAllClassificationAspects()—Gets an array of all the QNames (in prefix:localName form) of all classification aspects

  • createRootCategory(aspect, name)—Creates a new root category in the given classification

  • getRootCategories(aspect)—Gets all the root category nodes as an array for a given classification

The CategoryNode Object API

The CategoryNode objects returned from the classification object methods are extended from the standard JavaScript ScriptNode model to include category manipulation.

The following properties are available:

  • isCategory—Returns true if this is a category node; otherwise, it is false (supported by all nodes types)

  • categoryMembers—Gets an array of all the members of this category at any depth

  • subCategories—Gets an array of all the subcategories of this category at any depth

  • membersAndSubCategories—Gets an array of all the subcategories and members of this category at any depth

  • immediateCategoryMembers—Gets an array of all the immediate members of this category (only direct members of this category and not through subcategories)

  • immediateSubCategories—Gets an array of all the immediate subcategories of this category (only direct subcategories of this category and not through subcategories)

  • immediateMembersAndSubCategories—Gets an array of all the immediate subcategories and members of this category (only direct subcategories and members of this category and not through subcategories)

  • createSubCategory(name)—Creates a new subcategory from the current category node

  • removeCategory()—Deletes the current category node

WCM Web Projects

A root-level webprojects object provides script access to WCM functionality.

This API provides the following methods:

  • createWebProject(dnsName, name, title, description)—Creates a new Web project

  • getWebProject(WebProjectRef) —Gets a Web project

  • listWebProjects()—Lists all Web projects

  • listWebProjects(userName)—Lists all Web projects for which the specified user has membership

The WebProject Object API

The WCM WebProject API returns WebProject objects that represent individual Web projects.

The following properties are available:

  • name—The name of the Web project

  • title—The display name for the Web project

  • description—A description of the Web project

  • isTemplate—Determines if the Web project is a template

  • WebProjectRef — The unique reference for the Web project

The following methods are available:

  • getRoles()—Gets the roles for a Web project

  • save()—Updates the Web project

  • deleteWebProject()—Deletes the Web project and all contents

  • addMembership(userName, role)—Adds the specified user with the specified role to the Web project

  • removeMembership(userName)—Removes the specified user from a Web project

  • listMembers()—Lists the members of this project

  • createSandbox(userName)—Creates a user sandbox; does nothing if the user already has a sandbox

  • getSandboxes(userName)—Gets sandboxes for the Web project and user

  • getSandboxes()—Gets sandboxes for the Web project

The Sandbox Object API

The WCM WebProject API returns sandbox objects that represent individual user sandboxes.

The following properties are available:

  • name—The name of the sandbox

  • sandboxref—A unique reference of the sandbox

  • creator—The creator of the sandbox

  • storeNames—The store names

  • isStagingSandbox—Determines if this is a staging sandbox

  • isAuthorSandbox—Determines if this is an author sandbox

  • createdDateAsISO8601—The date the sandbox was created in ISO 8601 format

The following methods are available:

  • deleteSandbox()—Deletes the sandbox

  • submitAll(submitLabel, submitComment)—Submits the modified items directly to staging, bypassing any workflows that may have been configured for the Web project

  • submitAllWebApp(webApp, submitLabel, submitComment)—Submits the modified items for the specified web application directly to staging, bypassing any workflows that may have been configured for the Web project

  • submitAssets(assets, submitLabel, submitComment)—Submits the specified Asset objects directly to staging, bypassing any workflows that may have been configured for the Web project

  • submit(files, submitLabel, submitComment)—Submits the specified paths directly to staging, bypassing any workflows that may have been configured for the Web project

  • revertAll()—Reverts the modified items

  • revertAllWebApp(webApp)—Reverts the modified items for the specified Web application within the sandbox

  • revertAssets(assets)—Reverts the specified assets

  • revert(files)—Reverts the specified paths

  • getModifiedAssets()—Gets the modified assets within the sandbox

  • getModifiedAssetsWebApp(webApp)—Gets the modified assets for the specified Web application within the sandbox

  • getAsset(path)—Gets the asset

  • getAssetWebApp(webApp, path)—Gets the asset (path is relative to the Web application)

The WCM Asset Object API

The WCM Sandbox API returns Asset objects that represent individual file or folder assets within the sandbox.

The following properties are available:

  • creator— The user name of the creator of the asset

  • createdDate—The asset creation date

  • fileSize—The size of the file (in bytes)

  • name—The asset name

  • path—The absolute path of the asset, not relative to the web application. For example:

    /www/avm_webapps/root/index.html

  • isFile—Determines if this asset is a file

  • isFolder—Determines if this asset is a folder

  • isDeleted—Determines if this asset is deleted

  • isLocked—Determines if this asset is locked

  • lockOwner—The owner of the lock on the asset

  • createdDateAsISO8601—The asset creation date supplied as a string in ISO 8601 format

  • modifier—The user name of the modifier of the asset

  • modifiedDate—The date when the asset was last modified

  • modifiedDateAsISO8601—The date when the asset was modified, supplied in a string in ISO8601 format

The following methods are available:

  • rename(newName)—Renames this file or folder

  • move(newPath)—Moves this asset

Utility Methods

A root-level utils object is provided as a library of helper methods that are missing from generic JavaScript.

The following methods are available:

  • pad(string,length)—Pads a string with leading zeros to the specified length; returns the new string

  • getNodeFromString(noderef)—Returns a ScriptNode object representing the supplied NodeRef string

  • toBoolean(string)—Returns a Boolean object from a string value

  • shortQName(string)—Returns the short, or prefix, version of a long QName

THE SERVICES API

This section describes the Alfresco JavaScript Services API.

The Site Service

A site is a collaborative area for a unit of work or a project. The methods available for the Site service are grouped into siteservice and site object types.

The Site Service Object

The siteservice object provides the following methods:

  • createSite(site preset, shortName, title, description, visibility)—Creates a new site with specified visibility if set (PUBLIC, PRIVATE, or MODIFIED); returns the created site.

  • listSites(nameFilter, sitePresetFilter, size)—Lists the available sites in the repository; returns a list of the sites filtered, or all the available sites if no filters are specified. The optional size parameter specifies the maximum number of sites to return in the result; if 0 (default), all results are returned.

  • listUserSites(userName)—Lists all the sites to which the specified user has an explicit membership; returns a list of sites to which the user has an explicit membership.

  • getSite(shortName)—Gets a site for a provided short name; returns the site, or null if the site does not exist.

  • listSiteRoles()—Lists all the roles that can be assigned to a member of a site; returns the roles available to assign to a member of a site.

The Site Object

The site object provides the following properties:

  • shortName —The unique short name identifying the site (read-only)

  • sitePreset —The name of the site preset used to create the site (read-only)

  • title —The displayable title of the site

  • description —The displayable description of the site

  • node—The site node reference

  • visibility—The visibility of the site (PUBLIC, MODERATED, PRIVATE)

  • siteGroup—The site group name

  • sitePermissionGroups—A map of a role name mapped to the associated group name

The site object provides the following methods:

  • save()—Saves any outstanding updates to the site detail (required to save changes made to any properties of the site).

  • deleteSite()—Deletes the site; only a SiteManager role can delete a site.

  • listMembers(nameFilter, roleFilter)—Gets a map of members of the site filtered by user name (nameFilter) and/or user role (roleFilter) within the site; returns the list of members of a site with their roles, or all site members if no name or role filter is specified.

  • getMembersRole(userName)—Gets the role of a user on this site; returns the user's role if the user is a member of the site, or null if the user is not a member of the site.

  • isMember(userName)—Indicates whether a user is a member of the site; returns true if the user is a member of the site, or false otherwise.

  • setMembership(userName,role)— Sets the membership details for a user. If the user is not already a member of the site, they are added with the given role. If the user is already a member of the site, their role is updated to the new role.

  • removeMembership(userName)—Removes a user membership of the site.

    Note

    Only a site manager can modify and remove memberships. There must be at least one site manager at all times, and the last site manager cannot be removed.

  • getContainer(componentId)—Gets (or creates) the container folder (node) for the specified component identifier with the container type cm:folder.

  • getContainer(componentId, folderType)—Gets or creates the container folder for the specified component identifier (componentId) of the type either specified by the caller (cm:folder or a subtype) or cm:folder if a type is not specified; returns the name of the container folder, or null if the container cannot be created.

  • createContainer(componentId)—Creates a new site container of type cm:folder.

  • createContainer(componentId, folderType) —Creates a new site container of the given type (folderType), which should be a subtype of cm:folder.

  • createContainer(componentId, folderType, permissions)—Creates a new site container of the given type and applies the provided permissions (a map of authorities and permissions) to the created container.

  • hasContainer(componentId)—Determines if the container folder for the specified component exists; if true, the container folder exists.

  • setPermissions(node, permissions)—Sets the map of authorities and permissions on the provided node.

  • resetAllPermissions(node)—Resets any permissions that have been set on the node, deleting all permissions and setting the node to inherit permissions.

  • allowAllMembersCollaborate(node)—Allows all members of the site collaboration rights on the node.

  • denyAllAccess(node)—Denies access to all members of the site to the node, maintaining appropriate permissions for site managers.

  • getCustomProperty(name)—Gets the value of a custom property, or null if the custom property has not been set or does not exist.

  • getCustomProperties()—Gets a map of the custom properties of the site.

  • inviteModerated(inviteeComments, inviteeUserName, inviteeRole)—Creates a new moderated invitation to this Web site.

  • inviteNominated(inviteeFirstName, inviteeLastName, inviteeEmail, inviteeRole, serverPath, acceptUrl, rejectUrl)—Creates a new nominated invitation to this Web site for a new user who may not already be an Alfresco user.

  • inviteNominated(inviteeUserName, inviteeRole, serverPath, acceptUrl, rejectUrl)—Creates a new nominated invitation to this Web site for an existing user.

  • getInvitation(invitationId)—Gets an invitation to this Web site.

  • listInvitations()—Lists the outstanding invitations for this Web site.

  • listInvitations(props)—Lists the open invitations for this Web site with the specified properties.

The Activities Service

Activities refer to updates to content within a site, including uploaded files, blogs, discussions, calendars, and the team wiki. The methods available for the activities service are grouped around posting activities and the FeedControl object type.

The activities service provides the following methods.

  • postActivity(activityType, siteId, appTool, jsonActivityData)—Posts a custom activity type.

  • postActivity(activityType, siteId, appTool, nodeRef)—Posts a predefined activity type, looking up activity data asynchronously, including name, displayPath, typeQName, firstName, and lastName of posting user.

  • postActivity(activityType, siteId, appTool, nodeRef, beforeName)—Posts a predefined activity type, such as for a checked-out or renamed NodeRef; do not use this parameter for a deleted (or about-to-be-deleted) nodeRef.

  • postActivity(activityType, siteId, appTool, NodeRef, name, typeQName, parentNodeRef)—Posts a predefined activity, such as for the deleted NodeRef.

The FeedControl Object

The FeedControl object type provides the following methods:

  • setFeedControl(siteId, appToolId)—Sets the feed control for a site, an appTool, or a site/appTool combination for the current user

  • getFeedControls()—Gets the feed control for the current user; returns an array of user feed controls

  • unsetFeedControl(siteId, appToolId)—Unsets the feed control for the current user

The Tagging Service

A tag is a non-hierarchical keyword or term assigned to a piece of information. The properties and methods available for the Tagging service are grouped into the taggingService, TagScope, and TagDetails object types.

The TaggingService Object

The taggingService root-scoped object provides the following method:

  • getTags(storeref)—Gets all the tags available in a store; returns a list of the available tags

Extensions to the Existing ScriptNode

There are various properties and methods that are extensions to the existing ScriptNode. They provide an API to retrieve and manipulate tags on a node.

The following properties are available:

  • isTagScope—A read/write Boolean property indicating whether the node is a tag scope

  • tagScope—A read property that provides the nearest TagScope for the node (null if no tag scope is found)

  • tags—A read/write string array property of tags applied to this node (resets all tags when a value is specified)

The following methods are available:

  • clearTags()—Clears the tags of a node

  • addTag(tag)—Adds a tag to the node

  • addTags(tags)—Adds all the given tags to the node

  • removeTag(tag)—Removes a tag from the node

  • removeTags(tags)—Removes all the given tags from the node

  • childrenByTag(tag)—Gets all the (deep) children of this node that have the tag specified; returns the nodes that are the deep children of the node with the tag

Extensions to the Existing Search API

The Search API provides the following additional method:

  • tagSearch(store, tag)—Searches the store for all nodes with the given tag applied; returns the nodes with the tag applied

The TagScope Object

The extensions to the ScriptNode can return TagScope object types. They describe the tags scoped to a node.

The TagScope object type provides the following property:

  • tags—A read-only array containing the tag details in count order

The following methods are available:

  • getTopTags(topN)—Gets the top n tags ordered by count; returns the top n tag details ordered by count

  • getCount(tag)— Gets the count of a tag (0 if the tag is not present)

  • refresh()—Refreshes the tag scope

The TagDetails Object

The TagScope object can return TagDetails object types. They describe the name and count of the tag instances.

The TagDetails object type provides the following properties:

  • name—The name of the tag

  • count—The tag count

Thumbnail Services

A thumbnail is a transformation of content into a specified destination MIME type. This is most commonly an image of a particular size, but can also be, for example, a Flash rendition. This thumbnail is transformed and maintained by the Thumbnail service.

The Thumbnail Service

The Thumbnail service provides the following methods:

  • isThumbnailNameRegistered(thumbnailName)—Determines whether a given thumbnail name has been registered; returns true if the thumbnail name is registered, or false otherwise

  • getPlaceHolderResourcePath(thumbnailName)—Gets the resource path for the placeholder thumbnail for the given named thumbnail; returns a string of placeholder thumbnail resource path, or null if it is not set

Extensions to the Existing ScriptNode

The following are additional methods to the existing ScriptNode:

  • createThumbnail(thumbnailName,async)—Creates a thumbnail based on the definition registered for the provided thumbnail name. Returns the thumbnail script node if the async is false; otherwise it is null.

  • getThumbnail(thumbnailName)—Gets the given thumbnail name for the content property; returns the thumbnail.

  • getThumbnails()—Gets all the thumbnails for the content property of a given node; returns a list of thumbnails (empty if none are available).

  • getThumbnailDefinitions()—Returns an array of the names of the thumbnail definitions that can be applied to the content property of this node.

    Thumbnail definitions only appear in this list if they can produce a thumbnail for the content found in the content property. This is determined by looking at the MIME type of the content and the destination MIME type of the thumbnail.

The Thumbnail Object

The thumbnail object type extends the standard ScriptNode.

The following method is available:

  • updateThumbnail()—Updates all the thumbnails for a particular node

The Authority Service

The Authority service provides methods to retrieve groups. Authority is the general term to describe a group, user, or role.

The following methods are available:

  • getAllRootGroups()—Gets the root groups that do not have a parent group; returns the root groups (empty if there are no root groups).

  • getAllRootGroupsInZone(zone)—Gets all the root groups in the specified zone.

  • getGroup(shortName)—Gets a group given its short name; returns the authority, or null if it cannot be found.

  • createRootGroup(shortName, displayName)—Creates a new root group; returns the authority, or null if it cannot be found. There is a partial match on shortName with the characters "*" and "?". If this is empty, everything is matched.

  • searchGroups(shortNameFilter)—Searches for groups; returns the groups matching the query.

  • searchGroupsInZone(shortNameFilter, zone)— Searches for groups in the specified zone; returns groups matching the query.

The group Object

A group object represents an Alfresco group.

The group object provides the following properties:

  • authorityType—Gets the authority type

  • shortName—Gets the short name of the group

  • fullName—Gets the full name of the group

  • displayName—Changes the display name for this group (requires administrator permission)

  • allUsers—Gets the users contained within this group and its subgroups

  • allGroups—Gets all descendant subgroups

  • childUsers—Gets child users of this group

  • childGroups—Gets child groups of this group

  • parentGroups—Gets the immediate parents of this group

  • allParentGroups—Gets all the parents of this group

  • childAuthorities—Gets all the children of this group, regardless of type

  • getUserCount—Gets the number of users contained in this group

  • getGroupCount—Gets the number of child groups contained in this group

The following methods are available:

  • deleteGroup()—Deletes this group

  • isRootGroup()—Indicates whether the group is a root group

  • isAdminGroup()—Indicates whether the group is an administrator group

  • createGroup(shortName, displayName)—Creates a new group as a child of this group; returns the new group

  • removeGroup(shortName) —Removes a specified subgroup from this group

  • removeUser(shortName)—Removes a specified child user from this group

  • addAuthority(fullAuthorityName)—Adds authority as a child of this group

  • removeAuthority(fullAuthorityName)—Removes a child authority from this group

The user Object

A user object represents an Alfresco user. The user object provides the following properties:

  • authorityType—Gets the authority type (user, group, role)

  • shortName—Gets the short name of the user

  • fullName—Gets the full name of the user

  • displayName—Gets the display name of the user

Workflow Services

The Workflow JavaScript API lets you write JavaScript files to start and interact with workflows within Alfresco. Through the API, you can access and manage workflow definitions, instances, paths, tasks, and transitions.

The Workflow JavaScript API includes the ability to:

  • Create workflow packages

  • Start, cancel, or delete workflow instances

  • End and progress workflow paths to the next node with a specified transition

Note

The object model for this API is similar to that of the Advanced Workflow Java API. The relationships between the various types in this API are the same as the relationships between the various classes in the Advanced Workflow API. Each class in the Workflow JavaScript API mirrors a class in the Advanced Workflow API; however, the JavaScript classes are simpler and more easily accessible from JavaScript. All the JavaScript classes implement the serializable interface, which allows them to be stored in scriptable objects.

The Workflow Manager

The Workflow Manager is the entry point to the Workflow JavaScript API. It is the only object in this API exposed to the root scripting scope. In the root scripting scope, the WorkflowManager object is identified as workflow.

The Workflow Manager provides the following properties:

  • allDefinitions—Returns an array of all (old and current) versions of deployed workflow definitions (use latestDefinitions for current versions only)

  • assignedTasks—Returns an array of all tasks that are currently in progress assigned to the current user

  • completedTasks—Returns an array of all completed tasks assigned to the current user

  • latestDefinitions—Returns an array of the latest version of all deployed workflow definitions (use allDefinitions for all versions)

The Workflow Manager provides the following methods:

  • getDefinitionByName(name)—Returns the workflow definition with the given name, or null if no workflow definition with the given name exists

  • getDefinition(id)—Returns the workflow definition with the given ID, or null if no workflow definition with the given ID exists

  • getInstance(workflowInstanceId)—Returns the workflow instance with the given ID, or null if no workflow instance with the given ID exists

  • getPooledTasks(authority)—Returns an array of the pooled workflow task instances available to the given authority

  • getTask(id)—Returns the workflow task instance with the given ID, or returns null if no workflow task instance with the given ID exists. This method is identical to getTaskById.

  • getTaskById(id)—Returns the workflow task instance with the given ID or returns null if no workflow task instance with the given ID exists. This method is identical to getTask.

  • createPackage()—Creates a package (a container node that can store content associated with a workflow instance); returns a reference to the created container

JscriptWorkflowDefinition

The workflow definition is the type (or template) of a workflow process. A workflow process definition relates to a workflow instance like a Java-class definition relates to an instance of that class. You can use the workflow definition to create and start new workflow instances of that type, as well as to find all currently active instances of that type. A workflow definition has several properties, including ID, Name, Version, Title, and Description.

The following properties are available:

  • activeInstances—Returns an array of all active workflow instances for this workflow definition

  • description—Returns a description for this workflow definition

  • id—Returns an ID for this workflow definition

  • name—Returns a string name for this workflow definition

  • title—Returns a title for this workflow definition

  • version—Returns a version number for this workflow definition

The following methods are available:

  • startWorkflow(properties)—Creates and starts a new workflow instance of the workflow definition type; returns the workflow path for the created instance.

    This does not set a package container. The properties parameter is ignored if it is not of type ScriptableObject.

  • startWorkflow(properties, package)—Creates and starts a new workflow instance of the workflow definition type; returns the workflow path for the created instance.

JscriptWorkflowInstance

The workflow instance holds various data about a workflow, such as its start date, due date, current state, and so on. A workflow instance can be cancelled (made inactive), or deleted.

JscriptWorkflowInstance provides the following properties:

  • description—Returns the description for this workflow instance

  • endDate—Returns the date when this workflow instance ended

  • id—Returns the ID for this workflow instance

  • paths—Returns an array containing all the paths associated with this workflow instance

  • startDate—Returns the date when this workflow instance started

  • isActive—Returns true if the workflow instance is in progress; otherwise, returns false

The following methods are available:

  • cancel()—Cancels the workflow instance

  • delete()—Deletes the workflow instance

JscriptWorkflowNode

A workflow node is a single point in the workflow process. Some workflow nodes are task nodes with associated tasks that must be completed before the workflow can transition to the next node.

JscriptWorkflowNode provides the following properties:

  • description—Returns the description for this workflow node

  • name—Returns the name for this workflow node

  • title—Returns the title for this workflow node

  • transitions—Returns the list of transitions that are available for this node

  • isTaskNode—Returns true if this node is a task node; otherwise, returns false

JscriptWorkflowPath

A workflow path represents the current state (position) of a workflow instance. The path stores the current position in the workflow as well as the path taken through the workflow to reach this point. A workflow in progress can have multiple workflow paths if the process contains any forking nodes. The workflow path can be signaled to transition to the next node in the process.

JscriptWorkflowPath provides the following properties:

  • id—Returns the ID for this workflow path

  • instance—Returns the workflow instance to which this workflow path belongs

  • node—Returns the current node (position) of the workflow path

  • tasks—Returns an array of all the task instances associated with this workflow path

  • isActive—Returns true if this workflow path is in progress; otherwise, returns false

JscriptWorkflowPath provides the following method:

  • signal(transitionId)—Signals the workflow path to transition to the next node; returns the newly transitioned workflow path

JscriptWorkflowTask

JScriptWorkflowTask represents a specific instance of a workflow task as opposed to a workflow task definition (task type). A workflow task instance represents a user action that is usually something that cannot be automated in the workflow. Task instances can be associated with workflow nodes within the process definition. When the workflow path reaches a node with an associated task, it will not progress until the task is complete and the user signals a transition.

A workflow task instance can be signaled with a transition, progressing the workflow path to the next node with the specified transition. Some typical use cases of tasks include reviewing and approving documents, editing and appending documents, and marking exam papers.

JscriptWorkflowTask provides the following properties:

  • description—Returns the description for the workflow task instance

  • id—Returns the ID for the workflow task instance

  • name—Returns the name for the workflow task instance

  • packageResources—Returns an array of the content stored in the package container associated with this workflow task instance

  • properties—Returns a map containing all the properties associated with this task instance

  • title—Returns the title for the workflow task instance

  • transitions—Returns a map containing all the transition IDs (map keys) and transition titles (map values) for the task instance

  • isPooled—Returns true if this is a pooled task instance; otherwise, returns false

JscriptWorkflowTask provides the following method:

  • endTask(transitionId)—Ends the task and signals the associated workflow path to progress to the next node using the specified transition

JscriptWorkflowTransition

The workflow transition is a simple Data Transfer Object (DTO) representing a single transition type.

JscriptWorkflowTransition provides the following properties:

  • description—Returns the description for the workflow path

  • id—Returns the ID for the workflow path

  • title—Returns the title for the workflow path

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.49.243