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

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

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 Custom Field and Custom Attribute (Using Liferay UI and Programatically)

Custom fields are a way to add attributes to many types of assets in the portal. Its basically help us to add additional fields to existed models or entities. Adding some more additional attributes to existed entities or models helps us so to meet our requirements. Liferay provide two way's to allow the creation of Custom Fields. 1. Using Liferay UI 2. Programatically Lets look these both topic one by one-: Suppose you have a scenario where its needed to add few fields in your User_ Table So its simple to add using Liferay UI just you need to follow these steps-: 1. Using Liferay UI-:   Goto-> Control-Panel -> Click on Custom Field A List will be displayed-: Now you can add your custom fields for any entity in the list. Click on User Entity and a page will be displayed like this-: Now add these value in respective fields-: KEY- myContactId Type- Select Integer After adding the custom field we can view, update from the Lifera...