Child pages
  • Using the UserDirectoryService
Skip to end of metadata
Go to start of metadata


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.

Accessing the UserDirectoryService

  • You can use Spring Framework to inject the service or use the cover
  1. Using Spring to get the service for your class (e.g. YourAppClass) (recommended)
    1. Add the UserDirectoryService bean to the bean for YourAppClass
      <bean id="org.sakaiproject.yourapp.logic.YourAppClass"
      	<property name="userDirectoryService"
      		ref="org.sakaiproject.user.api.UserDirectoryService" />
    2. 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;
  2. Using the Component Manager to get the service
    • Note: This is not the recommended method, you should be using Spring to inject the service
    1. 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

  1. 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

  1. 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);
  2. 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);
  • No labels