Scripting - OpenKM 5.1

From OpenKM Documentation
Jump to: navigation, search

Scripting is an advanced feature - a sort of experimental one - that enables administrators to execute some BeanShell scripts in folders, fired on every notified event ( for example uploading documents ). It could be useful for performing automatic operations at repository level.

Scripting can be set by folder or document. You need to go to Administration > Repository view and browse the repository at low level. Be careful because an error can damage the document repository! When you have located the right place, select Scripting: Set script and a new scripting property will be added to the node. This new property can be edited to set your custom BeanShell code.

RepositoryView Scripting.png

Nota clasica.png OpenKM uses BeanShell. For more information point your browser to

BeanShell is a small, free, embeddable Java source interpreter with object scripting language features, written in Java. BeanShell dynamically executes standard Java syntax and extends it with common scripting conveniences such as loose types, commands, and method closures like those in Perl and JavaScript.

Okm admin 003.jpeg

Starting with OpenKM 5.0 you can also execute a custom script when OpenKM starts or stops. To do so, just create a start.bsh (and / or stop.bsh) file in $JBOSS_HOME. For example, we use this feature to create a complete environment (create custom users, register property groups, register workflow) each time the OpenKM demo is reinitialized.

Variable substitution

  • java.lang.String eventType - says the event that has fired the script. See below for event types.
  • javax.jcr.Session session - users session that executes the script.
  • javax.jcr.Node eventNode - node that causes the event.
  • javax.jcr.Node scriptNode - node where is stored the script.

Events types

Document related


Folder related


Mail related


Property related



Nota idea.png To register these examples you must go to repository view, select some folder for example /okm:root/Books/ and set script to enable mixing. A new property will appear - okm:scripCode. Edit it and paste the code from the scripting example.

Nota clasica.png If you are using OpenKM 4.1 (or previous), the right package is "es.git.openkm". The package "com.openkm" is valid starting at OpenKM 5.0

Automatic renaming of document

String parent = com.openkm.util.FileUtils.getParent(eventNode.getPath());
session.move(eventNode.getPath(), parent+"/renamed_document.doc");;

Automatic adding of keyword

eventNode.setProperty("okm:keywords", new String[]{"maligno"});;

Change log level

import org.apache.log4j.*;

Logger log = Logger.getLogger("com.openkm.module");

Reload log configuration

This sample work-as-is in OpenKM-LTE.

import org.apache.log4j.*;
import com.openkm.util.*;

String filename = ServerDetector.getHomeDir() + "/lib/";
new PropertyConfigurator().doConfigure(filename, LogManager.getLoggerRepository());

Purge all users trash

import com.openkm.api.*;
import com.openkm.core.*;
import com.openkm.bean.*;

String token = JcrSessionManager.getInstance().getSystemToken();

for (Folder trash : OKMFolder.getInstance().getChilds(token, "/okm:trash")) {
    print("Trash: " + trash.getPath()+"<br/>");
    for (Folder fld : OKMFolder.getInstance().getChilds(token, trash.getPath())) {
        print("About to delete folder: " + fld.getPath() + "<br/>");
        OKMFolder.getInstance().purge(token, fld.getPath());
    for (Document doc : OKMDocument.getInstance().getChilds(token, trash.getPath())) {
        print("About to delete document: " + doc.getPath() + "<br/>");
        OKMDocument.getInstance().purge(token, doc.getPath());
    for (Mail mail : OKMMail.getInstance().getChilds(token, trash.getPath())) {
        print("About to delete mail: " + mail.getPath() + "<br/>");
        OKMMail.getInstance().purge(token, mail.getPath());

Other alternative method:

import javax.jcr.*;
import com.openkm.core.*;
import com.openkm.bean.*;
import com.openkm.module.base.*;
String token = JcrSessionManager.getInstance().getSystemToken();
Session session = JcrSessionManager.getInstance().get(token);
Node trash = session.getRootNode().getNode(Repository.TRASH);
for (NodeIterator it = trash.getNodes(); it.hasNext(); ) {
    Node userTrash = it.nextNode();
    print("User Trash: " + userTrash.getPath() + "<br/>");
    for (NodeIterator itut = userTrash.getNodes(); itut.hasNext(); ) {
        Node child = itut.nextNode();
        print("About to delete: " + child.getPath() + "<br/>");
        if (child.isNodeType(Document.TYPE)) {
            BaseDocumentModule.purge(session, child.getParent(), child);
        } else if (child.isNodeType(Folder.TYPE)) {
            BaseFolderModule.purge(session, child);

You can see also a modified version which runs on the older OpenKM 5.0 branch at Forum: Purge trash of all users.

Using Beanshell to move Mails

The Script should check a specific Mail folder ("Docs") and move all the mails in another folder ("okm:root/Mails") in the Taxonomy. This runs as a Cronjob.

import javax.jcr.*;
import com.openkm.core.*;
import com.openkm.bean.*;
import com.openkm.module.*;

String token = JcrSessionManager.getInstance().getSystemToken();
Session session = JcrSessionManager.getInstance().get(token);

Node okmmail = session.getRootNode().getNode(Repository.MAIL);
Node okmroot = session.getRootNode().getNode(Repository.ROOT);

for (NodeIterator it = okmmail.getNodes(); it.hasNext(); ) {
  Node userMailFolder = it.nextNode();
  if( userMailFolder.getPath().equals("/okm:mail/Docs") ) {
    //Check the mail in the "Docs" folder
    for (NodeIterator itut = userMailFolder.getNodes(); itut.hasNext(); ) {
      Node mail = itut.nextNode();
      String name = mail.getName();
      //Check the keyword
      int available = name.indexOf("al");
      if (available != -1){
        session.move(mail.getPath(), okmroot.getPath() + "/alFolder/" + mail.getName());;
      available = name.indexOf("ka");
      if (available != -1){
        session.move(mail.getPath(), okmroot.getPath() + "/kaFolder/" + mail.getName());;

See related forum topic Using Beanshell to move Mails.

After uploading a file, remove all rights - except read - to all users but mantain to uploader

The Script should remove all rights to all users and roles - except read right - and will retain existing privileges of the uploader user.

import java.util.Map;
import com.openkm.api.OKMAuth;
import com.openkm.bean.Permission;

if (eventType.equals("CREATE_DOCUMENT")) {
	String userId = session.getUserID();
	String path = eventNode.getPath();
	OKMAuth oKMAuth = OKMAuth.getInstance();
	// All Roles only will continue having read grants
	Map hm = oKMAuth.getGrantedRoles(null, path);
	for (String roleName : hm.keySet()) {
		oKMAuth.revokeRole(null, path, roleName, Permission.WRITE, false);
		oKMAuth.revokeRole(null, path, roleName, Permission.DELETE, false);
		oKMAuth.revokeRole(null, path, roleName, Permission.SECURITY, false);
	// All users only will continue having read grants
	hm = oKMAuth.getGrantedUsers(null, path);
	for (String userName : hm.keySet()) {
		if (!session.getUserID().equals(userName)) {
			oKMAuth.revokeUser(null, path, userName, Permission.WRITE, false);
			oKMAuth.revokeUser(null, path, userName, Permission.DELETE, false);
			oKMAuth.revokeUser(null, path, userName, Permission.SECURITY, false);

Show repository stats

import com.openkm.bean.*;
import com.openkm.core.*;
import com.openkm.util.*;

String systemToken = JcrSessionManager.getInstance().getSystemToken();
print("Token: " + systemToken + "<br/>");
StatsInfo si = new DirectStatsModule().getDocumentsSizeByContext(systemToken);

for (long size : si.getSizes()) {
    print("StatsInfo.size: " + FormatUtil.formatSize(size) + "<br/>");

for (double percent : si.getPercents()) {
    print("StatsInfo.percent: " + percent + "<br/>");

Update repository stats

import com.openkm.core.*;

new RepositoryInfo().run();

Force datastore garbage collector

import com.openkm.core.*;

new DataStoreGarbageCollector().run();

Create a folder node (low level)

import javax.jcr.*;

String name = "newFolder";
Session session = DirectRepositoryModule.getSystemSession();

Node node = session.getRootNode().addNode(name, "okm:folder");
node.setProperty("okm:author", session.getUserID());
node.setProperty("okm:name", name);
node.setProperty("okm:authUsersRead", new String[] { session.getUserID() });
node.setProperty("okm:authUsersWrite", new String[] { session.getUserID() });
node.setProperty("okm:authUsersDelete", new String[] { session.getUserID() });
node.setProperty("okm:authUsersSecurity", new String[] { session.getUserID() });
node.setProperty("okm:authRolesRead", new String[] { "UserRole" });
node.setProperty("okm:authRolesWrite", new String[] { "UserRole" });
node.setProperty("okm:authRolesDelete", new String[] { "UserRole" });
node.setProperty("okm:authRolesSecurity", new String[] { "UserRole" });


Import reports from a folder

Import reports from $JBOSS_HOME/reports and also enable them in the default profile.

import java.sql.*;
import org.hibernate.*;
import com.openkm.core.*;
import com.openkm.util.*;
import com.openkm.dao.*;

Session hbmSession = HibernateUtil.getSessionFactory().openSession();
Connection con = hbmSession.connection();
Statement st = con.createStatement();
File reports = new File(Config.HOME_DIR + "/reports");

try {
    if (reports.isDirectory()) {
        for (File rep : reports.listFiles()) {
            int id = ReportDAO.createFromFile(rep, FileUtils.getFileName(rep.getName()), true);
            String sql = "insert into OKM_PROFILE_MSC_REPORT (PRP_ID, PRP_REPORT) values (1, " + id + ")";
            LegacyDAO.execute(con, sql);
} catch (Exception e) {
} finally {

Reset user document size

import com.openkm.dao.bean.cache.*;
import com.openkm.cache.*;

UserItems ui = UserItemsManager.get("okmAdmin");

Refresh user items

import com.openkm.cache.*;


Create some folders and set property group

import com.openkm.api.*;

for (int i=0; i < 10; i++) {
  String path = "/okm:root/fld_" + i;
  OKMFolder.getInstance().createSimple(null, path);
  OKMPropertyGroup.getInstance().addGroup(null, path, "okg:technology");

Show number of documents, folders and size from a given path

import com.openkm.bean.*;
import com.openkm.util.*;
import com.openkm.api.*;

ContentInfo ci = OKMFolder.getInstance().getContentInfo(null, "/okm:root/path/to/folder");
print("Folders: " + ci.getFolders() + "<br/>");
print("Documents: " + ci.getDocuments() + "<br/>");
print("Size: " + FormatUtil.formatSize(ci.getSize()) + "<br/>");

Automatic importing data from OpenKM server

import javax.jcr.*;
import com.openkm.core.*;
import com.openkm.api.*;

String token = JcrSessionManager.getInstance().getSystemToken();
Session session = JcrSessionManager.getInstance().get(token);
OKMDocument document = OKMDocument.getInstance();
OKMFolder folder = OKMFolder.getInstance();

public void autoImport(String okmPath, File fldpath) {
  try {
    print("Scanning " + fldpath.getName() + "<br/>");

    for (File file : fldpath.listFiles()) {
      print("Importing " + file.getName() + "<br/>");

      try {
        if (file.isDirectory()) {
          try {
            folder.createSimple(token, okmPath + file.getName());
          } catch (ItemExistsException ie) {
            // Folder already exists - just ignore exception
          autoImport( okmPath + file.getName() + "/", file);
        } else {
          // Check if file is still being written to
          long length = file.length();
          if (file.length() > length) continue;  // Skip file this time

          document.createSimple(token, okmPath + file.getName(), new FileInputStream(file));
        print("Created " + okmPath + file.getName() + "<br/>");
      } catch (Exception e) {
        print ("Exception:" + e + "<br/>");
        // Something bad happened to prevent import. Skip to next file.

  } catch (Exception e) {
    print("Exception: " + e + "<br/>");

autoImport("/okm:root/Scans/", new File("/home/scanner/scans"));

More info at forum contributor.