DefaultSpaceApplicationHandler.java

  1. /*
  2.  * Copyright (C) 2003-2007 eXo Platform SAS.
  3.  *
  4.  * This program is free software; you can redistribute it and/or
  5.  * modify it under the terms of the GNU Affero General Public License
  6.  * as published by the Free Software Foundation; either version 3
  7.  * of the License, or (at your option) any later version.
  8.  *
  9.  * This program is distributed in the hope that it will be useful,
  10.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.  * GNU General Public License for more details.
  13.  *
  14.  * You should have received a copy of the GNU General Public License
  15.  * along with this program; if not, see<http://www.gnu.org/licenses/>.
  16.  */
  17. package org.exoplatform.social.core.space.impl;

  18. import java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.Iterator;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Map.Entry;
  24. import java.util.Set;

  25. import org.exoplatform.application.registry.Application;
  26. import org.exoplatform.application.registry.ApplicationCategory;
  27. import org.exoplatform.container.ExoContainer;
  28. import org.exoplatform.container.ExoContainerContext;
  29. import org.exoplatform.container.PortalContainer;
  30. import org.exoplatform.container.xml.InitParams;
  31. import org.exoplatform.portal.config.DataStorage;
  32. import org.exoplatform.portal.config.UserACL;
  33. import org.exoplatform.portal.config.UserPortalConfigService;
  34. import org.exoplatform.portal.config.model.ApplicationType;
  35. import org.exoplatform.portal.config.model.Container;
  36. import org.exoplatform.portal.config.model.ModelObject;
  37. import org.exoplatform.portal.config.model.Page;
  38. import org.exoplatform.portal.config.model.PortalConfig;
  39. import org.exoplatform.portal.config.model.TransientApplicationState;
  40. import org.exoplatform.portal.mop.SiteKey;
  41. import org.exoplatform.portal.mop.navigation.NavigationContext;
  42. import org.exoplatform.portal.mop.navigation.NavigationService;
  43. import org.exoplatform.portal.mop.navigation.NodeContext;
  44. import org.exoplatform.portal.mop.navigation.NodeModel;
  45. import org.exoplatform.portal.mop.navigation.NodeState;
  46. import org.exoplatform.portal.mop.navigation.NodeState.Builder;
  47. import org.exoplatform.portal.mop.navigation.Scope;
  48. import org.exoplatform.portal.mop.page.PageContext;
  49. import org.exoplatform.portal.mop.page.PageKey;
  50. import org.exoplatform.portal.mop.page.PageService;
  51. import org.exoplatform.portal.mop.page.PageState;
  52. import org.exoplatform.portal.mop.user.UserNode;
  53. import org.exoplatform.portal.pom.config.Utils;
  54. import org.exoplatform.portal.pom.spi.gadget.Gadget;
  55. import org.exoplatform.portal.pom.spi.portlet.Portlet;
  56. import org.exoplatform.portal.pom.spi.portlet.PortletBuilder;
  57. import org.exoplatform.portal.webui.portal.UIPortal;
  58. import org.exoplatform.portal.webui.util.Util;
  59. import org.exoplatform.services.log.ExoLogger;
  60. import org.exoplatform.services.log.Log;
  61. import org.exoplatform.social.core.space.*;
  62. import org.exoplatform.social.core.space.model.Space;
  63. import org.exoplatform.social.core.space.spi.SpaceApplicationHandler;
  64. import org.exoplatform.social.core.space.spi.SpaceService;
  65. import org.exoplatform.social.core.space.spi.SpaceTemplateService;
  66. import org.exoplatform.webui.application.WebuiRequestContext;

  67. /**
  68.  * Default implementation for working with space applications.
  69.  *
  70.  * @author <a href="mailto:tungcnw@gmail.com">dang.tung</a>
  71.  * @author <a href="http://hoatle.net">hoatle (hoatlevan at gmail dot com)</a>
  72.  * @since OCt 17, 2008
  73.  */

  74. public class DefaultSpaceApplicationHandler implements SpaceApplicationHandler {
  75.   private static final Log LOG = ExoLogger.getLogger(DefaultSpaceApplicationHandler.class);

  76.   public static final String NAME = "classic";

  77.   private static final String TEMPLATE_NAME_PARAM = "templateName";

  78.   public static final String SPACE_TEMPLATE_PAGE_ID = "portal::classic::spacetemplate";

  79.   public static final String APPLICATION_CONTAINER = "Application";

  80.   /**
  81.    * The {groupId} preference value pattern
  82.    *
  83.    * @since 1.2.0-GA
  84.    */
  85.   private static final String GROUP_ID_PREFERENCE = "{groupId}";

  86.   /**
  87.    * The {modifiedGroupId} preference value pattern
  88.    *
  89.    * @since 1.2.0-GA
  90.    */
  91.   private static final String MODIFIED_GROUP_ID_PREFERENCE = "{modifiedGroupId}";

  92.   /**
  93.    * The {pageName} preference value pattern
  94.    *
  95.    * @since 1.2.0-GA
  96.    */
  97.   private static final String PAGE_NAME_PREFERENCE = "{pageName}";

  98.   /**
  99.    * The {pageUrl} preference value pattern
  100.    *
  101.    * @since 1.2.0-GA
  102.    */
  103.   private static final String PAGE_URL_PREFERENCE = "{pageUrl}";

  104.   private PortalContainer container = PortalContainer.getInstance();

  105.   private DataStorage dataStorage = null;
  106.   private PageService pageService = null;

  107.   private SpaceService spaceService;

  108.   private SpaceTemplateService spaceTemplateService;

  109.   private Map<ApplicationCategory, List<Application>> appStoreCache = null;

  110.   private static List<Application> appCache = new ArrayList<Application>();

  111.   private String templateName;

  112.   /**
  113.    * Constructor.
  114.    *
  115.    * @param dataStorage
  116.    */
  117.   public DefaultSpaceApplicationHandler(InitParams params, DataStorage dataStorage, PageService pageService, SpaceTemplateService spaceTemplateService) {
  118.     this.dataStorage = dataStorage;
  119.     this.pageService = pageService;
  120.     this.spaceTemplateService = spaceTemplateService;
  121.     if (params == null) {
  122.       templateName = NAME;
  123.     } else {
  124.       templateName = params.getValueParam(TEMPLATE_NAME_PARAM).getValue();
  125.     }
  126.   }

  127.   /**
  128.    * {@inheritDoc}
  129.    */
  130.   public void initApps(Space space, SpaceTemplate spaceTemplate) throws SpaceException {
  131.     try {
  132.       ExoContainer container = ExoContainerContext.getCurrentContainer();
  133.       NavigationService navService = (NavigationService) container.getComponentInstance(NavigationService.class);
  134.       NavigationContext navContext = SpaceUtils.createGroupNavigation(space.getGroupId());
  135.      
  136.       NodeContext<NodeContext<?>> parentNodeCtx = navService.loadNode(NodeModel.SELF_MODEL, navContext, Scope.CHILDREN, null);

  137.       //
  138.       SpaceApplication homeApplication = spaceTemplate.getSpaceHomeApplication();
  139.       if (homeApplication == null) {
  140.         throw new IllegalStateException("Could not find space home application for template "
  141.             + spaceTemplate.getName() == null ? "" : spaceTemplate.getName() + ". Could not init space apps");
  142.       }
  143.       NodeContext<NodeContext<?>> homeNodeCtx = createPageNodeFromApplication(navContext, parentNodeCtx, space, homeApplication, null, true);
  144.       SpaceService spaceService = getSpaceService();


  145.       List<SpaceApplication> spaceApplications = spaceTemplate.getSpaceApplicationList();
  146.       if (spaceApplications != null) {
  147.         for (SpaceApplication spaceApplication : spaceApplications) {
  148.           createPageNodeFromApplication(navContext, homeNodeCtx, space, spaceApplication, null, false);
  149.           spaceService.installApplication(space, spaceApplication.getPortletName());
  150.         }
  151.       }
  152.       //commit the parentNode to JCR
  153.       navService.saveNode(parentNodeCtx, null);
  154.     } catch (Exception e) {
  155.       throw new SpaceException(SpaceException.Code.UNABLE_TO_INIT_APP, e);
  156.     }
  157.   }
  158.  
  159.  
  160.  
  161.  
  162.  
  163.   /**
  164.    * {@inheritDoc}
  165.    */
  166.   public void deInitApp(Space space) throws SpaceException {
  167.     try {
  168.       String groupId = space.getGroupId();
  169.       NavigationContext spaceNavCtx = SpaceUtils.getGroupNavigationContext(groupId);
  170.       // return in case group navigation was removed by portal SOC-548
  171.       if (spaceNavCtx == null) {
  172.         return;
  173.       }
  174.       NodeContext<NodeContext<?>> homeNodeCtx = SpaceUtils.getHomeNodeWithChildren(spaceNavCtx, groupId);

  175.       for (NodeContext<?> child : homeNodeCtx.getNodes()) {
  176.         @SuppressWarnings("unchecked")
  177.         NodeContext<NodeContext<?>> childNode = (NodeContext<NodeContext<?>>) child;
  178.         Page page = dataStorage.getPage(childNode.getState().getPageRef().format());
  179.         dataStorage.remove(page);
  180.      }
  181.      
  182.      
  183.       SpaceUtils.removeGroupNavigation(groupId);
  184.     } catch (Exception e) {
  185.       throw new SpaceException(SpaceException.Code.UNABLE_TO_DEINIT_APP, e);
  186.     }
  187.   }

  188.   /**
  189.    * {@inheritDoc}
  190.    */
  191.   public void activateApplication(Space space, String appId, String appName) throws SpaceException {
  192.     ExoContainer container = ExoContainerContext.getCurrentContainer();
  193.     NavigationService navService = (NavigationService) container.getComponentInstance(NavigationService.class);
  194.     NavigationContext navContext;
  195.     NodeContext<NodeContext<?>> homeNodeCtx = null;

  196.     try {
  197.       navContext = SpaceUtils.getGroupNavigationContext(space.getGroupId());
  198.       homeNodeCtx = SpaceUtils.getHomeNodeWithChildren(navContext, space.getUrl());

  199.     } catch (Exception e) {
  200.       LOG.warn("space navigation not found.", e);
  201.       return;
  202.     }
  203.     SpaceApplication spaceApplication = null;
  204.     String spaceTemplateName = space.getTemplate();
  205.     SpaceTemplate spaceTemplate = spaceTemplateService.getSpaceTemplateByName(spaceTemplateName);
  206.     if (spaceTemplate == null) {
  207.       throw new IllegalStateException("Space template with name " + spaceTemplateName +" wasn't found");
  208.     }
  209.     for(SpaceApplication application : spaceTemplate.getSpaceApplicationList()){
  210.       if (appId.equals(application.getPortletName()) && !SpaceUtils.isInstalledApp(space, appId)) {
  211.         spaceApplication = application;
  212.       }
  213.     }

  214.     if(spaceApplication == null) {
  215.       spaceApplication = new SpaceApplication();
  216.       spaceApplication.setPortletName(appId);
  217.     }
  218.     createPageNodeFromApplication(navContext, homeNodeCtx, space, spaceApplication, appName, false);
  219.     navService.saveNode(homeNodeCtx, null);
  220.   }

  221.   /**
  222.    * {@inheritDoc}
  223.    */
  224.   public void deactiveApplication(Space space, String appId) throws SpaceException {
  225.     deactivateApplicationClassic(space, appId);
  226.   }

  227.   /**
  228.    * {@inheritDoc}
  229.    */
  230.   public void installApplication(Space space, String appId) throws SpaceException {

  231.   }

  232.   /**
  233.    * {@inheritDoc}
  234.    */
  235.   public void removeApplication(Space space, String appId, String appName) throws SpaceException {
  236.     removeApplicationClassic(space, appId, appName);
  237.   }

  238.   /**
  239.    * {@inheritDoc}
  240.    */
  241.   public void removeApplications(Space space) throws SpaceException {
  242.     try {
  243.       String[] apps = space.getApp().split(",");
  244.       String[] appPart = null;
  245.       for (int i = 0; i < apps.length; i++) {
  246.         appPart = apps[i].split(":");
  247.         removeApplication(space, appPart[0], appPart[1]);
  248.       }
  249.     } catch (Exception e) {
  250.       throw new SpaceException(SpaceException.Code.UNABLE_TO_REMOVE_APPLICATIONS, e);
  251.     }
  252.   }

  253.   /**
  254.    * {@inheritDoc}
  255.    */
  256.   public String getName() {
  257.     return templateName;
  258.   }

  259.   @Override
  260.   public void setName(String s) {

  261.   }

  262.   @Override
  263.   public String getDescription() {
  264.     return null;
  265.   }

  266.   @Override
  267.   public void setDescription(String s) {

  268.   }

  269.   /**
  270.    * Deactivates an application in a space
  271.    *
  272.    * @param space
  273.    * @param appId
  274.    */
  275.   private void deactivateApplicationClassic(Space space, String appId) {

  276.   }

  277.   /**
  278.    * Removes an classic-type application from a space
  279.    *
  280.    * @param space
  281.    * @param appId
  282.    * @throws SpaceException
  283.    */
  284.   private void removeApplicationClassic(Space space, String appId, String appName) throws SpaceException {
  285.     try {
  286.      
  287.       UserNode spaceUserNode = SpaceUtils.getSpaceUserNode(space);
  288.       UserNode removedNode = spaceUserNode.getChild(appName);
  289.      
  290.       if (removedNode == null) {
  291.         // In case of cannot find the removed node, try one more time
  292.         String spaceTemplateName = space.getTemplate();
  293.         SpaceTemplate spaceTemplate = spaceTemplateService.getSpaceTemplateByName(spaceTemplateName);
  294.         if (spaceTemplate == null) {
  295.           throw new IllegalStateException("Space template with name " + spaceTemplateName +" wasn't found");
  296.         }
  297.         List<SpaceApplication> spaceApplications = spaceTemplate.getSpaceApplicationList();
  298.         for (SpaceApplication spaceApplication : spaceApplications) {
  299.           if (appId.equals(spaceApplication.getPortletName())) {
  300.             removedNode = spaceUserNode.getChild(spaceApplication.getUri());
  301.           }
  302.         }
  303.       }
  304.      
  305.       if (removedNode != null) {
  306.         spaceUserNode.removeChild(removedNode.getName());
  307.       } else {
  308.         return;
  309.       }
  310.      
  311.       //remove page
  312.       if (removedNode != null) {
  313.         PageKey pageRef = removedNode.getPageRef();
  314.         if (pageRef.format() != null && pageRef.format().length() > 0) {
  315.           //only clear UI caching when it's in UI context
  316.           if (WebuiRequestContext.getCurrentInstance() != null) {
  317.             UIPortal uiPortal = Util.getUIPortal();
  318.             // Remove from cache
  319.             uiPortal.setUIPage(pageRef.format(), null);
  320.           }
  321.           pageService.destroyPage(pageRef);
  322.         }
  323.       }
  324.      
  325.       SpaceUtils.getUserPortal().saveNode(spaceUserNode, null);

  326.     } catch (Exception e) {
  327.       throw new SpaceException(SpaceException.Code.UNABLE_TO_REMOVE_APPLICATION, e);
  328.     }

  329.   }

  330.   /**
  331.    * Gets an application from a list
  332.    *
  333.    * @param apps
  334.    * @param appId
  335.    * @return
  336.    */
  337.   private Application getApplication(List<Application> apps, String appId) {
  338.     for (Application app : apps) {
  339.       if (app.getApplicationName().equals(appId)) {
  340.         return app;
  341.       }
  342.     }
  343.     return null;
  344.   }

  345.   /**
  346.    * Creates page node from application. - Creates Application instance from appId. <br> - Creates Page instance and set
  347.    * the newly-created application for that page; adds application to container. <br> - Creates PageNode instance and
  348.    * returns that pageNode.
  349.    *
  350.    * @param space
  351.    * @param spaceApplication
  352.    * @param isRoot
  353.    * @return
  354.    * @since 1.2.0-GA
  355.    */
  356.   private NodeContext<NodeContext<?>> createPageNodeFromApplication(NavigationContext navContext, NodeContext<NodeContext<?>> nodeCtx, Space space,
  357.                                                  SpaceApplication spaceApplication,
  358.                                                  String appName,
  359.                                                  boolean isRoot) throws SpaceException {
  360.     String appId = spaceApplication.getPortletName();
  361.     Application app = getApplication(space, appId);
  362.     String contentId = app.getContentId();
  363.     if (contentId == null) {
  364.       contentId = app.getCategoryName() + "/" + app.getApplicationName();
  365.     }
  366.     String appInstanceId = PortalConfig.GROUP_TYPE + "#" + space.getGroupId() + ":/" + contentId
  367.             + "/" + app.getApplicationName() + System.currentTimeMillis();
  368.     org.exoplatform.portal.config.model.Application<Gadget> gadgetApplication = null;
  369.     org.exoplatform.portal.config.model.Application<Portlet> portletApplication = null;

  370.     if (app.getType() == ApplicationType.GADGET) {
  371.       TransientApplicationState<Gadget> gadgetState = new TransientApplicationState<Gadget>(app.getApplicationName());
  372.       gadgetApplication = org.exoplatform.portal.config.model.Application.createGadgetApplication();
  373.       gadgetApplication.setState(gadgetState);
  374.       gadgetApplication.setAccessPermissions(new String[]{"*:" + space.getGroupId()});
  375.       gadgetApplication.setShowInfoBar(false);
  376.     } else {
  377.       portletApplication = createPortletApplication(appInstanceId, space, isRoot);
  378.       portletApplication.setAccessPermissions(new String[]{"*:" + space.getGroupId()});
  379.       portletApplication.setShowInfoBar(false);
  380.     }

  381.     String pageTitle = space.getDisplayName() + " - " + app.getDisplayName();
  382.     String pageName = app.getApplicationName();
  383.     //is the application installed?
  384.     if (SpaceUtils.isInstalledApp(space, appId) && (appName != null)) {
  385.       pageName = appName;
  386.     }
  387.     UserPortalConfigService userPortalConfigService = getUserPortalConfigService();
  388.     Page page = null;
  389.     try {
  390.       if (isRoot) {
  391.         page = userPortalConfigService.createPageTemplate("spaceHomePage",
  392.                 PortalConfig.GROUP_TYPE,
  393.                 space.getGroupId());
  394.         setPermissionForPage(page.getChildren(), "*:" + space.getGroupId());
  395.       } else {
  396.         page = userPortalConfigService.createPageTemplate("space",
  397.                 PortalConfig.GROUP_TYPE,
  398.                 space.getGroupId());
  399.         //setting some data to page.
  400.         setPage(space, app, gadgetApplication, portletApplication, page);
  401.       }
  402.       page.setName(pageName);
  403.       page.setTitle(pageTitle);
  404.      
  405.       //set permission for page
  406.       String visibility = space.getVisibility();
  407.       if (visibility.equals(Space.PUBLIC)) {
  408.         page.setAccessPermissions(new String[]{UserACL.EVERYONE});
  409.       } else {
  410.         page.setAccessPermissions(new String[]{"*:" + space.getGroupId()});
  411.       }
  412.       page.setEditPermission("manager:" + space.getGroupId());

  413.      
  414.       SiteKey siteKey = navContext.getKey();
  415.       PageKey pageKey = new PageKey(siteKey, page.getName());
  416.       PageState pageState = new PageState(
  417.                                           page.getTitle(),
  418.                                           page.getDescription(),
  419.                                           page.isShowMaxWindow(),
  420.                                           page.getFactoryId(),
  421.                                           page.getAccessPermissions() != null ? Arrays.asList(page.getAccessPermissions()) : null,
  422.                                           page.getEditPermission(), Arrays.asList(page.getMoveAppsPermissions()), Arrays.asList(page.getMoveContainersPermissions()));
  423.      
  424.       pageService.savePage(new PageContext(pageKey, pageState));
  425.       dataStorage.save(page);
  426.       page = dataStorage.getPage(page.getPageId());
  427.       PageContext pageContext = pageService.loadPage(PageKey.parse(page.getPageId()));
  428.       pageContext.update(page);
  429.     } catch (Exception e) {
  430.       LOG.warn(e.getMessage(), e);
  431.     }
  432.    
  433.    
  434.     if (isRoot) {
  435.       pageName = space.getUrl();
  436.     } else {
  437.       if (spaceApplication.getUri() != null && !spaceApplication.getUri().isEmpty()) {
  438.         pageName = spaceApplication.getUri();
  439.       }
  440.      
  441.     }
  442.     NodeContext<NodeContext<?>> childNodeCtx = nodeCtx.add(null, pageName);
  443.     Builder nodeStateBuilder = new NodeState.Builder().icon(spaceApplication.getIcon()).pageRef(PageKey.parse(page.getPageId()));
  444.     WebuiRequestContext context = WebuiRequestContext.getCurrentInstance();
  445.     if (context != null && !context.getApplicationResourceBundle().containsKey(appId + ".label.name")) {
  446.       nodeStateBuilder.label(app.getDisplayName());
  447.     }
  448.     childNodeCtx.setState(nodeStateBuilder.build());
  449.     return childNodeCtx;
  450.   }

  451.   /**
  452.    * Gets an application by its id.
  453.    *
  454.    * @param space
  455.    * @param appId
  456.    * @return
  457.    * @throws SpaceException
  458.    */
  459.   private Application getApplication(Space space, String appId) throws SpaceException {
  460.     Application app = getApplication(appCache, appId);
  461.     if (app == null) {
  462.       try {
  463.         if (appStoreCache == null) {
  464.           appStoreCache = SpaceUtils.getAppStore(space);
  465.         }
  466.         app = getApplication(appStoreCache, appId);
  467.         if (app == null) {
  468.           // retry
  469.           appStoreCache = SpaceUtils.getAppStore(space);
  470.           app = getApplication(appStoreCache, appId);
  471.           if (app == null) {
  472.             app = SpaceUtils.getAppFromPortalContainer(appId);
  473.             if (app == null) {
  474.               throw new Exception("app is null!");
  475.             }
  476.           }
  477.         }
  478.         appCache.add(app);
  479.       } catch (Exception e) {
  480.         throw new SpaceException(SpaceException.Code.UNABLE_TO_LIST_AVAILABLE_APPLICATIONS, e);
  481.       }
  482.     }
  483.     return app;
  484.   }

  485.   @SuppressWarnings("unchecked")
  486.   private void setPage(Space space,
  487.                        Application app,
  488.                        org.exoplatform.portal.config.model.Application<Gadget> gadgetApplication,
  489.                        org.exoplatform.portal.config.model.Application<Portlet> portletApplication,
  490.                        Page page) {
  491.    
  492.     ArrayList<ModelObject> pageChilds = page.getChildren();

  493.     //
  494.     Container container = SpaceUtils.findContainerById(pageChilds, SpaceUtils.APPLICATION_CONTAINER);
  495.     ArrayList<ModelObject> children = container.getChildren();
  496.    
  497.     if (app.getType() == ApplicationType.GADGET) {
  498.       children.add(gadgetApplication);
  499.     } else {
  500.       children.add(portletApplication);
  501.     }
  502.     container.setChildren(children);
  503.     pageChilds = setContainerById(pageChilds, container);
  504.     page.setChildren(pageChilds);
  505.     setPermissionForPage(page.getChildren(), "*:" + space.getGroupId());
  506.   }
  507.  
  508.   /**
  509.    * Gets an application from appStore by appId.
  510.    *
  511.    * @param appStore
  512.    * @param appId
  513.    * @return app or null
  514.    */
  515.   private Application getApplication(Map<ApplicationCategory, List<Application>> appStore,
  516.                                      String appId) {
  517.     Iterator<ApplicationCategory> categoryItr = appStore.keySet().iterator();
  518.     while (categoryItr.hasNext()) {
  519.       ApplicationCategory category = categoryItr.next();
  520.       List<Application> appList = category.getApplications();
  521.       Iterator<Application> appListItr = appList.iterator();
  522.       while (appListItr.hasNext()) {
  523.         Application app = appListItr.next();
  524.         if (app.getApplicationName().equals(appId)) {
  525.           return app;
  526.         }
  527.       }
  528.     }
  529.     return null;
  530.   }

  531.   /**
  532.    * Sets permission for page.
  533.    *
  534.    * @param children
  535.    * @param perm
  536.    * @return
  537.    */
  538.   @SuppressWarnings("unchecked")
  539.   private void setPermissionForPage(ArrayList<ModelObject> children, String perm) {
  540.     for (ModelObject modelObject : children) {
  541.       if (modelObject instanceof org.exoplatform.portal.config.model.Application<?>) {
  542.         ((org.exoplatform.portal.config.model.Application) modelObject).setAccessPermissions(new String[]{perm});
  543.       } else if (modelObject instanceof Container) {
  544.         ((Container) modelObject).setAccessPermissions(new String[]{perm});
  545.         setPermissionForPage(((Container) modelObject).getChildren(), perm);
  546.       }
  547.     }
  548.   }

  549.   /**
  550.    * Sets container by Id
  551.    *
  552.    * @param childs
  553.    * @param container
  554.    * @return
  555.    */
  556.   private ArrayList<ModelObject> setContainerById(ArrayList<ModelObject> childs, Container container) {
  557.     ArrayList<ModelObject> result = childs;
  558.     int index = result.indexOf(container);
  559.     //if container existing and child of the page
  560.     if (index != -1) {
  561.       result.set(index, container);
  562.     } else {
  563.       for (int i = 0; i < result.size(); i++) {
  564.         ModelObject obj = result.get(i);
  565.         if (org.exoplatform.portal.config.model.Application.class.isInstance(obj)) {
  566.           continue;
  567.         }
  568.         Container objContainer = (Container) obj;
  569.         ArrayList<ModelObject> tmp = setContainerById(objContainer.getChildren(), container);
  570.         objContainer.setChildren(tmp);
  571.         result.set(i, objContainer);
  572.       }
  573.     }
  574.     return result;
  575.   }

  576.   /**
  577.    * Creates portlet application from instanceId
  578.    *
  579.    * @param instanceId
  580.    * @return
  581.    */
  582.   private org.exoplatform.portal.config.model.Application<Portlet> createPortletApplication(String instanceId,
  583.                                                                                             Space space,
  584.                                                                                             boolean isRoot) {
  585.     int i0 = instanceId.indexOf("#");
  586.     int i1 = instanceId.indexOf(":/", i0 + 1);
  587.     String ownerType = instanceId.substring(0, i0);
  588.     String ownerId = instanceId.substring(i0 + 1, i1);
  589.     String persistenceid = instanceId.substring(i1 + 2);
  590.     String[] persistenceChunks = Utils.split("/", persistenceid);
  591.     PortletBuilder pb = new PortletBuilder();

  592.     String spaceTemplateName = space.getTemplate();
  593.     SpaceTemplate spaceTemplate = spaceTemplateService.getSpaceTemplateByName(spaceTemplateName);
  594.     if (spaceTemplate == null) {
  595.       throw new IllegalStateException("Space template with name " + spaceTemplateName +" wasn't found");
  596.     }
  597.     List<SpaceApplication> spaceApplicationList = spaceTemplate.getSpaceApplicationList();
  598.     SpaceApplication spaceApplication = null;
  599.     for (Iterator<SpaceApplication> iterator = spaceApplicationList.iterator(); iterator.hasNext() && spaceApplication == null;) {
  600.       SpaceApplication tmpSpaceApplication = iterator.next();
  601.       if (instanceId.contains(tmpSpaceApplication.getPortletName())) {
  602.         spaceApplication = tmpSpaceApplication;
  603.       }
  604.     }
  605.     if (spaceApplication != null && spaceApplication.getPreferences() != null) {
  606.       Set<Entry<String, String>> entrySet = spaceApplication.getPreferences().entrySet();
  607.       try {
  608.         for (Map.Entry<String, String> preference : entrySet) {
  609.           pb.add(preference.getKey(), getSubstituteValueFromPattern(space, spaceApplication, preference.getValue()));
  610.         }
  611.       } catch (Exception exception) {
  612.         LOG.warn(exception.getMessage(), exception);
  613.       }
  614.     }

  615.     TransientApplicationState<Portlet> portletState = new TransientApplicationState<Portlet>(persistenceChunks[0]
  616.             + "/"
  617.             + persistenceChunks[1],
  618.             pb.build(),
  619.             ownerType,
  620.             ownerId);
  621.     org.exoplatform.portal.config.model.Application<Portlet> portletApp =
  622.             org.exoplatform.portal.config.model.Application.createPortletApplication();
  623.     portletApp.setState(portletState);
  624.     return portletApp;
  625.   }

  626.   private String getSubstituteValueFromPattern(Space space, SpaceApplication spaceApplication, String pattern) {
  627.     if (!pattern.contains("{") || !pattern.contains("}")) {
  628.       return pattern;
  629.     }
  630.    
  631.     if (pattern.contains(GROUP_ID_PREFERENCE)) {
  632.       pattern = pattern.replace(GROUP_ID_PREFERENCE, space.getGroupId());
  633.     } else if (pattern.contains(MODIFIED_GROUP_ID_PREFERENCE)) {
  634.       String modifiedGroupId = space.getGroupId().replace("/", ".");
  635.       pattern = pattern.replace(MODIFIED_GROUP_ID_PREFERENCE, modifiedGroupId);
  636.     } else if (pattern.contains(PAGE_NAME_PREFERENCE)) {
  637.       pattern = pattern.replace(PAGE_NAME_PREFERENCE, spaceApplication.getAppTitle());
  638.     } else if (pattern.contains(PAGE_URL_PREFERENCE)) {
  639.       pattern = pattern.replace(PAGE_URL_PREFERENCE, spaceApplication.getUri());
  640.     }
  641.     return pattern;
  642.   }

  643.   /**
  644.    * Gets userPortalConfigService for the usage of creating new page from page template
  645.    *
  646.    * @return
  647.    */
  648.   private UserPortalConfigService getUserPortalConfigService() {
  649.     return (UserPortalConfigService) container.getComponentInstanceOfType(UserPortalConfigService.class);
  650.   }

  651.   private SpaceService getSpaceService() {
  652.     ExoContainer container = ExoContainerContext.getCurrentContainer();
  653.     if (spaceService == null) {
  654.       spaceService = (SpaceService) container.getComponentInstance(SpaceService.class);
  655.     }

  656.     return spaceService;
  657.   }
  658. }