sudo

Peter_Jodeleit
Crownpeak employee
Crownpeak employee
4 0 697

I've seen some code in the past where a 'sudo' like function is simulated. All solutions I stumbled upon implemented this by creating a new connection with the ConnectionManager.

Beside the obvious drawbacks - hard coded host, port, and password parameters - there are some more subtle ones. E.g. you have to ensure that the connection is closed on all possible control flows of your code. And even less obvious: The so created connection uses another ClassLoader than your 'main' connection. This is getting messy if you want to transfer data between connections. If you have no custom libraries all works out perfectly. But when a custom component is involved all of suddenly - bang, ClassCastException. Or something like java.lang.IllegalArgumentException: object is not an instance of declaring class. Or some other obscure exception, masking the root cause: Mixing instances of the same type from different ClassLoader instances.

So how to avoid these issues? The simple way ist to use a remote connection. Just define a 'remote' connection to the same project in the project settings and use this from your code.

With this simple solution the target user is fixed. If you want to choose the target user you could use the above mentioned method with an ad-hoc configuration. Here is a code-example how to achieve this (API-Level FS v5.0):

public static UserService sudo(final UserService userService, final String userName, final String password) {

     final RemoteProjectConfiguration rpc = new RemoteProjectConfiguration();

     final Project project = userService.getProject();

     rpc.setSymbolicName("local." + project.getName() + "." + userName);

     rpc.setLoginUser(userName, password); // v5 API, for v4.2 use rpc.setLoginName(userName) and rpc.setLoginPassword(password);

     final Connection sudoConnection = userService.getConnection().getRemoteConnection(rpc);

     return sudoConnection.getProjectById(project.getId()).getUserService();

}

Input paramters are userService and user credentials, return value is the UserService instance 'running' with the provided user credentials.

Version history
Last update:
‎11-20-2012 02:29 AM
Updated by: