Sunday, March 28, 2010

Perform repository actions as administrator in a transaction

I have faced the need to run a code as admin several times and every time i needed to look for how this was done correctly. Let's put a stick on my wall :-)


you will need:
  1. An AuthenticationUtil for handling the Authentication as and access of the method as a given user: runAs.
  2. A RetryingTransactionHelper to handle transactions requirements
  3. optionally I use here the synchronized modificator for the specific need of this example.

public synchronized Long getNextContractNumber() {
return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Long>() {
public Long doWork() throws Exception {
Long actualValue= null;
RetryingTransactionCallback<Long> transaction = new RetryingTransactionCallback<Long>() {
public Long execute() throws Exception {

List<String> currentNumberPathNames = getPathNames(currentNumberNodePath);
final NodeRef currentNumberNode = getNodeFromPathNames(currentNumberPathNames);
Long currentValue = (Long) nodeService.getProperty(currentNumberNode, PhagModel.PROP_CURRENT_NUMBER);
Long nextValue = currentValue + 1 ;
nodeService.setProperty(currentNumberNode, PhagModel.PROP_CURRENT_NUMBER, nextValue);
return nextValue;
}
};
actualValue = getTransactionHelper().doInTransaction(transaction);
return actualValue;
}
}, AuthenticationUtil.getAdminUserName());
}
it is a useful tool, it might certainly be useful for many.

No comments: