Using the UserDirectoryService
Information
This explains basic usage of the Sakai UserDirectoryService. This service is used to find out things like who the current user accessing your app is and get meta data about users.
- Trunk javadocs:
- Trunk source location: https://source.sakaiproject.org/svn/user/trunk/
Accessing the UserDirectoryService
- You can use Spring Framework to inject the service or use the cover
- Using Spring to get the service for your class (e.g. YourAppClass) (recommended)
- Add the UserDirectoryService bean to the bean for YourAppClass
<bean id="org.sakaiproject.yourapp.logic.YourAppClass" class="org.sakaiproject.yourapp.logic.impl.YourAppClassImpl"> <property name="userDirectoryService" ref="org.sakaiproject.user.api.UserDirectoryService" /> </bean>
- Add a variable and setter to YourAppClass to use the service in like so:
private UserDirectoryService userDirectoryService; public void setUserDirectoryService(UserDirectoryService userDirectoryService) { this.userDirectoryService = userDirectoryService; }
- Add the UserDirectoryService bean to the bean for YourAppClass
- Using the Component Manager to get the service
- Note: This is not the recommended method, you should be using Spring to inject the service
- Use the CM cover to get the service
import org.sakaiproject.component.cover.ComponentManager; ... private UserDirectoryService userDirectoryService; ... userDirectoryService = (UserDirectoryService) ComponentManager.get(UserDirectoryService.class);
Getting the current user
- Use the service variable to access the service and get the current User
User currentUser = userDirectoryService.getCurrentUser();
- Note: This returns a Sakai User object
- Note: If you just need the userId then do this:
String currentUserId = userDirectoryService.getCurrentUser().getId();
Getting information about a User
- If you have a Sakai userId (String) and want to get more information about the user you can do the following to get the Sakai User object
try { User user = userDirectoryService.getUser(userId); } catch (UserNotDefinedException e) { throw new IllegalArgumentException("Could not find user with id: " + userId); }
- If you want to find a Sakai User based on an email address you can do the following:
Collection c = userDirectoryService.findUsersByEmail(userEmail); if (!c.isEmpty()) { User aUser = (User) c.iterator().next(); } else { throw new IllegalArgumentException("Could not find user by email: " + userEmail); }