Skip to main content

Application Start Up Hook for Creating Layout, addingPortlet on Layout , Creating SitePages, Site, CustomField, Roles, Layout on Application StartUp

Step 1-: Create a Hook and it would be an Event Bundle HOOK (application.startup.events )
              In portal.properties add this line
              application.startup.events=com.test.event.MyPortalStartUpAction

Step 2-: First we need to create a class were we will define pages that we will need in our site

package com.test.pageutil

public class MyPageUtil {

public static Map<String, String> getPrivatePageList() {

   Map<String, String> pages = new LinkedHashMap<String, String>();
pages.put("pageOne", "PageOne");
pages.put("pageTwo", "PageTwo");
pages.put("pageThree", "PageThree");
return pages;
}

Step 3-: This hook class will extend SimpleAction

public class MyPortalStartUpAction extends SimpleAction{

@Override
public void run(String[] ids) throws ActionException {
try {
for (int i = 0; i < ids.length; i++) {
_log.info("MyPortalStartUpAction -- comapny id "+ids[i]);
}
doRun(GetterUtil.getLong(ids[0]));
}
catch (Exception e) {
throw new ActionException(e);
}
}

private void doRun(long companyId) throws Exception {

//Create Role and assign permission to it.
setupExpando(companyId);

//create Site and pages for portal using admin user
long userId = 0;
User adminUser = null;
try {
List<User> users = UserLocalServiceUtil.getUsers(0, UserLocalServiceUtil.getUsersCount());
for (User user : users) {
if(!user.isDefaultUser() && user.getStatus()!=5){
List<Role> roles = user.getRoles();
for (Role role : roles) {
if(role.getName().equalsIgnoreCase(RoleConstants.ADMINISTRATOR)){
adminUser = user;
userId = user.getUserId();
}
}
}
}
_log.info("adminUser : "+adminUser.getFullName());
}catch(Exception pe){
_log.info("User doesn't exist.");
}
}
}

         /**
* This method is used to create role using name and comanyId on application start-up.
* @param companyId
* @param roleName
* @return Newly added role is return
* @throws SystemException
*/
private Role createRole(long companyId, String roleName) throws SystemException{
long roleClassNameId = ClassNameLocalServiceUtil.getClassNameId(Role.class.getName());
long roleId = CounterLocalServiceUtil.increment(Role.class.getName());
Role role = RoleLocalServiceUtil.createRole(roleId);
role.setClassNameId(roleClassNameId);
role.setClassPK(roleId);
role.setName(roleName);
role.setType(RoleConstants.TYPE_REGULAR);
role.setCompanyId(companyId);
role.setTitle(roleName);
role = RoleLocalServiceUtil.updateRole(role);
return role;
}

/* apply custom theme for MyPortalSite Private pages */

if(userId != 0){
try {
Group group = GroupLocalServiceUtil.getGroup(companyId, MyPortalSite);

//check PRIVATE PAGES with its PORTLET is present or not
checkPrivatePages(group);
}catch(NoSuchGroupException nsge) {

                            createSite(userId);
}

/* Create Roles on application start-up if there is no role. */

protected void setupExpando(long companyId) throws Exception {

ExpandoTable table = null;
/* Change portal default password policy */
PasswordPolicy passwordPolicy = PasswordPolicyLocalServiceUtil.getDefaultPasswordPolicy(companyId);
if(passwordPolicy != null && passwordPolicy.getChangeRequired())
                   {
passwordPolicy.setChangeRequired(false);
PasswordPolicyLocalServiceUtil.updatePasswordPolicy(passwordPolicy);
           }

/* Create Roles on application start-up if there is no role. */

String[] actionKeys_Aanlytics_RW = {ActionKeys.VIEW, ActionKeys.ADD_ENTRY, ActionKeys.UPDATE, ActionKeys.DELETE};

try {
RoleLocalServiceUtil.getRole(companyId, MYRole_WRITE_ACCESS);
}
catch(NoSuchRoleException nsre){
createRole(companyId, MYRole_WRITE_ACCESS);
}

/*Create Custom-Field for Organization on application start-up */

table = ExpandoTableLocalServiceUtil.addTable(Organization.class.getName(), "CUSTOM_FIELDS");

table = ExpandoTableLocalServiceUtil.getTable(Organization.class.getName(), "CUSTOM_FIELDS");

//Here we are adding column(myOrgId,myOrgType) in custom filed

ExpandoColumnLocalServiceUtil.addColumn(table.getTableId(), myOrgId, ExpandoColumnConstants.LONG);

ExpandoColumn myCol = ExpandoColumnLocalServiceUtil.getColumn(table.getTableId(), myOrgId);

String[] defaultData = {"Select", "Company", "Location"};

ExpandoColumn myColOne = ExpandoColumnLocalServiceUtil.addColumn(table.getTableId(), myOrgType, ExpandoColumnConstants.STRING_ARRAY, defaultData);

myColOne = ExpandoColumnLocalServiceUtil.getColumn(table.getTableId(), myOrgType);


  }
}

private void checkPrivatePages(Group group) throws Exception{

Map<String, String> pages = MyPageUtil.getPrivatePageList()

//check layouts and portlet is present on layout or not for Private pages

List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(group.getGroupId(), true);
for (Layout layout : layouts)
{
if(!pages.isEmpty())
{
   List<Layout> layoutList = new ArrayList<Layout>();
     for (Map.Entry<String, String> page : pages.entrySet())
  {
        try{
        layoutList.add(addLayout(group, page.getValue(), true, "/"+page.getKey(), "2_columns_ii"));
        }catch(Exception e)
            {
       _log.info("Layout is already present.");
               }
  }
           _log.info("Layout is added "+layoutList);
  }

if(layout.getFriendlyURL().equalsIgnoreCase("/PageOne"))
{
   if(!isPortletOnLayout(layout, portletOne_WAR_PortletOneportlet))
    {
addPortletId(layout, portletOne_WAR_PortletOneportlet, Column1 );

      }
removeMapElement(pages, "pageOne");
 }

}
/**
* Add layout (page) for particular site (Group)
* @param group - site created model
* @param name - page name
* @param privateLayout - false : public page , true : private page
* @param friendlyURL
* @param layouteTemplateId
* @return
* @throws Exception
*/
private Layout addLayout( Group group, String name,  boolean privateLayout, String friendlyURL,
String layouteTemplateId) throws Exception {

ServiceContext serviceContext = new ServiceContext();
Layout layout = LayoutLocalServiceUtil.addLayout(group.getCreatorUserId(), group.getGroupId(),                               privateLayout,  LayoutConstants.DEFAULT_PARENT_LAYOUT_ID, name, StringPool.BLANK,
StringPool.BLANK, LayoutConstants.TYPE_PORTLET, false, friendlyURL, serviceContext);

LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet)layout.getLayoutType();

layoutTypePortlet.setLayoutTemplateId(0, layouteTemplateId, false);

addResources(layout, PortletKeys.DOCKBAR);

return layout;
}

private void addResources(Layout layout, String portletId) throws Exception
{

    String rootPortletId = PortletConstants.getRootPortletId(portletId);
    String portletPrimaryKey = PortletPermissionUtil.getPrimaryKey(layout.getPlid(), portletId);
    ResourceLocalServiceUtil.addResources
                                         (layout.getCompanyId(), layout.getGroupId(),
                                           0, rootPortletId, portletPrimaryKey, true, true, true);
}

/**
* Add portlet on particular layout (page)
* @param layout
* @param portletId
* @param columnId
* @return
* @throws Exception
*/
private String addPortletId(Layout layout, String portletId, String columnId) throws Exception
{

LayoutTypePortlet layoutTypePortlet =(LayoutTypePortlet)layout.getLayoutType();

List<Portlet> list = layoutTypePortlet.getPortlets();

portletId = layoutTypePortlet.addPortletId(0, portletId, columnId, -1, false);

addResources(layout, portletId);

updateLayout(layout);

return portletId;
}
/**
* Update layout after creating layout.
* @param layout
* @throws Exception
*/
private void updateLayout(Layout layout) throws Exception
{
    LayoutLocalServiceUtil.updateLayout(layout.getGroupId(), layout.isPrivateLayout(),           layout.getLayoutId(),layout.getTypeSettings());
}

/**
* Add custom theme for group.
* @param groupId
* @param privateLayout - set false for public page and true for private page.
* @param themeId - custom theme Id e.g Custom_WAR_Customtheme
* @throws PortalException
* @throws SystemException
*/
private void updateCustomTheme(long groupId, boolean privateLayout, String themeId)
throws PortalException, SystemException
 {
LayoutSetLocalServiceUtil.updateLookAndFeel(groupId, privateLayout, themeId, "01", "", false);
 }

/**
* Get all actions related to any model
* @param name as model name e.g - This i will update in my next tutorial
On Custom Action class
* @return all actions related to model
*/
private String[] getActionIds (String name) {

        String[] actions = null;
        //Here's is where I get all the actionIds, and not only the ones I need
        List<String> actionsList = ResourceActionsUtil.getResourceActions(name);
     
        for (int i = 0; i < actionsList.size(); i++)
            actions = actionsList.toArray(new String[i]);
     
        return actions;
}


/**
* Add permission (like VIEW, UPDATE or DELETE) for the particular role
* @param companyId
* @param roleId
* @param modelName - Resource where u want to permission for it
* @param actionsKeys - permission for user
* @throws PortalException
* @throws SystemException
*/
private void addResource(long companyId, Role role, String modelName, String[]actionsKeys)
throws PortalException, SystemException{

for (String actionKey : actionsKeys) {
if(!ResourcePermissionLocalServiceUtil.hasResourcePermission(companyId,
modelName,
ResourceConstants.SCOPE_COMPANY,
""+companyId,
role.getRoleId(),
actionKey)){
_log.info("Role("+role.getName()+") don't have this permission("+actionKey+") for this model("+modelName+")");
ResourcePermissionLocalServiceUtil.addResourcePermission(
companyId,
modelName,
ResourceConstants.SCOPE_COMPANY,
""+companyId,
role.getRoleId(),
actionKey);
}else{
_log.info("Role("+role.getName()+") already have this permission("+actionKey+") for this model("+modelName+")");
}

}
}

}

Comments

Popular posts from this blog

How the portal page is loaded with respective portlets

How the portal page is loaded with respective portlets When a user requests a page with a URL, 1.    The browser sends the request to the Application Server (AS). 2.    Liferay gets the page name from the URL. 3.    It goes to the layout database table and finds the related        theme and page layout. 4.    Based on the page layout, Liferay finds the portlets added        into each area of the page layout. 5.    Liferay runs the portlet and adds the output in the        portlet.vm template. 6.    Liferay interprets the portlet.vm template and adds the output        in the page layout. 7.    Then Liferay interprets the page layout and adds the output in        the portal_normal.vm template. 8.    After that Liferay interprets the portal...

Liferay 7.1 Topics Coming Soon stay connected

1. Liferay 7.1 Service Builder 2. Rest Service and Liferay 3. Consuming SOAP service with Liferay 7.1 4. Creating Theme With Liferay 7.1 Using Liferay IDE Using NPM 5. Create Angular NPM Module 6. Web Content Management 7. OSGI Basic 8. Liferay 7.1 with more than 1 DB 9. A sample project 10. Liferay Dev Ops

Liferay Permission System

Liferay Permission System 1. Liferay’s permission system uses a flexible mechanism that defines the actions that a given user can perform within the context of the portal or a specific portlet. 2. Portal and portlet developers break down the operations that can be performed in the portal or portlet into distinct actions. 3. The act of granting the ability to perform an action to a specific role is the act of granting a permission. 4. In Liferay, permissions are not granted to directly to users. Instead, permissions are granted to roles. Roles, in turn, can be assigned to specific users, sites, organizations, or user groups. Action: An operation that can be performed by a portal user. For example, actions that be performed on the Offer Portlet include ADD_TO_PAGE, CONFIGURATION, and VIEW. Actions that can be performed on a Offer entity include ADD_ENTRY, DELETE, PERMISSIONS, UPDATE, and VIEW. Resource: A generic representation of any portlet or entity in the portal on which ...