Saturday, October 31, 2015

Liferay Vocabularies, Categories and Tags Management

Liferay have good asset Frame work to manage Web content, Documents, Blogs, wikis and message board .It will help us segregate content and other assets.

Liferay have introduced Vocabulary, Categories and Tags to segregate all the assets and its makes displaying assets very easy. We can make different set of assets and we can display these by group. These categories and tags will help us to refine search result so that end user always see relevant data when they search. Assume we have news portal and it has different kind of news and have different locations. The news may be National News, International News, Politics, Sports, Entertainments and Other types of news.

Liferay have following types of segregation of Assets

Vocabulary
Category
Tags

Vocabulary:

 We can say its parent category under this we can have child categories. Asset may associated with multiple vocabularies.

Example:  News, Location Type

Categories:

It’s used to grouping assets, when we create any asset in Liferay we can map asset to specific category and we can also map one asset to multiple categories. Each vocabulary associated with one or more categories.

Example:

News:  Sports, Politics and Entertainment.

Tags:

Tags we can say keywords to make better search for assets. We will find some important keywords from asset then we make it as tags. Each asset can have multiple relevant tags

Note:

In Liferay Asset is like some entity it may be Web content, Blog, wiki, Document and Message boards. All these we can consider as Asset.

We can say each vocabulary can be associate with multiple categories and each asset can be associated with multiple categories and multiple tags.

Assume we have News Portal it consist huge amount of web content. Now we can categorise the content as follows.

Vocabularies

 News, Location Type

Categories:

News: Politics, Sports and Entertainment
Location Type:  International, National

In Liferay all assets mapping with group and group may be Site, Organization and User Group.

These vocabulary Categories based on Group means each site have its own vocabulary and categories.

Assume we have Liferay Site called News Portal

Step: 1

We have to create site called News Portal

Follow the article to know more about create Liferay Site.


Login as Portal Administrator and go to Control Panel there you can find Site section then click on sites section



It will launch you the site creation page click on Add button and Select blank Site


Provide Site Names and Description then click on save then site will be created
Name: News Portal

Description: any thing


Then you site will be crated once created site then create some page for site.
Go to pages section and click on site pages.



Click on Add page then give page name as Home then save it now page will be created.




Now page will be created successfully



Step: 2

Once you successfully created site then login as Site Administrator or Portal Administrator.
Go to my sites then you can see newly created site (News Portal) click on your site then you will navigate to your site home page.



Now you can see you’re newly created Site (News Portal)

You can also access site with following link



In the Dockbar click Admin menu you can see Site Administration section and click on site Content


In the content administration section you can see Categories link then click on it then you can see categories and vocabulary creation screen




Crete Vocabulary

Click on Add Vocabulary then it will launch you the screen to create new vocabulary now provide Name and Description. Finally click on save then new Vocabulary created for the site.



As for our example we are going to create News and Location Type. Same you use Add Vocabulary then create both.



Create Category

Click on Add Category then it will launch Add Category Popup window provide Name, Description and we need to map category with vocabulary. In the dropdown (To Vocabulary) you can select desired vocabulary.



You can create Categories Politics, Sports and Entertainment for News Vocabulary and National, International categories for Location Type Vocabulary

News Vocabulary




Location Type Vocabulary



We successfully crated Vocabulary and Categories now we are going to news and mapping these categories.

Step: 3

To prepare the news we will use Liferay web content Journal Articles. In the content section click on Web content and Add new Basic Web content.



It will launch you thee editor then design your news

Provide Title and Design your content in the editor.




In the right section you can see list of associated things for web content.
Click on Categories section then you can associate category for your news.

We already crated two vocabularies and each vocabulary have its own categories and these you can select as follows




Click on each vocabulary Select button then you can see relevant categories from that select check box which related to your web content then close window.

Assumer we are creating news relates sports and its national news. Now in the Location Type we need to select National and News Vocabulary select Sports

Location Type: National

News: Sports



Now you can see categories associated to web content.



In the tags section you can give relevant keys so that it will be associated to web content. Each tag you can separate with COMMA (,)

Finally categories and Tags associated to web content



Note:

You can also map multiple categories if the new belongs to National and International then you can selection both.

Finally click on Publish then web content will be crated.




The above process you can apply for each web content creation and select relevant categories and add relevant tags so that your news will be ready and you can display based on category and tags and users also can find relevant news when they search.

Step:4

Now we can display news based on categories. Liferay have provided portlet Asset Publisher from this we can display web content based on categories.

Go to Page and Drag and Drop Asset Publisher portlet.

Basically it will display all assets as follows


Go to Asset Publisher Portet configuration



Select Asset Type Web content Article then it will display only web content Article assets



In the filter you can display based on need. In the filer section you can see “Displayed assets must match these rules.”

Contains:

 The Contains should matching then it will be display

Do not Contains:

It will be display if the given category or tag does not contains.

ANY:

It’s like OR condition if we selection multiple then it wil apply OR condition

ALL:

It’s Apply AND condition if we select multiple then its will apply AND condition

Categories:

We can select categories

Tags:

We can select Tags

Only Politics News



Only Sports news



News with National OR Inter National



News with National AND International


News with National AND Politics



Such a way we can display based on our need.

Go Display section of configuration select Display Template Abstract and you can give number letter to display content as Abstract



In the Sow Meta data you can show required Meta data for asset



Finally click on save then it will display Assets as for Filter


Liferay also given category navigation portlet and this portlet we need use with asset publisher so that it will be display assets based on categories when we click on category.

 We need to always place this portlet with asset publisher portlet and we also have Tags Navigation portlet.


When we click on Tags or Categories then Assets will be Filters in Asset Publisher.
These portlet have Inter Portlet Communication (IPC)



The following is example for Asset Publisher and Category Navigation Portlet



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

Recent Posts

Recent Posts Widget

Popular Posts