OpenKM Scripting – Adding UserRole

A while back, when I first starting working with OpenKM, I accidentally removed the UserRole role from the root directory. For the longest time, I had know clue how to add the UserRole role back to that folder, or any other folder for that matter. Today, after playing around with the example scripts, I developed the following script that can be run from the Administrators tab:

import com.openkm.api.OKMAuth;
import com.openkm.core.JcrSessionManager;
import com.openkm.bean.Permission;

String token = JcrSessionManager.getInstance().getSystemToken();
OKMAuth.getInstance().grantRole(token, "/okm:root", "UserRole", Permission.READ, false);

JavaScript Snippet – String.prototype.hashCode()

The following prototype function mimics the hashCode() function of java.lang.String in Java:

String.prototype.hashCode = function() {
  for(var ret = 0, i = 0, len = this.length; i < len; i++) {
    ret = (31 * ret + this.charCodeAt(i)) << 0;
  }
  return ret;
};

Depending on the version of Java that you are running, what is returned from this function may not be the same thing that is returned in Java. On the other hand, this implementation is computationally equivalent to the algorithm shown on this Java doc page. As you may notice, due to the limit on an int in Java, I imposed the same limit on the size of the number returned by this function. The number returned will always be in the -2^31 to 2^31-1 range.

Here are some example JavaScript calls:

alert("H".hashCode()); // 72
alert("Chris West".hashCode());  // -438087208
alert("Hello world!!!".hashCode());  // 638403293
alert("This is a Java string".hashCode());  // 586653468

Try using the hashCode() function on the above strings in Java and see if the returned values match. They did for me:

public class test{
  public static void main(String args[]) {
    System.out.println("If true 4 times, everything is good:");
    System.out.println("H".hashCode() == 72);
    System.out.println("Chris West".hashCode() == -438087208);
    System.out.println("Hello world!!!".hashCode() == 638403293);
    System.out.println("This is a Java string".hashCode() == 586653468);
  }
}