Blog Post

...

Liferay get administrator user programmatically in Java

If you need to retrieve a Liferay User with Administrator role in your Java code, then this article for you. To make it work we'll use a few defined Liferay's LocalServiceUtil classes. At the time of this article writing I've used Liferay 6.x version, but LocalServiceUtils appeared since 5.0 version, and PortalUtil class exist since 6.0 version only (can be easily substituted). That means that proposed approach will work on Liferay 5.0 and higher.
At the beginning we need to get an Administrator role within some Liferay company:

 

    public static Role getRoleById(final long companyId, final String roleStrId) {
        try {
            return RoleLocalServiceUtil.getRole(companyId, roleStrId);
        } catch (final Exception e) {
            log.error("Utils::getRoleById Exception", e);
        }
        return null;
    }

 

To get a default companyId for current portal we can use com.liferay.portal.util.PortalUtil (since Liferay 6.0) or specify this companyId directly. Also RoleConstants.ADMINISTRATOR used to refer to predefined Liferay roles:

import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portal.model.RoleConstants;

    public static User getAdmin() {
        final long companyId = PortalUtil.getDefaultCompanyId();
        Role role = null;
        try {
            role = getRoleById(companyId, RoleConstants.ADMINISTRATOR);
            for (final User admin : UserLocalServiceUtil.getRoleUsers(role
                    .getRoleId())) {
                return admin;
            }
        } catch (final Exception e) {
            log.error("Utils::getAdmin Exception", e);
        }
        return null;
    }

Within this function we retrieve a list of all users with Administrator role and then return the first admin as a result of this function. That’s it.

Comments (0)

Tags: liferay


0 comments

Leave a Comment