@Override
  protected Map<String, List<StagedModel>> addDependentStagedModelsMap(Group group)
      throws Exception {

    Map<String, List<StagedModel>> dependentStagedModelsMap = new LinkedHashMap<>();

    DDMStructure ddmStructure =
        DDMStructureTestUtil.addStructure(group.getGroupId(), DDLRecordSet.class.getName());

    DDMTemplate ddmTemplate1 =
        DDMTemplateTestUtil.addTemplate(
            group.getGroupId(),
            ddmStructure.getStructureId(),
            PortalUtil.getClassNameId(DDLRecordSet.class));

    addDependentStagedModel(dependentStagedModelsMap, DDMTemplate.class, ddmTemplate1);

    DDMTemplate ddmTemplate2 =
        DDMTemplateTestUtil.addTemplate(
            group.getGroupId(),
            ddmStructure.getStructureId(),
            PortalUtil.getClassNameId(DDLRecordSet.class));

    addDependentStagedModel(dependentStagedModelsMap, DDMTemplate.class, ddmTemplate2);

    addDependentStagedModel(dependentStagedModelsMap, DDMStructure.class, ddmStructure);

    return dependentStagedModelsMap;
  }
  @Reference(target = ModuleServiceLifecycle.PORTAL_INITIALIZED, unbind = "-")
  protected void setModuleServiceLifecycle(ModuleServiceLifecycle moduleServiceLifecycle) {

    _classNameIds =
        new long[] {
          PortalUtil.getClassNameId(Company.class),
          PortalUtil.getClassNameId(Group.class),
          PortalUtil.getClassNameId(Organization.class)
        };
  }
  protected void addDDMStructureAttributes(Document document, JournalArticle article)
      throws Exception {

    DDMStructure ddmStructure =
        _ddmStructureLocalService.fetchStructure(
            article.getGroupId(),
            PortalUtil.getClassNameId(JournalArticle.class),
            article.getDDMStructureKey(),
            true);

    if (ddmStructure == null) {
      return;
    }

    document.addKeyword(Field.CLASS_TYPE_ID, ddmStructure.getStructureId());

    DDMFormValues ddmFormValues = null;

    try {
      Fields fields = _journalConverter.getDDMFields(ddmStructure, article.getDocument());

      ddmFormValues = _fieldsToDDMFormValuesConverter.convert(ddmStructure, fields);
    } catch (Exception e) {
      return;
    }

    if (ddmFormValues != null) {
      _ddmIndexer.addAttributes(document, ddmStructure, ddmFormValues);
    }
  }
  protected void addDDMTemplateLinks() throws Exception {
    try (LoggingTimer loggingTimer = new LoggingTimer()) {
      long classNameId = PortalUtil.getClassNameId(DDMStructure.class.getName());

      StringBundler sb = new StringBundler(6);

      sb.append("select DDMTemplate.templateId, JournalArticle.id_ ");
      sb.append("from JournalArticle inner join DDMTemplate on (");
      sb.append("DDMTemplate.groupId = JournalArticle.groupId and ");
      sb.append("DDMTemplate.templateKey = ");
      sb.append("JournalArticle.DDMTemplateKey and ");
      sb.append("JournalArticle.classNameId != ?)");

      try (PreparedStatement ps = connection.prepareStatement(sb.toString())) {

        ps.setLong(1, classNameId);

        try (ResultSet rs = ps.executeQuery()) {
          while (rs.next()) {
            long templateId = rs.getLong("templateId");
            long id = rs.getLong("id_");

            _ddmTemplateLinkLocalService.addTemplateLink(classNameId, id, templateId);
          }
        }
      }
    }
  }
  @Override
  public AssetEntry getAssetEntry(String className, long classPK) throws PortalException {

    LayoutRevision layoutRevision = _layoutRevisionLocalService.getLayoutRevision(classPK);

    LayoutSetBranch layoutSetBranch =
        _layoutSetBranchLocalService.getLayoutSetBranch(layoutRevision.getLayoutSetBranchId());

    User user = _userLocalService.getUserById(layoutRevision.getUserId());

    AssetEntry assetEntry = _assetEntryLocalService.createAssetEntry(classPK);

    assetEntry.setGroupId(layoutRevision.getGroupId());
    assetEntry.setCompanyId(user.getCompanyId());
    assetEntry.setUserId(user.getUserId());
    assetEntry.setUserName(user.getFullName());
    assetEntry.setCreateDate(layoutRevision.getCreateDate());
    assetEntry.setClassNameId(PortalUtil.getClassNameId(LayoutRevision.class.getName()));
    assetEntry.setClassPK(layoutRevision.getLayoutRevisionId());

    StringBundler sb = new StringBundler(4);

    sb.append(layoutRevision.getHTMLTitle(LocaleUtil.getSiteDefault()));
    sb.append(" [");
    sb.append(layoutSetBranch.getName());
    sb.append("]");

    assetEntry.setTitle(sb.toString());

    return assetEntry;
  }
  protected String addBasicWebContentStructureAndTemplate(long companyId) throws Exception {

    initJournalDDMCompositeModelsResourceActions();

    Group group = _groupLocalService.getCompanyGroup(companyId);

    long defaultUserId = _userLocalService.getDefaultUserId(companyId);

    Class<?> clazz = getClass();

    _defaultDDMStructureHelper.addDDMStructures(
        defaultUserId,
        group.getGroupId(),
        PortalUtil.getClassNameId(JournalArticle.class),
        clazz.getClassLoader(),
        "com/liferay/journal/internal/upgrade/v1_0_0/dependencies"
            + "/basic-web-content-structure.xml",
        new ServiceContext());

    String defaultLanguageId = UpgradeProcessUtil.getDefaultLanguageId(companyId);

    Locale defaultLocale = LocaleUtil.fromLanguageId(defaultLanguageId);

    List<Element> structureElements = getDDMStructures(defaultLocale);

    Element structureElement = structureElements.get(0);

    return StringUtil.toUpperCase(structureElement.elementText("name"));
  }
  protected String extractDDMContent(JournalArticle article, String languageId) throws Exception {

    DDMStructure ddmStructure =
        _ddmStructureLocalService.fetchStructure(
            article.getGroupId(),
            PortalUtil.getClassNameId(JournalArticle.class),
            article.getDDMStructureKey(),
            true);

    if (ddmStructure == null) {
      return StringPool.BLANK;
    }

    DDMFormValues ddmFormValues = null;

    try {
      Fields fields = _journalConverter.getDDMFields(ddmStructure, article.getDocument());

      ddmFormValues = _fieldsToDDMFormValuesConverter.convert(ddmStructure, fields);
    } catch (Exception e) {
      return StringPool.BLANK;
    }

    if (ddmFormValues == null) {
      return StringPool.BLANK;
    }

    return _ddmIndexer.extractIndexableAttributes(
        ddmStructure, ddmFormValues, LocaleUtil.fromLanguageId(languageId));
  }
  @BeforeClass
  public static void setUpClass() throws Exception {
    _user = UserTestUtil.addUser();

    long classNameId = PortalUtil.getClassNameId(LiferayRepository.class.getName());

    _group = GroupTestUtil.addGroup();

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

    _repository =
        RepositoryLocalServiceUtil.addRepository(
            TestPropsValues.getUserId(),
            _group.getGroupId(),
            classNameId,
            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
            "Repository A",
            StringPool.BLANK,
            "Test Portlet",
            new UnicodeProperties(),
            true,
            serviceContext);

    Object[] objects = setUp(_group.getGroupId(), StringPool.BLANK, serviceContext);

    _defaultRepositoryFolder = (Folder) objects[0];
    _defaultRepositoryDLFileVersion = (DLFileVersion) objects[1];

    objects = setUp(_repository.getRepositoryId(), "-NewRepository", serviceContext);

    _newRepositoryFolder = (Folder) objects[0];
  }
  protected void upgradeMicroblogActivities() throws Exception {
    try (LoggingTimer loggingTimer = new LoggingTimer();
        PreparedStatement ps =
            connection.prepareStatement(
                "select activityId, extraData from SocialActivity where " + "classNameId = ?")) {

      ps.setLong(1, PortalUtil.getClassNameId(MicroblogsEntry.class));

      try (ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
          long activityId = rs.getLong("activityId");
          String extraData = rs.getString("extraData");

          JSONObject extraDataJSONObject = JSONFactoryUtil.createJSONObject(extraData);

          long parentMicroblogsEntryId = extraDataJSONObject.getLong("receiverMicroblogsEntryId");

          extraDataJSONObject.put("parentMicroblogsEntryId", parentMicroblogsEntryId);

          extraDataJSONObject.remove("receiverMicroblogsEntryId");

          updateSocialActivity(activityId, extraDataJSONObject);
        }
      }
    }
  }
  protected AssetVocabulary addAssetVocabulary(
      long groupId,
      long companyId,
      String title,
      Map<Locale, String> nameMap,
      Map<Locale, String> descriptionMap)
      throws Exception {

    long userId = _userLocalService.getDefaultUserId(companyId);

    AssetVocabularySettingsHelper assetVocabularySettingsHelper =
        new AssetVocabularySettingsHelper();

    assetVocabularySettingsHelper.setClassNameIdsAndClassTypePKs(
        new long[] {PortalUtil.getClassNameId(JournalArticle.class.getName())},
        new long[] {-1},
        new boolean[] {false});
    assetVocabularySettingsHelper.setMultiValued(false);

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);

    return _assetVocabularyLocalService.addVocabulary(
        userId,
        groupId,
        title,
        nameMap,
        descriptionMap,
        assetVocabularySettingsHelper.toString(),
        serviceContext);
  }
  public void setClassName(String className) {
    long classNameId = PortalUtil.getClassNameId(className);

    _classNameIds = new long[] {classNameId};

    _toString = null;
  }
  protected void updateParentGroupId() throws Exception {
    try (LoggingTimer loggingTimer = new LoggingTimer()) {
      long classNameId = PortalUtil.getClassNameId("com.liferay.portal.model.Layout");

      try (PreparedStatement ps =
              connection.prepareStatement(
                  "select groupId, classPK from Group_ where classNameId = " + classNameId);
          ResultSet rs = ps.executeQuery()) {

        while (rs.next()) {
          long groupId = rs.getLong("groupId");
          long classPK = rs.getLong("classPK");

          Object[] layout = getLayout(classPK);

          if (layout != null) {
            long layoutGroupId = (Long) layout[0];

            runSQL(
                "update Group_ set parentGroupId = "
                    + layoutGroupId
                    + " where groupId = "
                    + groupId);
          }
        }
      }
    }
  }
  @BeforeClass
  public static void setUpClass() throws Exception {
    userClassNameId = PortalUtil.getClassNameId(User.class.getName());

    Class<?> clazz = SocialActivitySettingLocalServiceTest.class;

    String xml = new String(FileUtil.getBytes(clazz, "dependencies/liferay-social.xml"));

    SocialConfigurationUtil.read(clazz.getClassLoader(), new String[] {xml});
  }
  protected void addDDMStorageLink(Map<Long, List<Long>> ddmStructureIdsMap) throws Exception {

    long journalArticleClassNameId = PortalUtil.getClassNameId(JournalArticle.class.getName());

    for (Map.Entry<Long, List<Long>> entry : ddmStructureIdsMap.entrySet()) {

      long ddmStructureId = getDDMStructureId(entry.getKey(), entry.getValue());

      _ddmStorageLinkLocalService.addStorageLink(
          journalArticleClassNameId, entry.getKey(), ddmStructureId, new ServiceContext());
    }
  }
  @Override
  public ExportActionableDynamicQuery getExportActionableDynamicQuery(
      final PortletDataContext portletDataContext) {
    final ExportActionableDynamicQuery exportActionableDynamicQuery =
        new ExportActionableDynamicQuery() {
          @Override
          public long performCount() throws PortalException {
            ManifestSummary manifestSummary = portletDataContext.getManifestSummary();

            StagedModelType stagedModelType = getStagedModelType();

            long modelAdditionCount = super.performCount();

            manifestSummary.addModelAdditionCount(stagedModelType, modelAdditionCount);

            long modelDeletionCount =
                ExportImportHelperUtil.getModelDeletionCount(portletDataContext, stagedModelType);

            manifestSummary.addModelDeletionCount(stagedModelType, modelDeletionCount);

            return modelAdditionCount;
          }
        };

    initActionableDynamicQuery(exportActionableDynamicQuery);

    exportActionableDynamicQuery.setAddCriteriaMethod(
        new ActionableDynamicQuery.AddCriteriaMethod() {
          @Override
          public void addCriteria(DynamicQuery dynamicQuery) {
            portletDataContext.addDateRangeCriteria(dynamicQuery, "modifiedDate");
          }
        });

    exportActionableDynamicQuery.setCompanyId(portletDataContext.getCompanyId());

    exportActionableDynamicQuery.setGroupId(portletDataContext.getScopeGroupId());

    exportActionableDynamicQuery.setPerformActionMethod(
        new ActionableDynamicQuery.PerformActionMethod<Calendar>() {
          @Override
          public void performAction(Calendar calendar) throws PortalException {
            StagedModelDataHandlerUtil.exportStagedModel(portletDataContext, calendar);
          }
        });
    exportActionableDynamicQuery.setStagedModelType(
        new StagedModelType(PortalUtil.getClassNameId(Calendar.class.getName())));

    return exportActionableDynamicQuery;
  }
  protected KBFolder addKBFolder(long parentResourcePrimKey)
      throws com.liferay.portal.kernel.exception.PortalException {

    ServiceContext serviceContext =
        ServiceContextTestUtil.getServiceContext(_group, _user.getUserId());

    return KBFolderLocalServiceUtil.addKBFolder(
        _user.getUserId(),
        _group.getGroupId(),
        PortalUtil.getClassNameId(KBFolderConstants.getClassName()),
        parentResourcePrimKey,
        RandomTestUtil.randomString(),
        RandomTestUtil.randomString(),
        serviceContext);
  }
  @Override
  protected void doReindex(JournalArticle article) throws Exception {
    if (PortalUtil.getClassNameId(DDMStructure.class) == article.getClassNameId()) {

      Document document = getDocument(article);

      IndexWriterHelperUtil.deleteDocument(
          getSearchEngineId(), article.getCompanyId(),
          document.get(Field.UID), isCommitImmediately());

      return;
    }

    reindexArticleVersions(article);
  }
  protected long getCompanyGroupId(long companyId) throws Exception {
    try (PreparedStatement ps =
        connection.prepareStatement(
            "select groupId from Group_ where classNameId = ? and " + "classPK = ?")) {

      ps.setLong(1, PortalUtil.getClassNameId("com.liferay.portal.model.Company"));
      ps.setLong(2, companyId);

      try (ResultSet rs = ps.executeQuery()) {
        if (rs.next()) {
          return rs.getLong("groupId");
        }

        return 0;
      }
    }
  }
  @Override
  public int processEndTag() throws Exception {
    DDMTemplate portletDisplayDDMTemplate =
        PortletDisplayTemplateManagerUtil.getDDMTemplate(
            getDisplayStyleGroupId(),
            PortalUtil.getClassNameId(NavItem.class),
            getDisplayStyle(),
            true);

    if (portletDisplayDDMTemplate == null) {
      return EVAL_PAGE;
    }

    List<NavItem> branchNavItems = null;
    List<NavItem> navItems = null;

    try {
      branchNavItems = getBranchNavItems(request);

      navItems = getNavItems(branchNavItems);
    } catch (Exception e) {
      _log.error(e, e);
    }

    HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();

    Map<String, Object> contextObjects = new HashMap<>();

    contextObjects.put("branchNavItems", branchNavItems);
    contextObjects.put("displayDepth", _displayDepth);
    contextObjects.put("includedLayouts", _includedLayouts);
    contextObjects.put("preview", _preview);
    contextObjects.put("rootLayoutLevel", _rootLayoutLevel);
    contextObjects.put("rootLayoutType", _rootLayoutType);

    String result =
        PortletDisplayTemplateManagerUtil.renderDDMTemplate(
            request, response, portletDisplayDDMTemplate.getTemplateId(), navItems, contextObjects);

    JspWriter jspWriter = pageContext.getOut();

    jspWriter.write(result);

    return EVAL_PAGE;
  }
  protected KBArticle addKBArticle(long parentKbFolderId, String title) throws Exception {

    ServiceContext serviceContext =
        ServiceContextTestUtil.getServiceContext(_group, _user.getUserId());

    return KBArticleLocalServiceUtil.addKBArticle(
        _user.getUserId(),
        PortalUtil.getClassNameId(KBFolderConstants.getClassName()),
        parentKbFolderId,
        title,
        title,
        RandomTestUtil.randomString(),
        RandomTestUtil.randomString(),
        null,
        new String[0],
        new String[0],
        serviceContext);
  }
  protected KBArticle addChildKBArticle(KBArticle kbArticle, String title) throws Exception {

    ServiceContext serviceContext =
        ServiceContextTestUtil.getServiceContext(_group, _user.getUserId());

    return KBArticleLocalServiceUtil.addKBArticle(
        _user.getUserId(),
        PortalUtil.getClassNameId(KBArticleConstants.getClassName()),
        kbArticle.getResourcePrimKey(),
        title,
        title,
        RandomTestUtil.randomString(),
        RandomTestUtil.randomString(),
        null,
        new String[0],
        new String[0],
        serviceContext);
  }
  protected void addDDMStructure(
      String uuid_,
      long ddmStructureId,
      long groupId,
      long companyId,
      long userId,
      String userName,
      Timestamp createDate,
      Timestamp modifiedDate,
      String parentStructureId,
      String ddmStructureKey,
      String name,
      String description,
      String xsd)
      throws Exception {

    long parentDDMStructureId = 0;

    if (Validator.isNotNull(parentStructureId)) {
      parentDDMStructureId = updateStructure(parentStructureId);
    }

    long insertedDDMStructureId = getDDMStructureId(groupId, ddmStructureKey, false);

    if (insertedDDMStructureId == 0) {
      addDDMStructure(
          uuid_,
          ddmStructureId,
          groupId,
          companyId,
          userId,
          userName,
          createDate,
          modifiedDate,
          parentDDMStructureId,
          PortalUtil.getClassNameId("com.liferay.portlet.journal.model.JournalArticle"),
          ddmStructureKey,
          name,
          description,
          xsd,
          "xml",
          _DDM_STRUCTURE_TYPE_DEFAULT);
    }
  }
  @Override
  protected void addDDLDisplayTemplates(String ddmStructureKey, String dirName, String fileName)
      throws Exception {

    DDMStructure ddmStructure =
        ddmStructureLocalService.getStructure(
            groupId, PortalUtil.getClassNameId(DDLRecordSet.class), ddmStructureKey);

    StringBundler sb = new StringBundler(4);

    sb.append(resourcesDir);
    sb.append(dirName);
    sb.append(StringPool.SLASH);
    sb.append(fileName);

    Set<String> resourcePaths = servletContext.getResourcePaths(sb.toString());

    if (resourcePaths == null) {
      return;
    }

    for (String resourcePath : resourcePaths) {
      URL url = servletContext.getResource(resourcePath);

      URLConnection urlConnection = url.openConnection();

      String script = StringUtil.read(urlConnection.getInputStream());

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

      addDDMTemplate(
          groupId,
          ddmStructure.getStructureId(),
          resourcePath,
          getDDMTemplateLanguage(resourcePath),
          script,
          DDMTemplateConstants.TEMPLATE_TYPE_DISPLAY,
          StringPool.BLANK);
    }
  }
  protected void addDDMStorageLinks() throws Exception {
    try (LoggingTimer loggingTimer = new LoggingTimer()) {
      StringBundler sb = new StringBundler(8);

      sb.append("select DDMStructure.structureId, JournalArticle.id_ ");
      sb.append("from JournalArticle inner join DDMStructure on (");
      sb.append("DDMStructure.groupId in (select distinct Group_.");
      sb.append("groupId from Group_ where (Group_.groupId = ");
      sb.append("JournalArticle.groupId) or (Group_.companyId = ");
      sb.append("JournalArticle.companyId and Group_.friendlyURL = ?)) ");
      sb.append("and DDMStructure.structureKey = JournalArticle.");
      sb.append("DDMStructureKey and JournalArticle.classNameId != ?)");

      try (PreparedStatement ps = connection.prepareStatement(sb.toString())) {

        ps.setString(1, GroupConstants.GLOBAL_FRIENDLY_URL);
        ps.setLong(2, PortalUtil.getClassNameId(DDMStructure.class.getName()));

        try (ResultSet rs = ps.executeQuery()) {
          Map<Long, List<Long>> ddmStructureIdsMap = new HashMap<>();

          while (rs.next()) {
            long structureId = rs.getLong("structureId");
            long id = rs.getLong("id_");

            List<Long> ddmStructureIds = ddmStructureIdsMap.get(id);

            if (ddmStructureIds == null) {
              ddmStructureIds = new ArrayList<>();
            }

            ddmStructureIds.add(structureId);

            ddmStructureIdsMap.put(id, ddmStructureIds);
          }

          addDDMStorageLink(ddmStructureIdsMap);
        }
      }
    }
  }
  @Override
  protected BaseModel<?> addBaseModelWithDDMStructure(
      BaseModel<?> parentBaseModel, String keywords, ServiceContext serviceContext)
      throws Exception {

    String content = DDMStructureTestUtil.getSampleStructuredContent(keywords);

    DDMForm ddmForm = DDMStructureTestUtil.getSampleDDMForm("name");

    DDMStructure ddmStructure =
        DDMStructureTestUtil.addStructure(
            serviceContext.getScopeGroupId(), JournalArticle.class.getName(), ddmForm);

    DDMTemplate ddmTemplate =
        DDMTemplateTestUtil.addTemplate(
            serviceContext.getScopeGroupId(),
            ddmStructure.getStructureId(),
            PortalUtil.getClassNameId(JournalArticle.class));

    return addArticleWithXmlContent(
        parentBaseModel, content, ddmStructure, ddmTemplate, serviceContext);
  }
  protected void updateAssetEntryClassTypeId() throws Exception {
    try (LoggingTimer loggingTimer = new LoggingTimer();
        PreparedStatement ps1 =
            connection.prepareStatement(
                "select companyId, groupId, resourcePrimKey, structureId "
                    + "from JournalArticle where structureId != ''");
        ResultSet rs = ps1.executeQuery()) {

      long classNameId =
          PortalUtil.getClassNameId("com.liferay.portlet.journal.model.JournalArticle");

      try (PreparedStatement ps2 =
          AutoBatchPreparedStatementUtil.concurrentAutoBatch(
              connection,
              "update AssetEntry set classTypeId = ? where " + "classNameId = ? AND classPK = ?")) {

        while (rs.next()) {
          long groupId = rs.getLong("groupId");
          long companyId = rs.getLong("companyId");
          long resourcePrimKey = rs.getLong("resourcePrimKey");
          String structureId = rs.getString("structureId");

          long ddmStructureId =
              getDDMStructureId(groupId, getCompanyGroupId(companyId), structureId);

          ps2.setLong(1, ddmStructureId);
          ps2.setLong(2, classNameId);
          ps2.setLong(3, resourcePrimKey);

          ps2.addBatch();
        }

        ps2.executeBatch();
      }
    }
  }
  @Override
  public ExportActionableDynamicQuery getExportActionableDynamicQuery(
      final PortletDataContext portletDataContext) {
    final ExportActionableDynamicQuery exportActionableDynamicQuery =
        new ExportActionableDynamicQuery() {
          @Override
          public long performCount() throws PortalException {
            ManifestSummary manifestSummary = portletDataContext.getManifestSummary();

            StagedModelType stagedModelType = getStagedModelType();

            long modelAdditionCount = super.performCount();

            manifestSummary.addModelAdditionCount(stagedModelType, modelAdditionCount);

            long modelDeletionCount =
                ExportImportHelperUtil.getModelDeletionCount(portletDataContext, stagedModelType);

            manifestSummary.addModelDeletionCount(stagedModelType, modelDeletionCount);

            return modelAdditionCount;
          }
        };

    initActionableDynamicQuery(exportActionableDynamicQuery);

    exportActionableDynamicQuery.setAddCriteriaMethod(
        new ActionableDynamicQuery.AddCriteriaMethod() {
          @Override
          public void addCriteria(DynamicQuery dynamicQuery) {
            portletDataContext.addDateRangeCriteria(dynamicQuery, "modifiedDate");

            StagedModelType stagedModelType = exportActionableDynamicQuery.getStagedModelType();

            long referrerClassNameId = stagedModelType.getReferrerClassNameId();

            Property classNameIdProperty = PropertyFactoryUtil.forName("classNameId");

            if ((referrerClassNameId != StagedModelType.REFERRER_CLASS_NAME_ID_ALL)
                && (referrerClassNameId != StagedModelType.REFERRER_CLASS_NAME_ID_ANY)) {
              dynamicQuery.add(classNameIdProperty.eq(stagedModelType.getReferrerClassNameId()));
            } else if (referrerClassNameId == StagedModelType.REFERRER_CLASS_NAME_ID_ANY) {
              dynamicQuery.add(classNameIdProperty.isNotNull());
            }
          }
        });

    exportActionableDynamicQuery.setCompanyId(portletDataContext.getCompanyId());

    exportActionableDynamicQuery.setGroupId(portletDataContext.getScopeGroupId());

    exportActionableDynamicQuery.setPerformActionMethod(
        new ActionableDynamicQuery.PerformActionMethod<MBDiscussion>() {
          @Override
          public void performAction(MBDiscussion mbDiscussion) throws PortalException {
            StagedModelDataHandlerUtil.exportStagedModel(portletDataContext, mbDiscussion);
          }
        });
    exportActionableDynamicQuery.setStagedModelType(
        new StagedModelType(
            PortalUtil.getClassNameId(MBDiscussion.class.getName()),
            StagedModelType.REFERRER_CLASS_NAME_ID_ALL));

    return exportActionableDynamicQuery;
  }
/** @author Jürgen Kappler */
public class SiteBrowserDisplayContext {

  public SiteBrowserDisplayContext(
      HttpServletRequest request,
      LiferayPortletRequest liferayPortletRequest,
      LiferayPortletResponse liferayPortletResponse) {

    _request = request;
    _liferayPortletRequest = liferayPortletRequest;
    _liferayPortletResponse = liferayPortletResponse;
  }

  public String getDisplayStyle() {
    if (Validator.isNotNull(_displayStyle)) {
      return _displayStyle;
    }

    PortalPreferences portalPreferences =
        PortletPreferencesFactoryUtil.getPortalPreferences(_request);

    _displayStyle =
        portalPreferences.getValue(SiteBrowserPortletKeys.SITE_BROWSER, "display-style", "list");

    return _displayStyle;
  }

  public String getFilter() {
    if (_filter != null) {
      return _filter;
    }

    _filter = ParamUtil.getString(_request, "filter");

    return _filter;
  }

  public long getGroupId() {
    if (_groupId != null) {
      return _groupId;
    }

    _groupId = ParamUtil.getLong(_request, "groupId");

    return _groupId;
  }

  public LinkedHashMap<String, Object> getGroupParams() throws PortalException {

    if (_groupParams != null) {
      return _groupParams;
    }

    long groupId = ParamUtil.getLong(_request, "groupId");
    boolean includeCurrentGroup = ParamUtil.getBoolean(_request, "includeCurrentGroup", true);

    String type = getType();

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

    PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();
    User user = themeDisplay.getUser();

    boolean filterManageableGroups = true;

    if (permissionChecker.isCompanyAdmin()) {
      filterManageableGroups = false;
    }

    _groupParams = new LinkedHashMap<>();

    _groupParams.put("active", Boolean.TRUE);

    if (isManualMembership()) {
      _groupParams.put("manualMembership", Boolean.TRUE);
    }

    if (type.equals("child-sites")) {
      Group parentGroup = GroupLocalServiceUtil.getGroup(groupId);

      List<Group> parentGroups = new ArrayList<>();

      parentGroups.add(parentGroup);

      _groupParams.put("groupsTree", parentGroups);
    } else if (filterManageableGroups) {
      _groupParams.put("usersGroups", user.getUserId());
    }

    _groupParams.put("site", Boolean.TRUE);

    if (!includeCurrentGroup && (groupId > 0)) {
      List<Long> excludedGroupIds = new ArrayList<>();

      Group group = GroupLocalServiceUtil.getGroup(groupId);

      if (group.isStagingGroup()) {
        excludedGroupIds.add(group.getLiveGroupId());
      } else {
        excludedGroupIds.add(groupId);
      }

      _groupParams.put("excludedGroupIds", excludedGroupIds);
    }

    return _groupParams;
  }

  public GroupSearch getGroupSearch() throws Exception {
    ThemeDisplay themeDisplay = (ThemeDisplay) _request.getAttribute(WebKeys.THEME_DISPLAY);

    Company company = themeDisplay.getCompany();

    GroupSearch groupSearch = new GroupSearch(_liferayPortletRequest, getPortletURL());

    GroupSearchTerms groupSearchTerms = (GroupSearchTerms) groupSearch.getSearchTerms();

    List<Group> results = new ArrayList<>();

    int additionalSites = 0;
    int total = 0;

    boolean includeCompany = ParamUtil.getBoolean(_request, "includeCompany");
    boolean includeUserPersonalSite = ParamUtil.getBoolean(_request, "includeUserPersonalSite");

    long[] classNameIds = _CLASS_NAME_IDS;

    if (includeCompany) {
      classNameIds = ArrayUtil.append(classNameIds, PortalUtil.getClassNameId(Company.class));
    }

    if (includeUserPersonalSite) {
      if (groupSearch.getStart() == 0) {
        Group userPersonalSite =
            GroupLocalServiceUtil.getGroup(
                company.getCompanyId(), GroupConstants.USER_PERSONAL_SITE);

        results.add(userPersonalSite);
      }

      additionalSites++;
    }

    String type = getType();

    if (type.equals("layoutScopes")) {
      total =
          GroupLocalServiceUtil.getGroupsCount(
              themeDisplay.getCompanyId(), Layout.class.getName(), getGroupId());
    } else if (type.equals("parent-sites")) {
    } else {
      total =
          GroupLocalServiceUtil.searchCount(
              themeDisplay.getCompanyId(),
              classNameIds,
              groupSearchTerms.getKeywords(),
              getGroupParams());
    }

    total += additionalSites;

    groupSearch.setTotal(total);

    int start = groupSearch.getStart();

    if (groupSearch.getStart() > additionalSites) {
      start = groupSearch.getStart() - additionalSites;
    }

    int end = groupSearch.getEnd() - additionalSites;

    List<Group> groups = null;

    if (type.equals("layoutScopes")) {
      groups =
          GroupLocalServiceUtil.getGroups(
              company.getCompanyId(), Layout.class.getName(), getGroupId(), start, end);

      groups = _filterLayoutGroups(groups, isPrivateLayout());
    } else if (type.equals("parent-sites")) {
      Group group = GroupLocalServiceUtil.getGroup(getGroupId());

      groups = group.getAncestors();

      String filter = getFilter();

      if (Validator.isNotNull(filter)) {
        groups = _filterGroups(groups, filter);
      }

      total = groups.size();

      total += additionalSites;

      groupSearch.setTotal(total);
    } else {
      groups =
          GroupLocalServiceUtil.search(
              company.getCompanyId(),
              classNameIds,
              groupSearchTerms.getKeywords(),
              getGroupParams(),
              start,
              end,
              groupSearch.getOrderByComparator());
    }

    results.addAll(groups);

    groupSearch.setResults(results);

    return groupSearch;
  }

  public PortletURL getPortletURL() throws PortalException {
    PortletURL portletURL = _liferayPortletResponse.createRenderURL();

    User selUser = PortalUtil.getSelectedUser(_request);

    if (selUser != null) {
      portletURL.setParameter("p_u_i_d", String.valueOf(selUser.getUserId()));
    }

    long[] selectedGroupIds =
        StringUtil.split(ParamUtil.getString(_request, "selectedGroupIds"), 0L);
    boolean includeCompany = ParamUtil.getBoolean(_request, "includeCompany");
    boolean includeCurrentGroup = ParamUtil.getBoolean(_request, "includeCurrentGroup", true);
    boolean includeUserPersonalSite = ParamUtil.getBoolean(_request, "includeUserPersonalSite");
    String eventName =
        ParamUtil.getString(
            _request, "eventName", _liferayPortletResponse.getNamespace() + "selectSite");
    String target = ParamUtil.getString(_request, "target");

    portletURL.setParameter("groupId", String.valueOf(getGroupId()));
    portletURL.setParameter("selectedGroupIds", StringUtil.merge(selectedGroupIds));
    portletURL.setParameter("type", getType());
    portletURL.setParameter("types", getTypes());
    portletURL.setParameter("displayStyle", getDisplayStyle());
    portletURL.setParameter("filter", getFilter());
    portletURL.setParameter("includeCompany", String.valueOf(includeCompany));
    portletURL.setParameter("includeCurrentGroup", String.valueOf(includeCurrentGroup));
    portletURL.setParameter("includeUserPersonalSite", String.valueOf(includeUserPersonalSite));
    portletURL.setParameter("manualMembership", String.valueOf(isManualMembership()));
    portletURL.setParameter("eventName", eventName);
    portletURL.setParameter("target", target);

    return portletURL;
  }

  public String getType() {
    if (_type != null) {
      return _type;
    }

    _type = ParamUtil.getString(_request, "type");

    String[] types = getTypes();

    if (Validator.isNull(_type)) {
      _type = types[0];
    }

    return _type;
  }

  public String[] getTypes() {
    if (_types != null) {
      return _types;
    }

    _types = ParamUtil.getParameterValues(_request, "types");

    if (_types.length == 0) {
      _types = new String[] {"sites-that-i-administer"};
    }

    return _types;
  }

  public Boolean isManualMembership() {
    if (_manualMembership != null) {
      return _manualMembership;
    }

    _manualMembership = ParamUtil.getBoolean(_request, "manualMembership");

    return _manualMembership;
  }

  public Boolean isPrivateLayout() {
    if (_privateLayout != null) {
      return _privateLayout;
    }

    _privateLayout = ParamUtil.getBoolean(_request, "privateLayout");

    return _privateLayout;
  }

  private List<Group> _filterGroups(List<Group> groups, String filter) throws Exception {

    List<Group> filteredGroups = new ArrayList();

    for (Group group : groups) {
      if (filter.equals("contentSharingWithChildrenEnabled")
          && SitesUtil.isContentSharingWithChildrenEnabled(group)) {

        filteredGroups.add(group);
      }
    }

    return filteredGroups;
  }

  private List<Group> _filterLayoutGroups(List<Group> groups, Boolean privateLayout)
      throws Exception {

    List<Group> filteredGroups = new ArrayList();

    if (privateLayout == null) {
      return groups;
    }

    for (Group group : groups) {
      if (!group.isLayout()) {
        continue;
      }

      Layout layout = LayoutLocalServiceUtil.getLayout(group.getClassPK());

      if (layout.isPrivateLayout() == privateLayout) {
        filteredGroups.add(group);
      }
    }

    return filteredGroups;
  }

  private static final long[] _CLASS_NAME_IDS =
      new long[] {
        PortalUtil.getClassNameId(Group.class), PortalUtil.getClassNameId(Organization.class)
      };

  private String _displayStyle;
  private String _filter;
  private Long _groupId;
  private LinkedHashMap<String, Object> _groupParams;
  private final LiferayPortletRequest _liferayPortletRequest;
  private final LiferayPortletResponse _liferayPortletResponse;
  private Boolean _manualMembership;
  private Boolean _privateLayout;
  private final HttpServletRequest _request;
  private String _type;
  private String[] _types;
}
  protected long getStructureTypeClassNameId() {
    DDMDisplay ddmDisplay = getDDMDisplay();

    return PortalUtil.getClassNameId(ddmDisplay.getStructureType());
  }
 @Override
 public StagedModelType getStagedModelType() {
   return new StagedModelType(PortalUtil.getClassNameId(WSRPProducer.class.getName()));
 }