Execute code with admin permissions in Liferay


Execute code with admin permissions in Liferay

There will be business need to customize liferay behavior and to create admin portlets that  mimic liferay functionalities such as create site and role etc.   but you may wonder that you will get empty site templates through code and exception while updating liferay core functionalities.

Below is sample code executes with admin privileges:

PermissionChecker currentPermisionChecker = PermissionThreadLocal.getPermissionChecker();
Role adminRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),"Administrator");
List<User> adminUsers = UserLocalServiceUtil.getRoleUsers(adminRole.getRoleId());
PrincipalThreadLocal.setName(adminUsers.iterator().next().getUserId());
PermissionChecker checker =PermissionCheckerFactoryUtil.create(adminUsers.iterator().next());
PermissionThreadLocal.setPermissionChecker(checker);

 // Start your code
This example pulls list of site templates
List<LayoutSetPrototype> layoutSetPrototypes = LayoutSetPrototypeServiceUtil.search(company.getCompanyId(), Boolean.TRUE, null);
//End your code
PermissionThreadLocal.setPermissionChecker(currentPermisionChecker);