Because every record is subject to security, change to a user you know has the appropriate rights to ensure that your code runs. To execute code regardless of your functional or record security rights, you can run code as if you are the system user.
Note: If you want code to fail if the current user does not have the appropriate rights, you do not need to run code as the system user.
The system user, which has the username "system" and contact name "system, system" includes the following characteristics:
•Has all rights at all times.
•Cannot be added to a group.
•Cannot be denied security rights in a record's Security tab.
•Can always execute any method in the API.
To run code as the system user inside a call, use utilityService.runAsSystemUser().
UtilityService includes four runAsSystemUser() methods. The method you use depends on whether you want to return data and/or execute additional code if the call throws an exception.
The following code snippet indicates how to execute code as a system user without returning any results:
utilityService.runAsSystemUser(new Callable() { public void call() { // Place your code here. } }); |
The following code snippet indicates how to execute code as a system user and return data:
String username = utilityService.runAsSystemUser(new CallableWithReturn<String>() { public String call() { String answer = ""; // Place your code here. return answer; } }); |
The following code snippet indicates how to execute code as a system user without returning any results and also executing additional code if the call throws an exception:
try { utilityService.runAsSystemUser(new CallableWithException<FileNotFoundException> callable() { public void call() throws FileNotFoundException { throw new FileNotFoundException(); } }); } catch (FileNotFoundException e) { System.out.println("Couldn't find file!"); } |
You can combine the last two code snippets to execute code that returns data or that executes additional code in the case of an error.