Wednesday, October 21, 2015

Liferay Setting Individual Resource Permissions on Roles

Liferay have good permission system that can restrict the access over the resources. Liferay have set of permission actions for each resource. In Liferay prospective resource may be portlet, page, model object and other resources like images, files.

We have two important tables which all manage Liferay permission system


ResouceAction

ResourcePermission


Important Util Classes


ResourcePermissionServiceUtil

ResourceActionLocalServiceUtil


To set Individual Resource Permission on role we will use following Methods
Individual Resource Permissions


void com.liferay.portal.service.ResourcePermissionServiceUtil.setIndividualResourcePermissions(long groupId, long companyId, String name, String primKey, long roleId, String[] actionIds) throws PortalException, SystemException


Updates the role's permissions at the scope, setting the actions that can be performed on resources of the type. Existing actions are replaced.

This method can be used to set permissions at any scope, but it is generally only used at the individual scope. For example, it could be used to set the guest permissions on a blog post.

Depending on the scope, the value of primKey will have different meanings. For more information, see com.liferay.portal.model.impl.ResourcePermissionImpl.

Parameters:
groupId the primary key of the group

companyId the primary key of the company

name the resource's name, which can be either a model class name or a portlet ID for example  com.liferay.portlet.documentlibrary.model.DLFileEntry

primKey the primary key example  FileEntry Id

roleId the primary key of the role

actionIds the action IDs of the actions (VIEW,DELETE,ADD like that)

Throws:

PortalException - if the user did not have permission to set resource permissions, or if a role with the primary key or a resource action with the name and action ID could not be found

SystemException - if a system exception occurred



public static void setIndividualResourcePermissions(long groupId,
long companyId, java.lang.String name, java.lang.String primKey,java.util.Map<java.lang.Long, java.lang.String[]> roleIdsToActionIds)throws com.liferay.portal.kernel.exception.PortalException,
com.liferay.portal.kernel.exception.SystemException

Updates the role's permissions at the scope, setting the actions that can be performed on resources of the type. Existing actions are replaced.
This method can be used to set permissions at any scope, but it is generally only used at the individual scope. For example, it could be used to set the guest permissions on a blog post.

Depending on the scope, the value of primKey will have different meanings. For more information, see com.liferay.portal.model.impl.ResourcePermissionImpl.

Parameters:

groupId the primary key of the group

companyId the primary key of the company

name the resource's name, which can be either a class name or a portlet ID
primKey the primary key

roleIdsToActionIds a map of role IDs to action IDs of the actions

Throws:
PortalException - if the user did not have permission to set resource permissions, or if a role with the primary key or a resource action with the name and action ID could not be found

SystemException - if a system exception occurred



Note:

Prime key value will be changed based on resource type some time it is primary key of resource or its combination of some pattern based on resource.

The complete details about permission system please go through following Article.


In the example case we are going to enable view permission to all file entries of site/organization and these file entries are images.

Important Scenarios:

Case: 1

Some time when we migrate Liferay portal from one version to other then all images which are migrated not visible to GUEST role if this scenario following code will help us to enable View permission for all images on Guest role.

Case: 2

Some time when we upload bulk images into Liferay document library using custom portlet then images might not have view permission to guest user then we can use following code snippet to enable view permission to all images on Guest role.

In the bulk uploading once file entry is created then we can use following code to enable different permission action on different roles.

Liferay have beautiful feature that executing other langue’s scripts in Liferay portal these will help update or do some actions on portal using Liferay API. We don’t required any application to do some actions rather than we can create some script for example Groovy script which is similar to Java using Liferay API so that it can perform desired actions in Liferay portal.

Note:

When we set view permission to images or file entry then we also need to set same permission to those folders.
We also need to set permission to folders where file entries available

Example to Set View Permission to All Images for Role Guest in the Site/Organization

Sample code to enable view permission to all images in the Site/Organization

public void setViewPermissionforGuestonAllfileEntries(ActionRequest actionRequest,
ActionResponse actionResponse) throws Exception {
DynamicQuery fileEntryQuery= DynamicQueryFactoryUtil.forClass(DLFileEntry.class, PortalClassLoaderUtil.getClassLoader());
Criterion criterion = null;
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
//criterion = RestrictionsFactoryUtil.in("mimeType",new String[]{"image/png","image/x-ms-bmp","image/jpeg"});
//String valueForLike=StringPool.PERCENT+"image"+StringPool.PERCENT;
criterion=RestrictionsFactoryUtil.like("mimeType",new StringBuilder("%").append("image").append("%").toString());
criterion=RestrictionsFactoryUtil.and(criterion,RestrictionsFactoryUtil.eq("groupId",new Long(themeDisplay.getScopeGroupId())));
fileEntryQuery.add(criterion);
List<DLFileEntry> fileEntriesList=DLFileEntryLocalServiceUtil.dynamicQuery(fileEntryQuery);
Role guestRole=RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
RoleConstants.GUEST);
String[] actionIds=new String[]{"VIEW"};
logger.info("fileEntriesList"+fileEntriesList.size());
long lastViewPermissionAssignedFolderId=0;
long currentFolderId=0;
for(DLFileEntry curFileEntry:fileEntriesList){
try{
currentFolderId=curFileEntry.getFolderId();
if(currentFolderId!=0&&lastViewPermissionAssignedFolderId!=currentFolderId){
ResourcePermissionServiceUtil.setIndividualResourcePermissions(
curFileEntry.getGroupId(), curFileEntry.getCompanyId(),
DLFolder.class.getName(),String.valueOf(currentFolderId),guestRole.getRoleId(), actionIds);
lastViewPermissionAssignedFolderId=currentFolderId;
logger.info("permission successfully setted to folder id"+currentFolderId);
}
ResourcePermissionServiceUtil.setIndividualResourcePermissions(
curFileEntry.getGroupId(), curFileEntry.getCompanyId(),
DLFileEntry.class.getName(),String.valueOf(curFileEntry.getFileEntryId()),
guestRole.getRoleId(), actionIds);
}catch(Exception e){
logger.error("permission not able stet"+e.getLocalizedMessage());
}

logger.info("permission successfully setted to "+curFileEntry.getName());
}

}

Example to Set View Permission to All Images for Role Guest in the Site/Organization with Second Method


public void setViewPermissionforGuestonAllfileEntriesAnotherWay(ActionRequest actionRequest,
ActionResponse actionResponse) throws Exception {

DynamicQuery fileEntryQuery= DynamicQueryFactoryUtil.forClass(DLFileEntry.class, PortalClassLoaderUtil.getClassLoader());
Criterion criterion = null;
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
//criterion = RestrictionsFactoryUtil.in("mimeType",new String[]{"image/png","image/x-ms-bmp","image/jpeg"});
//String valueForLike=StringPool.PERCENT+"image"+StringPool.PERCENT;
criterion=RestrictionsFactoryUtil.like("mimeType",new StringBuilder("%").append("image").append("%").toString());
criterion=RestrictionsFactoryUtil.and(criterion,RestrictionsFactoryUtil.eq("groupId",new Long(themeDisplay.getScopeGroupId())));
fileEntryQuery.add(criterion);
List<DLFileEntry> fileEntriesList=
DLFileEntryLocalServiceUtil.dynamicQuery(fileEntryQuery);
Role guestRole=RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
RoleConstants.GUEST);
Role siteMemebrRole=RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
RoleConstants.SITE_MEMBER);
String[] guestActionIds=new String[]{"VIEW",""};
String[] siteMemebrActionIds=new String[]{"VIEW","DELETE"};
java.util.Map<java.lang.Long, java.lang.String[]> roleIdsToActionIds=new HashMap<Long, String[]>();
roleIdsToActionIds.put(guestRole.getRoleId(), guestActionIds);
roleIdsToActionIds.put(siteMemebrRole.getRoleId(),siteMemebrActionIds);
logger.info("fileEntriesList"+fileEntriesList.size());
long lastViewPermissionAssignedFolderId=0;
long currentFolderId=0;
for(DLFileEntry curFileEntry:fileEntriesList){
try{
currentFolderId=curFileEntry.getFolderId();
if(currentFolderId!=0&&lastViewPermissionAssignedFolderId!=currentFolderId){
ResourcePermissionServiceUtil.setIndividualResourcePermissions(
curFileEntry.getGroupId(), curFileEntry.getCompanyId(),
DLFolder.class.getName(),String.valueOf(currentFolderId),roleIdsToActionIds);
lastViewPermissionAssignedFolderId=currentFolderId;
logger.info("permission successfully setted to folder id"+currentFolderId);
}
ResourcePermissionServiceUtil.setIndividualResourcePermissions(
curFileEntry.getGroupId(), curFileEntry.getCompanyId(),
DLFileEntry.class.getName(),String.valueOf(curFileEntry.getFileEntryId()),
roleIdsToActionIds);
}catch(Exception e){
logger.error("permission not able stet"+e.getLocalizedMessage());
}

logger.info("permission successfully setted to "+curFileEntry.getName());
}

}


The following is simple Groovy scrip execute from Liferay Server Administration then you can enable guest permission to all images in the site.

Note

You have to change to your groupId and companyId that are hard coded in the script


import com.liferay.portal.service.ResourcePermissionServiceUtil;
 import com.liferay.portal.model.Role;
 import com.liferay.portal.service.RoleLocalServiceUtil;
import java.util.List;
import com.liferay.portal.model.RoleConstants;
 import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;
 import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
import com.liferay.portal.kernel.dao.orm.Criterion;
import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portlet.documentlibrary.model.DLFolder;

DynamicQuery fileEntryQuery= DynamicQueryFactoryUtil.forClass(DLFileEntry.class, PortalClassLoaderUtil.getClassLoader());
Criterion criterion = null;
String[] mimeTypeExtensiona=["image/png","image/x-ms-bmp","image/jpeg"] as String[];

criterion = RestrictionsFactoryUtil.in("mimeType",mimeTypeExtensiona);
criterion=RestrictionsFactoryUtil.and(criterion,RestrictionsFactoryUtil.eq("groupId",new Long(126774)));
fileEntryQuery.add(criterion);
List<DLFileEntry> fileEntriesList=DLFileEntryLocalServiceUtil.dynamicQuery(fileEntryQuery);
Role guestRole=RoleLocalServiceUtil.getRole(20155,RoleConstants.GUEST);
String[] actionIds=["VIEW"] as String[];
out.println("fileEntriesList"+fileEntriesList.size());
long lastViewPermissionAssignedFolderId=0;
long currentFolderId=0;
for(DLFileEntry curFileEntry:fileEntriesList){
try{
currentFolderId=curFileEntry.getFolderId();
if(currentFolderId!=0&&lastViewPermissionAssignedFolderId!=currentFolderId){
ResourcePermissionServiceUtil.setIndividualResourcePermissions(curFileEntry.getGroupId(), curFileEntry.getCompanyId(),DLFolder.class.getName(),
String.valueOf(currentFolderId),guestRole.getRoleId(), actionIds);
lastViewPermissionAssignedFolderId=currentFolderId;
out.println("permission successfully setted to folder id"+currentFolderId);
}
ResourcePermissionServiceUtil.setIndividualResourcePermissions(
curFileEntry.getGroupId(), curFileEntry.getCompanyId(),
DLFileEntry.class.getName(),String.valueOf(curFileEntry.getFileEntryId()),
guestRole.getRoleId(), actionIds);
}catch(Exception e){
out.println("permission not able stet"+e.getLocalizedMessage());
}

out.println("permission successfully setted to "+curFileEntry.getName());
}


Note:

In above dynamic query have used IN operator to fetch all file entries which are matched to given mime types.

The following is simple Groovy scrip execute from Liferay Server Administration then you can enable guest permission to all images in the site.

Note

You have to change to your groupId and companyId that are hard coded in the script


import com.liferay.portal.service.ResourcePermissionServiceUtil;
import com.liferay.portal.model.Role;
import com.liferay.portal.service.RoleLocalServiceUtil;
import java.util.List;
import com.liferay.portal.model.RoleConstants;
import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;
import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
import com.liferay.portal.kernel.dao.orm.Criterion;
import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import  com.liferay.portal.kernel.util.StringPool;
import com.liferay.portlet.documentlibrary.model.DLFolder;

DynamicQuery fileEntryQuery= DynamicQueryFactoryUtil.forClass(DLFileEntry.class, PortalClassLoaderUtil.getClassLoader());
Criterion criterion = null;
String valueForLike=StringPool.PERCENT+"image"+StringPool.PERCENT;
criterion=RestrictionsFactoryUtil.like("mimeType",valueForLike);
criterion=RestrictionsFactoryUtil.and(criterion,RestrictionsFactoryUtil.eq("groupId",new Long(142101)));
fileEntryQuery.add(criterion);
List<DLFileEntry> fileEntriesList=DLFileEntryLocalServiceUtil.dynamicQuery(fileEntryQuery);
Role guestRole=RoleLocalServiceUtil.getRole(20155,RoleConstants.GUEST);
String[] actionIds=["VIEW"] as String[];
out.println("fileEntriesList"+fileEntriesList.size());
long lastViewPermissionAssignedFolderId=0;
long currentFolderId=0;
for(DLFileEntry curFileEntry:fileEntriesList){
try{
currentFolderId=curFileEntry.getFolderId();
if(currentFolderId!=0&&lastViewPermissionAssignedFolderId!=currentFolderId){
ResourcePermissionServiceUtil.setIndividualResourcePermissions(curFileEntry.getGroupId(), curFileEntry.getCompanyId(),DLFolder.class.getName(),
String.valueOf(currentFolderId),guestRole.getRoleId(), actionIds);
lastViewPermissionAssignedFolderId=currentFolderId;
out.println("permission successfully setted to folder id"+currentFolderId);
}
ResourcePermissionServiceUtil.setIndividualResourcePermissions(
curFileEntry.getGroupId(), curFileEntry.getCompanyId(),
DLFileEntry.class.getName(),String.valueOf(curFileEntry.getFileEntryId()),
guestRole.getRoleId(), actionIds);
}catch(Exception e){
out.println("permission not able stet"+e.getLocalizedMessage());
}

out.println("permission successfully setted to "+curFileEntry.getName());
}

                        
Note:

In above dynamic query have used like operator to fetch all file entries which are images include all types images (PNG, GIF, JPEG, BMP and TIF).

Execute Groovy Script in Liferay

Liferay have ability to execute other langue’s script to make some actions in the Liferay portal and these script uses the Liferay API so that it can do some operations in Liferay portal. Liferay supported scripts like Groovy, Python, Ruby, Beanshell and JavaScript.


Download Sample Liferay Groovy Scripts from following location


Login as Liferay Portal admin and go to Liferay Control Panel there you can see the server administration


Once click on server Administration it will launch User Interface there we can do many things in the tabs you can find Script click on the tab.




Select Language Groovy from the drop down and copy given Groovy script in the text area finally click on Execute button then groovy script will be executed.

Output for above scripts as follows



Reference about Individual Resource Permissions


Author

Sunday, September 6, 2015

Working with Dynamic Data Lists in Liferay Part-I

Liferay have provided the way to create new data definition so that we can easily create new data list and we can use it store data. Dynamic data list way of design our data model and store that data as for our desired models.

We will define our data definition and we can create different data list based on the definition then we can store the data as for defined model. Data List are associated with sites.

Liferay have given very good user Interface to create new definitions and we can display these definition list to capture data from end users.

These we can use in real time requirement like To Do List, Contact US, Feedback and Meeting Minutes.

Data Definition:

Data Definition are data model like data structure

Data List:

Data List is use the data definition and it will be separate unit the data stored is associate with data list.

These are steps to use Liferay Dynamic Data List.

Define Data List Definition
Create Data List based on Definition
Display List to capture data from End User.

Liferay have provided few data definitions.

Using Existed Dynamic Data Definitions.

Liferay have provide following definition.


Using Existed Definition to create Data List

Login as Portal Administrator


Now go to Site Administration and then select content in the site administration.




Once click on Content then it will launch Administration Dash board there you can find Dynamic Data List. Click on that so that it will launch dynamic data list user interface screens.




Now we will create new Data List so click on Add button then it will launch Create new data List screen.


Once click on Add it will launch screen will ask details to create new data list. Assume we are going to create Contact Us Data list. Give following input data.

Name: Product Contact Us
Description:  Product Contact Us




To create new data list we need to select relevant Data Definition so click on Data Definition select button it will show available definitions. In the list select Contact Us data definition in the list.



Now you can see selected Contact us Definition 



Finally click on save then then new data list will be created and it will use the contact us definition.



We ready with new data list and now we can use this list to capture the data.

Create one new page. Go to home page. Left site you can see the Admin controls there click on Add



Click on page tab then give page name and select layout for page then click on Add page then page will be created.



Go to newly created page now we have to add the Dynamic Data List Display Portlet to page.
Go to Add Application and select Dynamic Data List Display Portlet then click on add portlet then it will be added to the page.



You can see Select List and Add List controls to portlet boron now click on Select List link

Once click on Select List it will display list of dynamic list and select desired list then save it finally close the popup and list will be associated with the portlet.




Select Product Contact Us list click on save then Dynamic Data List will be associated to the portlet.



Once click on Add button then Data List will be displayed in the page.


Fill the form then click on publish data will be stored and you can see the data in the portlet.



This how we can use existed data definitions from that we can create new data list. These list we can display through Dynamic Data List Display portlet and there we can fill the list and save the data.

Author

Recent Posts

Recent Posts Widget

Popular Posts