private void _checkPermission() throws PrincipalException {
    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    if ((permissionChecker == null) || !permissionChecker.isOmniadmin()) {
      throw new PrincipalException();
    }
  }
  protected void addSearchAnyTags(BooleanQuery contextQuery, SearchContext searchContext)
      throws Exception {

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    long[] anyTagIds = _assetEntryQuery.getAnyTagIds();

    if (anyTagIds.length == 0) {
      return;
    }

    long[] filteredAnyTagIds = AssetUtil.filterTagIds(permissionChecker, anyTagIds);

    if (filteredAnyTagIds.length == 0) {
      addImpossibleTerm(contextQuery, Field.ASSET_TAG_IDS);

      return;
    }

    BooleanQuery tagIdsQuery = BooleanQueryFactoryUtil.create(searchContext);

    for (long tagId : anyTagIds) {
      tagIdsQuery.addTerm(Field.ASSET_TAG_IDS, tagId);
    }

    contextQuery.add(tagIdsQuery, BooleanClauseOccur.MUST);
  }
  protected void copyPreferences(String sourcePortletId, String targetPortletId) {

    Layout layout = getLayout();

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PortletPreferencesIds portletPreferencesIds =
          PortletPreferencesFactoryUtil.getPortletPreferencesIds(
              layout.getGroupId(), permissionChecker.getUserId(), layout, sourcePortletId, false);

      javax.portlet.PortletPreferences sourcePortletPreferences =
          PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);

      portletPreferencesIds =
          PortletPreferencesFactoryUtil.getPortletPreferencesIds(
              layout.getGroupId(), permissionChecker.getUserId(), layout, targetPortletId, false);

      PortletPreferencesLocalServiceUtil.updatePreferences(
          portletPreferencesIds.getOwnerId(),
          portletPreferencesIds.getOwnerType(),
          portletPreferencesIds.getPlid(),
          portletPreferencesIds.getPortletId(),
          sourcePortletPreferences);
    } catch (Exception e) {
    }
  }
示例#4
0
  public String transform(
      ThemeDisplay themeDisplay, Map<String, Object> contextObjects, String script, String langType)
      throws Exception {

    if (Validator.isNull(langType)) {
      return null;
    }

    long companyId = 0;
    long companyGroupId = 0;
    long scopeGroupId = 0;
    long siteGroupId = 0;

    if (themeDisplay != null) {
      companyId = themeDisplay.getCompanyId();
      companyGroupId = themeDisplay.getCompanyGroupId();
      scopeGroupId = themeDisplay.getScopeGroupId();
      siteGroupId = themeDisplay.getSiteGroupId();
    }

    String templateId = String.valueOf(contextObjects.get("template_id"));

    templateId = getTemplateId(templateId, companyId, companyGroupId, scopeGroupId);

    Template template = getTemplate(templateId, script, langType);

    UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

    try {
      if (contextObjects != null) {
        for (String key : contextObjects.keySet()) {
          template.put(key, contextObjects.get(key));
        }
      }

      template.put("company", getCompany(themeDisplay, companyId));
      template.put("companyId", companyId);
      template.put("device", getDevice(themeDisplay));

      String templatesPath = getTemplatesPath(companyId, scopeGroupId);

      template.put("journalTemplatesPath", templatesPath);
      template.put("permissionChecker", PermissionThreadLocal.getPermissionChecker());
      template.put(
          "randomNamespace", PwdGenerator.getPassword(PwdGenerator.KEY3, 4) + StringPool.UNDERLINE);
      template.put("scopeGroupId", scopeGroupId);
      template.put("siteGroupId", siteGroupId);
      template.put("templatesPath", templatesPath);

      // Deprecated variables

      template.put("groupId", scopeGroupId);

      mergeTemplate(template, unsyncStringWriter);
    } catch (Exception e) {
      throw new TransformException("Unhandled exception", e);
    }

    return unsyncStringWriter.toString();
  }
  @Test
  public void testFilterFindByG_N() throws Exception {
    Group scopeGroup = addScopeGroup();

    Group siteGroup = scopeGroup.getParentGroup();

    String assetTagName = ServiceTestUtil.randomString();

    addAssetTag(siteGroup.getGroupId(), assetTagName, null);

    User user = UserTestUtil.addUser(null, 0);

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      try {
        AssetTagFinderUtil.filterFindByG_N(scopeGroup.getGroupId(), assetTagName);

        Assert.fail();
      } catch (NoSuchTagException nste) {
      }

      AssetTag siteGroupAssetTag =
          AssetTagFinderUtil.filterFindByG_N(siteGroup.getGroupId(), assetTagName);

      Assert.assertEquals(StringUtil.toLowerCase(assetTagName), siteGroupAssetTag.getName());
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }
  @Override
  public boolean isDisabled(Object obj) {
    if (!PropsValues.ORGANIZATIONS_ASSIGNMENT_STRICT) {
      return false;
    }

    User user = (User) obj;

    try {
      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      if (isChecked(user)) {
        if (OrganizationMembershipPolicyUtil.isMembershipProtected(
                permissionChecker, user.getUserId(), _organization.getOrganizationId())
            || OrganizationMembershipPolicyUtil.isMembershipRequired(
                user.getUserId(), _organization.getOrganizationId())) {

          return true;
        }
      } else {
        if (!OrganizationMembershipPolicyUtil.isMembershipAllowed(
            user.getUserId(), _organization.getOrganizationId())) {

          return true;
        }
      }

      return !UserPermissionUtil.contains(permissionChecker, user.getUserId(), ActionKeys.UPDATE);
    } catch (Exception e) {
      _log.error(e, e);
    }

    return super.isDisabled(obj);
  }
  @Override
  public boolean isDisabled(Object obj) {
    User user = (User) obj;

    try {
      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      if (isChecked(user)) {
        if (OrganizationMembershipPolicyUtil.isRoleProtected(
                permissionChecker,
                user.getUserId(),
                _organization.getOrganizationId(),
                _role.getRoleId())
            || OrganizationMembershipPolicyUtil.isRoleRequired(
                user.getUserId(), _organization.getOrganizationId(), _role.getRoleId())) {

          return true;
        }
      } else {
        if (!OrganizationMembershipPolicyUtil.isRoleAllowed(
            user.getUserId(), _organization.getOrganizationId(), _role.getRoleId())) {

          return true;
        }
      }
    } catch (Exception e) {
      _log.error(e, e);
    }

    return super.isDisabled(obj);
  }
  @Override
  public void removePortletId(long userId, String portletId, boolean cleanUp) {

    try {
      Portlet portlet = PortletLocalServiceUtil.getPortletById(getCompanyId(), portletId);

      if (portlet == null) {
        _log.error("Portlet " + portletId + " cannot be removed because it is not registered");

        return;
      }

      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      if (!LayoutPermissionUtil.contains(permissionChecker, getLayout(), ActionKeys.UPDATE)
          && !isCustomizable()) {

        return;
      }
    } catch (Exception e) {
      _log.error(e, e);

      return;
    }

    List<String> columns = getColumns();

    for (int i = 0; i < columns.size(); i++) {
      String columnId = columns.get(i);

      if (isCustomizable() && isColumnDisabled(columnId)) {
        continue;
      }

      String columnValue = StringPool.BLANK;

      if (hasUserPreferences()) {
        columnValue = getUserPreference(columnId);
      } else {
        columnValue = getTypeSettingsProperty(columnId);
      }

      columnValue = StringUtil.removeFromList(columnValue, portletId);

      if (hasUserPreferences()) {
        setUserPreference(columnId, columnValue);
      } else {
        setTypeSettingsProperty(columnId, columnValue);
      }
    }

    if (cleanUp) {
      try {
        onRemoveFromLayout(new String[] {portletId});
      } catch (Exception e) {
        _log.error(e, e);
      }
    }
  }
  protected void checkWikiPagePermission(long scopeGroupId) throws PortalException {

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    if (!permissionChecker.hasPermission(
        scopeGroupId, "com.liferay.portlet.wiki", scopeGroupId, ActionKeys.ADD_NODE)) {

      throw new PrincipalException();
    }
  }
  protected void checkMBMessagePermission(long scopeGroupId) throws PortalException {

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    if (!permissionChecker.hasPermission(
        scopeGroupId, "com.liferay.portlet.messageboards", scopeGroupId, ActionKeys.BAN_USER)) {

      throw new PrincipalException();
    }
  }
示例#11
0
  protected void addSearchAllCategories(BooleanQuery contextQuery, SearchContext searchContext)
      throws Exception {

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    long[] allCategoryIds = _assetEntryQuery.getAllCategoryIds();

    if (allCategoryIds.length == 0) {
      return;
    }

    long[] filteredAllCategoryIds = AssetUtil.filterCategoryIds(permissionChecker, allCategoryIds);

    if (allCategoryIds.length != filteredAllCategoryIds.length) {
      addImpossibleTerm(contextQuery, Field.ASSET_CATEGORY_IDS);

      return;
    }

    BooleanQuery categoryIdsQuery = BooleanQueryFactoryUtil.create(searchContext);

    for (long allCategoryId : filteredAllCategoryIds) {
      AssetCategory assetCategory = AssetCategoryLocalServiceUtil.fetchAssetCategory(allCategoryId);

      if (assetCategory == null) {
        continue;
      }

      List<Long> categoryIds = new ArrayList<>();

      if (PropsValues.ASSET_CATEGORIES_SEARCH_HIERARCHICAL) {
        categoryIds.addAll(AssetCategoryLocalServiceUtil.getSubcategoryIds(allCategoryId));
      }

      if (categoryIds.isEmpty()) {
        categoryIds.add(allCategoryId);
      }

      BooleanQuery categoryIdQuery = BooleanQueryFactoryUtil.create(searchContext);

      for (long categoryId : categoryIds) {
        categoryIdQuery.addTerm(Field.ASSET_CATEGORY_IDS, categoryId);
      }

      categoryIdsQuery.add(categoryIdQuery, BooleanClauseOccur.MUST);
    }

    contextQuery.add(categoryIdsQuery, BooleanClauseOccur.MUST);
  }
  @Test(expected = PrincipalException.class)
  public void testCreateRepositoryFromExistingFolderWithoutPermissions() throws Exception {

    DLFolder dlFolder = DLTestUtil.addDLFolder(_group.getGroupId());

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PermissionThreadLocal.setPermissionChecker(new AlwaysDenyingPermissionChecker());

      RepositoryFactoryUtil.create(dlFolder.getFolderId(), 0, 0);
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }
  protected KBArticle getKBArticle(long resourcePrimKey, int status) throws Exception {

    KBArticle kbArticle = KBArticleLocalServiceUtil.fetchLatestKBArticle(resourcePrimKey, status);

    if (kbArticle == null) {
      return null;
    }

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    if (!KBArticlePermission.contains(permissionChecker, kbArticle, ActionKeys.VIEW)) {

      return null;
    }

    return kbArticle;
  }
  protected void testUserPermissions(
      boolean addBaseModelPermission, boolean addParentBaseModelPermission) throws Exception {

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(group.getGroupId());

    SearchContext searchContext = SearchContextTestUtil.getSearchContext(group.getGroupId());

    searchContext.setKeywords(getSearchKeywords());

    int initialBaseModelsSearchCount =
        searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), searchContext);

    serviceContext.setAddGroupPermissions(addParentBaseModelPermission);
    serviceContext.setAddGuestPermissions(addParentBaseModelPermission);

    BaseModel<?> parentBaseModel = getParentBaseModel(group, serviceContext);

    serviceContext.setAddGroupPermissions(addBaseModelPermission);
    serviceContext.setAddGuestPermissions(addBaseModelPermission);

    baseModel = addBaseModel(parentBaseModel, true, getSearchKeywords(), serviceContext);

    User user = UserTestUtil.addUser(null, 0);

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      searchContext.setUserId(user.getUserId());

      int baseModelsCount = initialBaseModelsSearchCount;

      if (addBaseModelPermission && !isCheckBaseModelPermission()) {
        baseModelsCount++;
      }

      Assert.assertEquals(
          baseModelsCount,
          searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), searchContext));
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }
  @Test
  public void testFilterCountByG_N_P() throws Exception {
    Group scopeGroup = addScopeGroup();

    Group siteGroup = scopeGroup.getParentGroup();

    String assetTagName = ServiceTestUtil.randomString();
    String[] assetTagProperties = {
      "key" + AssetTagConstants.PROPERTY_KEY_VALUE_SEPARATOR + "value"
    };

    int initialScopeGroupAssetTagsCount =
        AssetTagFinderUtil.filterCountByG_N_P(
            scopeGroup.getGroupId(), assetTagName, assetTagProperties);
    int initialTagsCountSiteGroup =
        AssetTagFinderUtil.filterCountByG_N_P(
            siteGroup.getGroupId(), assetTagName, assetTagProperties);

    addAssetTag(siteGroup.getGroupId(), assetTagName, assetTagProperties);

    User user = UserTestUtil.addUser(null, 0);

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      int scopeGroupAssetTagsCount =
          AssetTagFinderUtil.filterCountByG_N_P(
              scopeGroup.getGroupId(), assetTagName, assetTagProperties);

      Assert.assertEquals(initialScopeGroupAssetTagsCount, scopeGroupAssetTagsCount);

      int siteGroupAssetTagsCount =
          AssetTagFinderUtil.filterCountByG_N_P(
              siteGroup.getGroupId(), assetTagName, assetTagProperties);

      Assert.assertEquals(initialTagsCountSiteGroup + 1, siteGroupAssetTagsCount);
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }
示例#16
0
  protected void initThreadLocals(User user) throws Exception {
    CompanyThreadLocal.setCompanyId(user.getCompanyId());

    PrincipalThreadLocal.setName(user.getUserId());

    if (!_usePermissionChecker) {
      return;
    }

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    if (permissionChecker != null) {
      return;
    }

    permissionChecker = PermissionCheckerFactoryUtil.create(user);

    PermissionThreadLocal.setPermissionChecker(permissionChecker);
  }
  @Test
  public void testFilterCountByG_C_N() throws Exception {
    Group scopeGroup = addScopeGroup();

    Group siteGroup = scopeGroup.getParentGroup();

    long classNameId = PortalUtil.getClassNameId(BlogsEntry.class);
    String assetTagName = ServiceTestUtil.randomString();

    int initialScopeGroupAssetTagsCount =
        AssetTagFinderUtil.filterCountByG_C_N(scopeGroup.getGroupId(), classNameId, assetTagName);
    int initialSiteGroupAssetTagsCount =
        AssetTagFinderUtil.filterCountByG_C_N(siteGroup.getGroupId(), classNameId, assetTagName);

    addBlogsEntry(scopeGroup.getGroupId(), assetTagName);

    User user = UserTestUtil.addUser(null, 0);

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      int scopeGroupAssetTagsCount =
          AssetTagFinderUtil.filterCountByG_C_N(scopeGroup.getGroupId(), classNameId, assetTagName);

      Assert.assertEquals(initialScopeGroupAssetTagsCount + 1, scopeGroupAssetTagsCount);

      int siteGroupAssetTagsCount =
          AssetTagFinderUtil.filterCountByG_C_N(siteGroup.getGroupId(), classNameId, assetTagName);

      Assert.assertEquals(initialSiteGroupAssetTagsCount, siteGroupAssetTagsCount);
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }
示例#18
0
  public Hits search(
      long companyId,
      long userId,
      String portletId,
      long groupId,
      long[] repositoryIds,
      String keywords,
      int start,
      int end) {

    try {
      SearchContext searchContext = new SearchContext();

      searchContext.setCompanyId(companyId);
      searchContext.setEnd(end);
      searchContext.setEntryClassNames(new String[] {DLFileEntryConstants.getClassName()});
      searchContext.setGroupIds(new long[] {groupId});

      Indexer indexer = IndexerRegistryUtil.getIndexer(DLFileEntryConstants.getClassName());

      searchContext.setSearchEngineId(indexer.getSearchEngineId());

      searchContext.setStart(start);
      searchContext.setUserId(userId);

      BooleanQuery contextQuery = BooleanQueryFactoryUtil.create(searchContext);

      contextQuery.addRequiredTerm(Field.PORTLET_ID, portletId);

      if (groupId > 0) {
        Group group = groupLocalService.getGroup(groupId);

        if (group.isLayout()) {
          contextQuery.addRequiredTerm(Field.SCOPE_GROUP_ID, groupId);

          groupId = group.getParentGroupId();
        }

        contextQuery.addRequiredTerm(Field.GROUP_ID, groupId);
      }

      if (ArrayUtil.isNotEmpty(repositoryIds)) {
        BooleanQuery repositoryIdsQuery = BooleanQueryFactoryUtil.create(searchContext);

        for (long repositoryId : repositoryIds) {
          try {
            if (userId > 0) {
              PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

              DLFolderPermission.check(permissionChecker, groupId, repositoryId, ActionKeys.VIEW);
            }

            if (repositoryId == DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

              repositoryId = groupId;
            }

            TermQuery termQuery =
                TermQueryFactoryUtil.create(searchContext, "repositoryId", repositoryId);

            repositoryIdsQuery.add(termQuery, BooleanClauseOccur.SHOULD);
          } catch (Exception e) {
          }
        }

        contextQuery.add(repositoryIdsQuery, BooleanClauseOccur.MUST);
      }

      BooleanQuery searchQuery = BooleanQueryFactoryUtil.create(searchContext);

      searchQuery.addTerms(_KEYWORDS_FIELDS, keywords);

      BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(searchContext);

      fullQuery.add(contextQuery, BooleanClauseOccur.MUST);

      List<BooleanClause> clauses = searchQuery.clauses();

      if (!clauses.isEmpty()) {
        fullQuery.add(searchQuery, BooleanClauseOccur.MUST);
      }

      return SearchEngineUtil.search(searchContext, fullQuery);
    } catch (Exception e) {
      throw new SystemException(e);
    }
  }
  @Override
  public PortletPreferencesIds getPortletPreferencesIds(
      long siteGroupId, long userId, Layout layout, String portletId, boolean modeEditGuest)
      throws PortalException {

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    String originalPortletId = portletId;

    Portlet portlet = PortletLocalServiceUtil.getPortletById(layout.getCompanyId(), portletId);

    long ownerId = 0;
    int ownerType = 0;
    long plid = 0;

    if (modeEditGuest) {
      boolean hasUpdateLayoutPermission =
          LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.UPDATE);

      if (!layout.isPrivateLayout() && hasUpdateLayoutPermission) {
      } else {

        // Only users with the correct permissions can update guest
        // preferences

        throw new PrincipalException();
      }
    }

    if (PortletConstants.hasUserId(originalPortletId)
        && (PortletConstants.getUserId(originalPortletId) == userId)) {

      ownerId = userId;
      ownerType = PortletKeys.PREFS_OWNER_TYPE_USER;
      plid = layout.getPlid();
    } else if (portlet.isPreferencesCompanyWide()) {
      ownerId = layout.getCompanyId();
      ownerType = PortletKeys.PREFS_OWNER_TYPE_COMPANY;
      plid = PortletKeys.PREFS_PLID_SHARED;
      portletId = PortletConstants.getRootPortletId(portletId);
    } else {
      if (portlet.isPreferencesUniquePerLayout()) {
        ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT;
        ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT;
        plid = layout.getPlid();

        if (portlet.isPreferencesOwnedByGroup()) {
        } else {
          if ((userId <= 0) || modeEditGuest) {
            userId = UserLocalServiceUtil.getDefaultUserId(layout.getCompanyId());
          }

          ownerId = userId;
          ownerType = PortletKeys.PREFS_OWNER_TYPE_USER;
        }
      } else {
        plid = PortletKeys.PREFS_PLID_SHARED;

        if (portlet.isPreferencesOwnedByGroup()) {
          ownerId = siteGroupId;
          ownerType = PortletKeys.PREFS_OWNER_TYPE_GROUP;
          portletId = PortletConstants.getRootPortletId(portletId);
        } else {
          if ((userId <= 0) || modeEditGuest) {
            userId = UserLocalServiceUtil.getDefaultUserId(layout.getCompanyId());
          }

          ownerId = userId;
          ownerType = PortletKeys.PREFS_OWNER_TYPE_USER;
        }
      }
    }

    return new PortletPreferencesIds(layout.getCompanyId(), ownerId, ownerType, plid, portletId);
  }
  protected String getUserPreference(String key) {
    String value = StringPool.BLANK;

    if (!hasUserPreferences()) {
      return value;
    }

    value =
        _portalPreferences.getValue(CustomizedPages.namespacePlid(getPlid()), key, StringPool.NULL);

    if (!value.equals(StringPool.NULL)) {
      return value;
    }

    value = getTypeSettingsProperty(key);

    if (Validator.isNull(value)) {
      return value;
    }

    List<String> newPortletIds = new ArrayList<>();

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    String[] portletIds = StringUtil.split(value);

    for (String portletId : portletIds) {
      try {
        String rootPortletId = PortletConstants.getRootPortletId(portletId);

        if (!PortletPermissionUtil.contains(
            permissionChecker, rootPortletId, ActionKeys.ADD_TO_PAGE)) {

          continue;
        }
      } catch (Exception e) {
        _log.error(e, e);
      }

      String newPortletId = null;

      boolean preferencesUniquePerLayout = false;

      try {
        Portlet portlet = PortletLocalServiceUtil.getPortletById(getCompanyId(), portletId);

        preferencesUniquePerLayout = portlet.isPreferencesUniquePerLayout();
      } catch (SystemException se) {
        _log.error(se, se);
      }

      if (PortletConstants.hasInstanceId(portletId) || preferencesUniquePerLayout) {

        String instanceId = null;

        if (PortletConstants.hasInstanceId(portletId)) {
          instanceId = PortletConstants.generateInstanceId();
        }

        newPortletId =
            PortletConstants.assemblePortletId(
                portletId, _portalPreferences.getUserId(), instanceId);

        copyPreferences(_portalPreferences.getUserId(), portletId, newPortletId);
      } else {
        newPortletId = portletId;
      }

      newPortletIds.add(newPortletId);
    }

    value = StringUtil.merge(newPortletIds);

    setUserPreference(key, value);

    return value;
  }
  protected String addPortletId(
      long userId,
      String portletId,
      String columnId,
      int columnPos,
      boolean checkPermission,
      boolean strictHasPortlet)
      throws PortalException {

    portletId = JS.getSafeName(portletId);

    Layout layout = getLayout();

    Portlet portlet = null;

    try {
      portlet = PortletLocalServiceUtil.getPortletById(layout.getCompanyId(), portletId);

      if (portlet == null) {
        if (_log.isWarnEnabled()) {
          _log.warn("Portlet " + portletId + " cannot be added because it is not registered");
        }

        return null;
      }

      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      if (checkPermission
          && !PortletPermissionUtil.contains(
              permissionChecker, layout, portlet, ActionKeys.ADD_TO_PAGE)) {

        return null;
      }
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (portlet.isSystem()) {
      return null;
    }

    if (portlet.isInstanceable() && !PortletConstants.hasInstanceId(portletId)) {

      portletId =
          PortletConstants.assemblePortletId(portletId, PortletConstants.generateInstanceId());
    }

    if (hasPortletId(portletId, strictHasPortlet)) {
      return null;
    }

    if (columnId == null) {
      LayoutTemplate layoutTemplate = getLayoutTemplate();

      List<String> columns = layoutTemplate.getColumns();

      if (!columns.isEmpty()) {
        columnId = columns.get(0);
      }
    }

    if (columnId == null) {
      return null;
    }

    if (isCustomizable()) {
      if (isColumnDisabled(columnId)) {
        return null;
      }

      if ((PortletConstants.hasInstanceId(portletId) || portlet.isPreferencesUniquePerLayout())
          && hasUserPreferences()) {

        portletId = PortletConstants.assemblePortletId(portletId, userId);
      }
    }

    String columnValue = StringPool.BLANK;

    if (hasUserPreferences()) {
      columnValue = getUserPreference(columnId);
    } else {
      columnValue = getTypeSettingsProperty(columnId);
    }

    if ((columnValue == null) && columnId.startsWith(_NESTED_PORTLETS_NAMESPACE)) {

      addNestedColumn(columnId);
    }

    if (columnPos >= 0) {
      List<String> portletIds = ListUtil.fromArray(StringUtil.split(columnValue));

      if (columnPos <= portletIds.size()) {
        portletIds.add(columnPos, portletId);
      } else {
        portletIds.add(portletId);
      }

      columnValue = StringUtil.merge(portletIds);
    } else {
      columnValue = StringUtil.add(columnValue, portletId);
    }

    if (hasUserPreferences()) {
      setUserPreference(columnId, columnValue);
    } else {
      setTypeSettingsProperty(columnId, columnValue);
    }

    try {
      if (_enablePortletLayoutListener) {
        PortletLayoutListener portletLayoutListener = portlet.getPortletLayoutListenerInstance();

        if (portletLayoutListener != null) {
          portletLayoutListener.onAddToLayout(portletId, layout.getPlid());
        }
      }
    } catch (Exception e) {
      _log.error("Unable to fire portlet layout listener event", e);
    }

    return portletId;
  }
  @Test
  public void testFilterFindByG_N_P() throws Exception {
    Group scopeGroup = addScopeGroup();

    Group siteGroup = scopeGroup.getParentGroup();

    String assetTagName = ServiceTestUtil.randomString();
    String[] assetTagProperties = {
      "key" + AssetTagConstants.PROPERTY_KEY_VALUE_SEPARATOR + "value"
    };

    List<AssetTag> initialScopeGroupAssetTags =
        AssetTagFinderUtil.filterFindByG_N_P(
            new long[] {scopeGroup.getGroupId()},
            assetTagName,
            assetTagProperties,
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS,
            null);
    List<AssetTag> initialSiteGroupAssetTags =
        AssetTagFinderUtil.filterFindByG_N_P(
            new long[] {siteGroup.getGroupId()},
            assetTagName,
            assetTagProperties,
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS,
            null);

    addAssetTag(siteGroup.getGroupId(), assetTagName, assetTagProperties);

    User user = UserTestUtil.addUser(null, 0);

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      List<AssetTag> scopeGroupAssetTags =
          AssetTagFinderUtil.filterFindByG_N_P(
              new long[] {scopeGroup.getGroupId()},
              assetTagName,
              assetTagProperties,
              QueryUtil.ALL_POS,
              QueryUtil.ALL_POS,
              null);

      Assert.assertEquals(initialScopeGroupAssetTags.size(), scopeGroupAssetTags.size());

      List<AssetTag> siteGroupAssetTags =
          AssetTagFinderUtil.filterFindByG_N_P(
              new long[] {siteGroup.getGroupId()},
              assetTagName,
              assetTagProperties,
              QueryUtil.ALL_POS,
              QueryUtil.ALL_POS,
              null);

      Assert.assertEquals(initialSiteGroupAssetTags.size() + 1, siteGroupAssetTags.size());
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }
示例#23
0
  protected String doTransform(
      ThemeDisplay themeDisplay,
      Map<String, String> tokens,
      String viewMode,
      String languageId,
      String xml,
      String script)
      throws Exception {

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    long companyId = GetterUtil.getLong(tokens.get("company_id"));
    Company company = CompanyLocalServiceUtil.getCompanyById(companyId);
    long groupId = GetterUtil.getLong(tokens.get("group_id"));
    String journalTemplatesPath =
        VelocityResourceListener.JOURNAL_SEPARATOR
            + StringPool.SLASH
            + companyId
            + StringPool.SLASH
            + groupId;
    String randomNamespace = PwdGenerator.getPassword(PwdGenerator.KEY3, 4) + StringPool.UNDERLINE;
    Locale locale = LocaleUtil.fromLanguageId(languageId);

    XSLErrorListener xslErrorListener = new XSLErrorListener(locale);

    StreamSource xmlSource = new StreamSource(new UnsyncStringReader(xml));

    TransformerFactory transformerFactory = TransformerFactory.newInstance();

    transformerFactory.setURIResolver(new URIResolver(tokens, languageId));
    transformerFactory.setErrorListener(xslErrorListener);

    try {
      StreamSource scriptSource = new StreamSource(new UnsyncStringReader(script));

      Transformer transformer = transformerFactory.newTransformer(scriptSource);

      transformer.setParameter("company", company);
      transformer.setParameter("companyId", new Long(companyId));
      transformer.setParameter("groupId", String.valueOf(groupId));
      transformer.setParameter("journalTemplatesPath", journalTemplatesPath);
      transformer.setParameter("viewMode", viewMode);
      transformer.setParameter("locale", locale);
      transformer.setParameter("permissionChecker", PermissionThreadLocal.getPermissionChecker());
      transformer.setParameter("randomNamespace", randomNamespace);

      transformer.transform(xmlSource, new StreamResult(unsyncByteArrayOutputStream));
    } catch (Exception e1) {
      String errorTemplate = ContentUtil.get(PropsValues.JOURNAL_ERROR_TEMPLATE_XSL);

      StreamSource scriptSource = new StreamSource(new UnsyncStringReader(errorTemplate));

      Transformer transformer = transformerFactory.newTransformer(scriptSource);

      transformer.setParameter("company", company);
      transformer.setParameter("companyId", new Long(companyId));
      transformer.setParameter("groupId", String.valueOf(groupId));
      transformer.setParameter("journalTemplatesPath", journalTemplatesPath);
      transformer.setParameter("locale", locale);
      transformer.setParameter("randomNamespace", randomNamespace);

      transformer.setParameter("exception", xslErrorListener.getMessageAndLocation());
      transformer.setParameter("script", script);

      if (xslErrorListener.getLocation() != null) {
        transformer.setParameter("column", new Integer(xslErrorListener.getColumnNumber()));
        transformer.setParameter("line", new Integer(xslErrorListener.getLineNumber()));
      }

      transformer.transform(xmlSource, new StreamResult(unsyncByteArrayOutputStream));
    }

    return unsyncByteArrayOutputStream.toString(StringPool.UTF8);
  }
  public String addPortletId(
      long userId, String portletId, String columnId, int columnPos, boolean checkPermission)
      throws PortalException, SystemException {

    portletId = JS.getSafeName(portletId);

    Layout layout = getLayout();

    Portlet portlet = null;

    try {
      portlet = PortletLocalServiceUtil.getPortletById(layout.getCompanyId(), portletId);

      if (portlet == null) {
        if (_log.isWarnEnabled()) {
          _log.warn("Portlet " + portletId + " cannot be added because it is not registered");
        }

        return null;
      }

      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      if (checkPermission
          && !PortletPermissionUtil.contains(
              permissionChecker, layout, portlet, ActionKeys.ADD_TO_PAGE)) {

        return null;
      }
    } catch (Exception e) {
      _log.error(e, e);
    }

    if (portlet.isSystem()) {
      return null;
    }

    if ((portlet.isInstanceable())
        && (PortletConstants.getInstanceId(portlet.getPortletId()) == null)) {

      portletId = portletId + getFullInstanceSeparator();
    }

    if (hasPortletId(portletId)) {
      return null;
    }

    if (columnId == null) {
      LayoutTemplate layoutTemplate = getLayoutTemplate();

      List<String> columns = layoutTemplate.getColumns();

      if (columns.size() > 0) {
        columnId = columns.get(0);
      }
    }

    if (columnId != null) {
      if (isCustomizable() && isColumnDisabled(columnId)) {
        return null;
      }

      String columnValue = StringPool.BLANK;

      if (hasUserPreferences()) {
        columnValue = getUserPreference(columnId);
      } else {
        columnValue = getTypeSettingsProperties().getProperty(columnId);
      }

      if ((columnValue == null) && (columnId.startsWith(_nestedPortletsNamespace))) {

        addNestedColumn(columnId);
      }

      if (columnPos >= 0) {
        List<String> portletIds = ListUtil.fromArray(StringUtil.split(columnValue));

        if (columnPos <= portletIds.size()) {
          portletIds.add(columnPos, portletId);
        } else {
          portletIds.add(portletId);
        }

        columnValue = StringUtil.merge(portletIds);
      } else {
        columnValue = StringUtil.add(columnValue, portletId);
      }

      if (hasUserPreferences()) {
        setUserPreference(columnId, columnValue);
      } else {
        getTypeSettingsProperties().setProperty(columnId, columnValue);
      }
    }

    try {
      PortletLayoutListener portletLayoutListener = portlet.getPortletLayoutListenerInstance();

      if (_enablePortletLayoutListener && (portletLayoutListener != null)) {

        portletLayoutListener.onAddToLayout(portletId, layout.getPlid());
      }
    } catch (Exception e) {
      _log.error("Unable to fire portlet layout listener event", e);
    }

    return portletId;
  }
  private ActionResult _doProcessAction(
      HttpServletRequest request, HttpServletResponse response, Portlet portlet) throws Exception {

    HttpServletRequest ownerLayoutRequest = getOwnerLayoutRequestWrapper(request, portlet);

    Layout ownerLayout = (Layout) ownerLayoutRequest.getAttribute(WebKeys.LAYOUT);

    boolean allowAddPortletDefaultResource =
        PortalUtil.isAllowAddPortletDefaultResource(ownerLayoutRequest, portlet);

    if (!allowAddPortletDefaultResource) {
      String url = null;

      LastPath lastPath = (LastPath) request.getAttribute(WebKeys.LAST_PATH);

      if (lastPath != null) {
        StringBundler sb = new StringBundler(3);

        sb.append(PortalUtil.getPortalURL(request));
        sb.append(lastPath.getContextPath());
        sb.append(lastPath.getPath());

        url = sb.toString();
      } else {
        url = String.valueOf(request.getRequestURI());
      }

      _log.error("Reject processAction for " + url + " on " + portlet.getPortletId());

      return ActionResult.EMPTY_ACTION_RESULT;
    }

    Layout layout = (Layout) request.getAttribute(WebKeys.LAYOUT);

    WindowState windowState =
        WindowStateFactory.getWindowState(ParamUtil.getString(request, "p_p_state"));

    if (layout.isTypeControlPanel()
        && ((windowState == null)
            || windowState.equals(WindowState.NORMAL)
            || Validator.isNull(windowState.toString()))) {

      windowState = WindowState.MAXIMIZED;
    }

    PortletMode portletMode =
        PortletModeFactory.getPortletMode(ParamUtil.getString(request, "p_p_mode"));

    PortletPreferencesIds portletPreferencesIds =
        PortletPreferencesFactoryUtil.getPortletPreferencesIds(request, portlet.getPortletId());

    PortletPreferences portletPreferences =
        PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);

    ServletContext servletContext = (ServletContext) request.getAttribute(WebKeys.CTX);

    InvokerPortlet invokerPortlet = PortletInstanceFactoryUtil.create(portlet, servletContext);

    PortletConfig portletConfig = PortletConfigFactoryUtil.create(portlet, servletContext);
    PortletContext portletContext = portletConfig.getPortletContext();

    String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE);

    if (_log.isDebugEnabled()) {
      _log.debug("Content type " + contentType);
    }

    UploadServletRequest uploadServletRequest = null;

    try {
      if ((contentType != null) && contentType.startsWith(ContentTypes.MULTIPART_FORM_DATA)) {

        PortletConfigImpl invokerPortletConfigImpl =
            (PortletConfigImpl) invokerPortlet.getPortletConfig();

        if (invokerPortlet.isStrutsPortlet()
            || invokerPortletConfigImpl.isCopyRequestParameters()
            || !invokerPortletConfigImpl.isWARFile()) {

          uploadServletRequest = new UploadServletRequestImpl(request);

          request = uploadServletRequest;
        }
      }

      if (PropsValues.AUTH_TOKEN_CHECK_ENABLED && invokerPortlet.isCheckAuthToken()) {

        AuthTokenUtil.check(request);
      }

      ActionRequestImpl actionRequestImpl =
          ActionRequestFactory.create(
              request,
              portlet,
              invokerPortlet,
              portletContext,
              windowState,
              portletMode,
              portletPreferences,
              layout.getPlid());

      User user = PortalUtil.getUser(request);

      ActionResponseImpl actionResponseImpl =
          ActionResponseFactory.create(
              actionRequestImpl,
              response,
              portlet.getPortletId(),
              user,
              layout,
              windowState,
              portletMode);

      actionRequestImpl.defineObjects(portletConfig, actionResponseImpl);

      ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequestImpl);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);

      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

      long scopeGroupId = themeDisplay.getScopeGroupId();

      boolean access =
          PortletPermissionUtil.hasAccessPermission(
              permissionChecker, scopeGroupId, ownerLayout, portlet, portletMode);

      if (access) {
        invokerPortlet.processAction(actionRequestImpl, actionResponseImpl);

        actionResponseImpl.transferHeaders(response);
      }

      RenderParametersPool.put(
          request,
          layout.getPlid(),
          portlet.getPortletId(),
          actionResponseImpl.getRenderParameterMap());

      List<Event> events = actionResponseImpl.getEvents();

      String redirectLocation = actionResponseImpl.getRedirectLocation();

      if (Validator.isNull(redirectLocation) && portlet.isActionURLRedirect()) {

        PortletURL portletURL =
            new PortletURLImpl(
                actionRequestImpl,
                actionRequestImpl.getPortletName(),
                layout.getPlid(),
                PortletRequest.RENDER_PHASE);

        Map<String, String[]> renderParameters = actionResponseImpl.getRenderParameterMap();

        for (Map.Entry<String, String[]> entry : renderParameters.entrySet()) {

          String key = entry.getKey();
          String[] value = entry.getValue();

          portletURL.setParameter(key, value);
        }

        redirectLocation = portletURL.toString();
      }

      return new ActionResult(events, redirectLocation);
    } finally {
      if (uploadServletRequest != null) {
        uploadServletRequest.cleanUp();
      }

      ServiceContextThreadLocal.popServiceContext();
    }
  }
  public void removePortletId(long userId, String portletId, boolean cleanUp) {

    try {
      Portlet portlet = PortletLocalServiceUtil.getPortletById(getCompanyId(), portletId);

      if (portlet == null) {
        _log.error("Portlet " + portletId + " cannot be removed because it is not registered");

        return;
      }

      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      if (!LayoutPermissionUtil.contains(permissionChecker, getLayout(), ActionKeys.UPDATE)
          && !isCustomizable()) {

        return;
      }
    } catch (Exception e) {
      _log.error(e, e);
    }

    List<String> columns = getColumns();

    for (int i = 0; i < columns.size(); i++) {
      String columnId = columns.get(i);

      if (isCustomizable() && isColumnDisabled(columnId)) {
        continue;
      }

      String columnValue = StringPool.BLANK;

      if (hasUserPreferences()) {
        columnValue = getUserPreference(columnId);
      } else {
        columnValue = getTypeSettingsProperties().getProperty(columnId);
      }

      columnValue = StringUtil.remove(columnValue, portletId);

      if (hasUserPreferences()) {
        setUserPreference(columnId, columnValue);

        try {
          String rootPortletId = PortletConstants.getRootPortletId(portletId);

          ResourceLocalServiceUtil.deleteResource(
              getCompanyId(),
              rootPortletId,
              ResourceConstants.SCOPE_INDIVIDUAL,
              PortletPermissionUtil.getPrimaryKey(getPlid(), portletId));
        } catch (Exception e) {
        }
      } else {
        getTypeSettingsProperties().setProperty(columnId, columnValue);
      }
    }

    if (cleanUp) {
      removeStatesPortletId(portletId);
      removeModesPortletId(portletId);

      try {
        onRemoveFromLayout(portletId);
      } catch (Exception e) {
        _log.error("Unable to fire portlet layout listener event", e);
      }
    }
  }
  protected Query doGetPermissionQuery(
      long companyId,
      long[] groupIds,
      long userId,
      String className,
      Query query,
      SearchContext searchContext)
      throws Exception {

    Indexer indexer = IndexerRegistryUtil.getIndexer(className);

    if (!indexer.isPermissionAware()) {
      return query;
    }

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    AdvancedPermissionChecker advancedPermissionChecker = null;

    if ((permissionChecker != null) && (permissionChecker instanceof AdvancedPermissionChecker)) {

      advancedPermissionChecker = (AdvancedPermissionChecker) permissionChecker;
    }

    if (advancedPermissionChecker == null) {
      return query;
    }

    PermissionCheckerBag permissionCheckerBag =
        getPermissionCheckerBag(advancedPermissionChecker, userId);

    if (permissionCheckerBag == null) {
      return query;
    }

    List<Group> groups = new UniqueList<Group>();
    List<Role> roles = new UniqueList<Role>();
    List<UserGroupRole> userGroupRoles = new UniqueList<UserGroupRole>();
    Map<Long, List<Role>> groupIdsToRoles = new HashMap<Long, List<Role>>();

    roles.addAll(permissionCheckerBag.getRoles());

    if (ArrayUtil.isEmpty(groupIds)) {
      groups.addAll(GroupLocalServiceUtil.getUserGroups(userId, true));
      groups.addAll(permissionCheckerBag.getGroups());

      userGroupRoles = UserGroupRoleLocalServiceUtil.getUserGroupRoles(userId);
    } else {
      groups.addAll(permissionCheckerBag.getGroups());

      for (long groupId : groupIds) {
        if (GroupLocalServiceUtil.hasUserGroup(userId, groupId)) {
          Group group = GroupLocalServiceUtil.getGroup(groupId);

          groups.add(group);
        }

        userGroupRoles.addAll(UserGroupRoleLocalServiceUtil.getUserGroupRoles(userId, groupId));
        userGroupRoles.addAll(
            UserGroupRoleLocalServiceUtil.getUserGroupRolesByUserUserGroupAndGroup(
                userId, groupId));
      }
    }

    if (advancedPermissionChecker.isSignedIn()) {
      roles.add(RoleLocalServiceUtil.getRole(companyId, RoleConstants.GUEST));
    }

    for (Group group : groups) {
      PermissionCheckerBag userBag =
          advancedPermissionChecker.getUserBag(userId, group.getGroupId());

      List<Role> groupRoles = userBag.getRoles();

      groupIdsToRoles.put(group.getGroupId(), groupRoles);

      roles.addAll(groupRoles);
    }

    return doGetPermissionQuery_6(
        companyId,
        groupIds,
        userId,
        className,
        query,
        searchContext,
        advancedPermissionChecker,
        groups,
        roles,
        userGroupRoles,
        groupIdsToRoles);
  }
示例#28
0
  public String transform(
      ThemeDisplay themeDisplay,
      Map<String, String> tokens,
      String viewMode,
      String languageId,
      String xml,
      String script,
      String langType)
      throws Exception {

    // Setup listeners

    if (_log.isDebugEnabled()) {
      _log.debug("Language " + languageId);
    }

    if (Validator.isNull(viewMode)) {
      viewMode = Constants.VIEW;
    }

    if (_logTokens.isDebugEnabled()) {
      String tokensString = PropertiesUtil.list(tokens);

      _logTokens.debug(tokensString);
    }

    if (_logTransformBefore.isDebugEnabled()) {
      _logTransformBefore.debug(xml);
    }

    List<TransformerListener> transformerListeners = new ArrayList<TransformerListener>();

    for (String transformerListenersClassName : _transformerListenerClassNames) {

      TransformerListener transformerListener = null;

      try {
        if (_log.isDebugEnabled()) {
          _log.debug("Instantiate listener " + transformerListenersClassName);
        }

        ClassLoader classLoader = PortalClassLoaderUtil.getClassLoader();

        transformerListener =
            (TransformerListener)
                InstanceFactory.newInstance(classLoader, transformerListenersClassName);

        transformerListeners.add(transformerListener);
      } catch (Exception e) {
        _log.error(e, e);
      }

      // Modify XML

      if (_logXmlBeforeListener.isDebugEnabled()) {
        _logXmlBeforeListener.debug(xml);
      }

      if (transformerListener != null) {
        xml = transformerListener.onXml(xml, languageId, tokens);

        if (_logXmlAfterListener.isDebugEnabled()) {
          _logXmlAfterListener.debug(xml);
        }
      }

      // Modify script

      if (_logScriptBeforeListener.isDebugEnabled()) {
        _logScriptBeforeListener.debug(script);
      }

      if (transformerListener != null) {
        script = transformerListener.onScript(script, xml, languageId, tokens);

        if (_logScriptAfterListener.isDebugEnabled()) {
          _logScriptAfterListener.debug(script);
        }
      }
    }

    // Transform

    String output = null;

    if (Validator.isNull(langType)) {
      output = LocalizationUtil.getLocalization(xml, languageId);
    } else {
      long companyId = 0;
      long companyGroupId = 0;
      long articleGroupId = 0;

      if (tokens != null) {
        companyId = GetterUtil.getLong(tokens.get("company_id"));
        companyGroupId = GetterUtil.getLong(tokens.get("company_group_id"));
        articleGroupId = GetterUtil.getLong(tokens.get("article_group_id"));
      }

      long scopeGroupId = 0;
      long siteGroupId = 0;

      if (themeDisplay != null) {
        companyId = themeDisplay.getCompanyId();
        companyGroupId = themeDisplay.getCompanyGroupId();
        scopeGroupId = themeDisplay.getScopeGroupId();
        siteGroupId = themeDisplay.getSiteGroupId();
      }

      String templateId = tokens.get("template_id");

      templateId = getTemplateId(templateId, companyId, companyGroupId, articleGroupId);

      Template template = getTemplate(templateId, tokens, languageId, xml, script, langType);

      UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

      try {
        if (Validator.isNotNull(xml)) {
          Document document = SAXReaderUtil.read(xml);

          Element rootElement = document.getRootElement();

          List<TemplateNode> templateNodes = getTemplateNodes(themeDisplay, rootElement);

          if (templateNodes != null) {
            for (TemplateNode templateNode : templateNodes) {
              template.put(templateNode.getName(), templateNode);
            }
          }

          Element requestElement = rootElement.element("request");

          template.put("request", insertRequestVariables(requestElement));

          template.put("xmlRequest", requestElement.asXML());
        }

        template.put("articleGroupId", articleGroupId);
        template.put("company", getCompany(themeDisplay, companyId));
        template.put("companyId", companyId);
        template.put("device", getDevice(themeDisplay));

        String templatesPath = getTemplatesPath(companyId, articleGroupId);

        template.put("journalTemplatesPath", templatesPath);

        Locale locale = LocaleUtil.fromLanguageId(languageId);

        template.put("locale", locale);

        template.put("permissionChecker", PermissionThreadLocal.getPermissionChecker());
        template.put(
            "randomNamespace",
            PwdGenerator.getPassword(PwdGenerator.KEY3, 4) + StringPool.UNDERLINE);
        template.put("scopeGroupId", scopeGroupId);
        template.put("siteGroupId", siteGroupId);
        template.put("templatesPath", templatesPath);
        template.put("viewMode", viewMode);

        // Deprecated variables

        template.put("groupId", articleGroupId);

        mergeTemplate(template, unsyncStringWriter);
      } catch (Exception e) {
        if (e instanceof DocumentException) {
          throw new TransformException("Unable to read XML document", e);
        } else if (e instanceof IOException) {
          throw new TransformException("Error reading template", e);
        } else if (e instanceof TransformException) {
          throw (TransformException) e;
        } else {
          throw new TransformException("Unhandled exception", e);
        }
      }

      output = unsyncStringWriter.toString();
    }

    // Postprocess output

    for (TransformerListener transformerListener : transformerListeners) {

      // Modify output

      if (_logOutputBeforeListener.isDebugEnabled()) {
        _logOutputBeforeListener.debug(output);
      }

      output = transformerListener.onOutput(output, languageId, tokens);

      if (_logOutputAfterListener.isDebugEnabled()) {
        _logOutputAfterListener.debug(output);
      }
    }

    if (_logTransfromAfter.isDebugEnabled()) {
      _logTransfromAfter.debug(output);
    }

    return output;
  }
  private void _doServeResource(
      HttpServletRequest request, HttpServletResponse response, Portlet portlet) throws Exception {

    HttpServletRequest ownerLayoutRequest = getOwnerLayoutRequestWrapper(request, portlet);

    Layout ownerLayout = (Layout) ownerLayoutRequest.getAttribute(WebKeys.LAYOUT);

    boolean allowAddPortletDefaultResource =
        PortalUtil.isAllowAddPortletDefaultResource(ownerLayoutRequest, portlet);

    if (!allowAddPortletDefaultResource) {
      String url = null;

      LastPath lastPath = (LastPath) request.getAttribute(WebKeys.LAST_PATH);

      if (lastPath != null) {
        StringBundler sb = new StringBundler(3);

        sb.append(PortalUtil.getPortalURL(request));
        sb.append(lastPath.getContextPath());
        sb.append(lastPath.getPath());

        url = sb.toString();
      } else {
        url = String.valueOf(request.getRequestURI());
      }

      response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

      _log.error("Reject serveResource for " + url + " on " + portlet.getPortletId());

      return;
    }

    WindowState windowState = (WindowState) request.getAttribute(WebKeys.WINDOW_STATE);

    PortletMode portletMode =
        PortletModeFactory.getPortletMode(ParamUtil.getString(request, "p_p_mode"));

    PortletPreferencesIds portletPreferencesIds =
        PortletPreferencesFactoryUtil.getPortletPreferencesIds(request, portlet.getPortletId());

    PortletPreferences portletPreferences =
        PortletPreferencesLocalServiceUtil.getPreferences(portletPreferencesIds);

    ServletContext servletContext = (ServletContext) request.getAttribute(WebKeys.CTX);

    InvokerPortlet invokerPortlet = PortletInstanceFactoryUtil.create(portlet, servletContext);

    PortletConfig portletConfig = PortletConfigFactoryUtil.create(portlet, servletContext);
    PortletContext portletContext = portletConfig.getPortletContext();

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

    Layout layout = (Layout) request.getAttribute(WebKeys.LAYOUT);

    String portletPrimaryKey =
        PortletPermissionUtil.getPrimaryKey(layout.getPlid(), portlet.getPortletId());

    portletDisplay.setId(portlet.getPortletId());
    portletDisplay.setRootPortletId(portlet.getRootPortletId());
    portletDisplay.setInstanceId(portlet.getInstanceId());
    portletDisplay.setResourcePK(portletPrimaryKey);
    portletDisplay.setPortletName(portletConfig.getPortletName());
    portletDisplay.setNamespace(PortalUtil.getPortletNamespace(portlet.getPortletId()));

    WebDAVStorage webDAVStorage = portlet.getWebDAVStorageInstance();

    if (webDAVStorage != null) {
      portletDisplay.setWebDAVEnabled(true);
    } else {
      portletDisplay.setWebDAVEnabled(false);
    }

    ResourceRequestImpl resourceRequestImpl =
        ResourceRequestFactory.create(
            request,
            portlet,
            invokerPortlet,
            portletContext,
            windowState,
            portletMode,
            portletPreferences,
            layout.getPlid());

    long companyId = PortalUtil.getCompanyId(request);

    ResourceResponseImpl resourceResponseImpl =
        ResourceResponseFactory.create(
            resourceRequestImpl, response, portlet.getPortletId(), companyId);

    resourceRequestImpl.defineObjects(portletConfig, resourceResponseImpl);

    try {
      ServiceContext serviceContext = ServiceContextFactory.getInstance(resourceRequestImpl);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);

      PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

      long scopeGroupId = themeDisplay.getScopeGroupId();

      boolean access =
          PortletPermissionUtil.hasAccessPermission(
              permissionChecker, scopeGroupId, ownerLayout, portlet, portletMode);

      if (access) {
        invokerPortlet.serveResource(resourceRequestImpl, resourceResponseImpl);

        resourceResponseImpl.transferHeaders(response);
      }
    } finally {
      ServiceContextThreadLocal.popServiceContext();
    }
  }
  @Override
  protected void dispatch(final Set<MessageListener> messageListeners, final Message message) {

    if (!message.contains("companyId")) {
      message.put("companyId", CompanyThreadLocal.getCompanyId());
    }

    if (!message.contains("permissionChecker")) {
      message.put("permissionChecker", PermissionThreadLocal.getPermissionChecker());
    }

    if (!message.contains("principalName")) {
      message.put("principalName", PrincipalThreadLocal.getName());
    }

    if (!message.contains("principalPassword")) {
      message.put("principalPassword", PrincipalThreadLocal.getPassword());
    }

    ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();

    Runnable runnable =
        new MessageRunnable(message) {

          public void run() {
            try {
              long messageCompanyId = message.getLong("companyId");

              if (messageCompanyId > 0) {
                CompanyThreadLocal.setCompanyId(messageCompanyId);
              }

              PermissionChecker permissionChecker =
                  (PermissionChecker) message.get("permissionChecker");

              if (permissionChecker != null) {
                PermissionThreadLocal.setPermissionChecker(permissionChecker);
              }

              String messagePrincipalName = message.getString("principalName");

              if (Validator.isNotNull(messagePrincipalName)) {
                PrincipalThreadLocal.setName(messagePrincipalName);
              }

              String messagePrincipalPassword = message.getString("principalPassword");

              if (Validator.isNotNull(messagePrincipalPassword)) {
                PrincipalThreadLocal.setPassword(messagePrincipalPassword);
              }

              Boolean clusterForwardMessage =
                  (Boolean) message.get(ClusterLinkUtil.CLUSTER_FORWARD_MESSAGE);

              if (clusterForwardMessage != null) {
                MessageValuesThreadLocal.setValue(
                    ClusterLinkUtil.CLUSTER_FORWARD_MESSAGE, clusterForwardMessage);
              }

              for (MessageListener messageListener : messageListeners) {
                try {
                  messageListener.receive(message);
                } catch (MessageListenerException mle) {
                  _log.error("Unable to process message " + message, mle);
                }
              }
            } finally {
              ThreadLocalCacheManager.clearAll(Lifecycle.REQUEST);

              CentralizedThreadLocal.clearShortLivedThreadLocals();
            }
          }
        };

    threadPoolExecutor.execute(runnable);
  }