Liferay Beanshell to understand Liferay API

Objective of this article: Understand Liferay Beanshell feature.

Use of Beanshell: It allows us to execute java code directly from Liferay UI.

Beanshell is a Java scripting language that’s designed to run Java code with little or no changes.  Beanshell doesn’t support the use of Java Generics.

 
Liferay has a great feature to run java code from the UI. Consider you want to check some java API then beanshell is very handy to use. Because for using beanshell you no need to develop anything. You can just run your liferay API directly. 

To use beanshell go to your control panel. Access the beanshell as shown in below screen shot

beanshell

Below are the implicit objects that we can use in beanshell

  • portletConfig 
  • portletContext 
  • actionRequest 
  • actionResponse
  • out
Now lets run some Liferay API from the beanshell
 
1. Display the total number of users:
     import com.liferay.portal.model.User;
     import com.liferay.portal.service.UserLocalServiceUtil;
     import java.util.List;

     int userCount = UserLocalServiceUtil.getUsersCount();
     out.println(userCount);

 

run-code
2. Find the company ID
   import com.liferay.portal.util.PortalUtil;
   long companyId = PortalUtil.getCompanyId(actionRequest );
   out.println("The comapny Id is : "+companyId);
3. Get current user object
 
   import com.liferay.portal.util.PortalUtil;
   import com.liferay.portal.model.User;

   User user = PortalUtil.getUser(actionRequest );
   out.println("First Name :"+user.getFirstName());
   out.println("Last Name :"+user.getLastName());
   out.println("Full Name :"+user.getFullName());

 

4. Get the version of your Liferay
 
   import com.liferay.portal.kernel.util.ReleaseInfo;
   String version = ReleaseInfo.getVersion();
   out.println("The Liferay Version :"+version);
5. Get theme
  
   import com.liferay.portal.theme.ThemeDisplay ;
   import com.liferay.portal.util.WebKeys;
   import com.liferay.portal.model.Theme;
   ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
   Theme theme = themeDisplay.getTheme();
   out.println("Current Theme: "+theme.getName());
Here in this session I have given only basics of using beanshell. However you can use this feature according to your requirements. For example consider you have 10,000 users in your portal and now you want update each user with a particular role. In this case you can use this feature instead of doing it manually.

 

Limitation:
This feature can be used only for Liferay API as well as liferay default services. You will not be able to test your own custom services which are developed as plugin portlet.

About The Author

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top
%d