public List<KBArticle> getKBArticles(
      long[] resourcePrimKeys, int status, OrderByComparator orderByComparator)
      throws SystemException {

    List<KBArticle> kbArticles = new ArrayList<KBArticle>();

    Long[][] params = new Long[][] {ArrayUtil.toArray(resourcePrimKeys)};

    while ((params = KnowledgeBaseUtil.getParams(params[0])) != null) {
      List<KBArticle> curKBArticles = null;

      if (status == WorkflowConstants.STATUS_ANY) {
        curKBArticles = kbArticlePersistence.findByR_L(ArrayUtil.toArray(params[1]), true);
      } else if (status == WorkflowConstants.STATUS_APPROVED) {
        curKBArticles = kbArticlePersistence.findByR_M(ArrayUtil.toArray(params[1]), true);
      } else {
        curKBArticles = kbArticlePersistence.findByR_S(ArrayUtil.toArray(params[1]), status);
      }

      kbArticles.addAll(curKBArticles);
    }

    if (orderByComparator != null) {
      kbArticles = ListUtil.sort(kbArticles, orderByComparator);
    } else {
      kbArticles = KnowledgeBaseUtil.sort(resourcePrimKeys, kbArticles);
    }

    return new UnmodifiableList<KBArticle>(kbArticles);
  }
  public List<KeyValuePair> getAvailableVocabularyNames() throws PortalException {

    List<KeyValuePair> availableVocabularNames = new ArrayList<>();

    long[] assetVocabularyIds = getAssetVocabularyIds();

    Arrays.sort(assetVocabularyIds);

    Set<Long> availableAssetVocabularyIdsSet = SetUtil.fromArray(getAvailableAssetVocabularyIds());

    for (long assetVocabularyId : availableAssetVocabularyIdsSet) {
      if (Arrays.binarySearch(assetVocabularyIds, assetVocabularyId) < 0) {

        AssetVocabulary assetVocabulary =
            AssetVocabularyLocalServiceUtil.fetchAssetVocabulary(assetVocabularyId);

        assetVocabulary = assetVocabulary.toEscapedModel();

        availableVocabularNames.add(
            new KeyValuePair(String.valueOf(assetVocabularyId), getTitle(assetVocabulary)));
      }
    }

    return ListUtil.sort(availableVocabularNames, new KeyValuePairComparator(false, true));
  }
  public FileEntry moveFileEntryFromTrash(
      long userId, FileEntry fileEntry, long newFolderId, ServiceContext serviceContext)
      throws PortalException, SystemException {

    // File entry

    List<DLFileVersion> dlFileVersions =
        dlFileVersionLocalService.getFileVersions(
            fileEntry.getFileEntryId(), WorkflowConstants.STATUS_ANY);

    dlFileVersions = ListUtil.sort(dlFileVersions, new FileVersionVersionComparator());

    FileVersion fileVersion = new LiferayFileVersion(dlFileVersions.get(0));

    dlFileEntryLocalService.updateStatus(
        userId,
        fileVersion.getFileVersionId(),
        fileVersion.getStatus(),
        new HashMap<String, Serializable>(),
        serviceContext);

    // File rank

    dlFileRankLocalService.enableFileRanks(fileEntry.getFileEntryId());

    // App helper

    return dlAppService.moveFileEntry(fileEntry.getFileEntryId(), newFolderId, serviceContext);
  }
  public List<PluginPackage> getSortedPluginPackages() {
    List<PluginPackage> pluginPackages = new ArrayList<PluginPackage>();

    pluginPackages.addAll(_pluginPackages.values());

    return ListUtil.sort(pluginPackages, new PluginPackageNameAndContextComparator());
  }
  public List<KBArticle> getKBArticleAndAllDescendants(
      long resourcePrimKey, int status, OrderByComparator orderByComparator)
      throws SystemException {

    List<KBArticle> kbArticles = getKBArticles(new long[] {resourcePrimKey}, status, null);

    kbArticles = ListUtil.copy(kbArticles);

    Long[][] params = new Long[][] {new Long[] {resourcePrimKey}};

    while ((params = KnowledgeBaseUtil.getParams(params[0])) != null) {
      List<KBArticle> curKBArticles = null;

      if (status == WorkflowConstants.STATUS_ANY) {
        curKBArticles = kbArticlePersistence.findByP_L(ArrayUtil.toArray(params[1]), true);
      } else if (status == WorkflowConstants.STATUS_APPROVED) {
        curKBArticles = kbArticlePersistence.findByP_M(ArrayUtil.toArray(params[1]), true);
      } else {
        curKBArticles = kbArticlePersistence.findByP_S(ArrayUtil.toArray(params[1]), status);
      }

      kbArticles.addAll(curKBArticles);

      long[] resourcePrimKeys =
          StringUtil.split(ListUtil.toString(curKBArticles, "resourcePrimKey"), 0L);

      params[0] = ArrayUtil.append(params[0], ArrayUtil.toArray(resourcePrimKeys));
    }

    if (orderByComparator != null) {
      kbArticles = ListUtil.sort(kbArticles, orderByComparator);
    }

    return new UnmodifiableList<KBArticle>(kbArticles);
  }
  public List<Theme> getThemes(long companyId) {
    Map<String, Theme> themes = _getThemes(companyId);

    List<Theme> themesList = ListUtil.fromMapValues(themes);

    return ListUtil.sort(themesList);
  }
  private <T, V extends T> List<T> _subList(
      List<V> list, int start, int end, OrderByComparator<T> obc) {

    if (obc != null) {
      list = ListUtil.sort(list, obc);
    }

    return (List<T>) ListUtil.toList(ListUtil.subList(list, start, end));
  }
  public static String[] getCategories(List<App> apps, List<Bundle> bundles) {
    List<String> categories = new ArrayList<>();

    categories.addAll(getAppCategories(apps));
    categories.addAll(getBundleCategories(bundles));

    ListUtil.distinct(categories);
    ListUtil.sort(categories);

    categories.add(0, "all-categories");

    return ArrayUtil.toStringArray(categories);
  }
  protected List<String> getSortedParameterNames(
      UploadPortletRequest uploadPortletRequest, String imagePrefix) throws Exception {

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

    Enumeration<String> enu = uploadPortletRequest.getParameterNames();

    while (enu.hasMoreElements()) {
      String name = enu.nextElement();

      if (name.startsWith(imagePrefix)) {
        parameterNames.add(name);
      }
    }

    return ListUtil.sort(parameterNames);
  }
  private void _printProperties(boolean update) {
    List<String> keys = Collections.list((Enumeration<String>) _props.propertyNames());

    keys = ListUtil.sort(keys);

    if (update) {
      System.out.println("-- updated properties --");
    } else {
      System.out.println("-- listing properties --");
    }

    for (String key : keys) {
      System.out.println(key + "=" + _props.getProperty(key));
    }

    System.out.println("");
  }
  public FileEntry moveFileEntryToTrash(long userId, FileEntry fileEntry)
      throws PortalException, SystemException {

    // File entry

    DLFileEntry dlFileEntry = (DLFileEntry) fileEntry.getModel();

    dlFileEntry.setTitle(DLAppUtil.appendTrashNamespace(dlFileEntry.getTitle()));

    dlFileEntryPersistence.update(dlFileEntry, false);

    List<DLFileVersion> dlFileVersions =
        dlFileVersionLocalService.getFileVersions(
            fileEntry.getFileEntryId(), WorkflowConstants.STATUS_ANY);

    dlFileVersions = ListUtil.sort(dlFileVersions, new FileVersionVersionComparator());

    FileVersion fileVersion = new LiferayFileVersion(dlFileVersions.get(0));

    int oldStatus = fileVersion.getStatus();

    // File version

    dlFileEntryLocalService.updateStatus(
        userId,
        fileVersion.getFileVersionId(),
        WorkflowConstants.STATUS_IN_TRASH,
        new HashMap<String, Serializable>(),
        new ServiceContext());

    // File shortcut

    dlFileShortcutLocalService.disableFileShortcuts(fileEntry.getFileEntryId());

    // File rank

    dlFileRankLocalService.disableFileRanks(fileEntry.getFileEntryId());

    // Social

    socialActivityLocalService.addActivity(
        userId,
        fileEntry.getGroupId(),
        DLFileEntryConstants.getClassName(),
        fileEntry.getFileEntryId(),
        SocialActivityConstants.TYPE_MOVE_TO_TRASH,
        StringPool.BLANK,
        0);

    // Trash

    List<ObjectValuePair<Long, Integer>> fileVersionStatuses =
        new ArrayList<ObjectValuePair<Long, Integer>>(dlFileVersions.size());

    for (DLFileVersion dlFileVersion : dlFileVersions) {
      ObjectValuePair<Long, Integer> fileVersionStatus = new ObjectValuePair<Long, Integer>();

      fileVersionStatus.setKey(dlFileVersion.getFileVersionId());

      int status = dlFileVersion.getStatus();

      if (status == WorkflowConstants.STATUS_PENDING) {
        status = WorkflowConstants.STATUS_DRAFT;
      }

      fileVersionStatus.setValue(status);

      fileVersionStatuses.add(fileVersionStatus);
    }

    trashEntryLocalService.addTrashEntry(
        userId,
        fileEntry.getGroupId(),
        DLFileEntryConstants.getClassName(),
        fileEntry.getFileEntryId(),
        oldStatus,
        fileVersionStatuses,
        null);

    // Workflow

    if (oldStatus == WorkflowConstants.STATUS_PENDING) {
      workflowInstanceLinkLocalService.deleteWorkflowInstanceLink(
          fileVersion.getCompanyId(),
          fileVersion.getGroupId(),
          DLFileEntryConstants.getClassName(),
          fileVersion.getFileVersionId());
    }

    return fileEntry;
  }
  public void updateActions(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    long roleId = ParamUtil.getLong(actionRequest, "roleId");

    Role role = RoleLocalServiceUtil.getRole(roleId);

    String roleName = role.getName();

    if (roleName.equals(RoleConstants.ADMINISTRATOR)
        || roleName.equals(RoleConstants.ORGANIZATION_ADMINISTRATOR)
        || roleName.equals(RoleConstants.ORGANIZATION_OWNER)
        || roleName.equals(RoleConstants.OWNER)
        || roleName.equals(RoleConstants.SITE_ADMINISTRATOR)
        || roleName.equals(RoleConstants.SITE_OWNER)) {

      throw new RolePermissionsException(roleName);
    }

    String portletResource = ParamUtil.getString(actionRequest, "portletResource");
    String[] relatedPortletResources =
        StringUtil.split(ParamUtil.getString(actionRequest, "relatedPortletResources"));
    String[] modelResources =
        StringUtil.split(ParamUtil.getString(actionRequest, "modelResources"));

    Map<String, List<String>> resourceActionsMap = new HashMap<>();

    if (Validator.isNotNull(portletResource)) {
      resourceActionsMap.put(
          portletResource, ResourceActionsUtil.getResourceActions(portletResource, null));
    }

    for (String relatedPortletResource : relatedPortletResources) {
      resourceActionsMap.put(
          relatedPortletResource,
          ResourceActionsUtil.getResourceActions(relatedPortletResource, null));
    }

    for (String modelResource : modelResources) {
      resourceActionsMap.put(
          modelResource, ResourceActionsUtil.getResourceActions(null, modelResource));
    }

    int rootResourceScope = ResourceConstants.SCOPE_COMPANY;
    String[] rootResourceGroupIds = null;

    String[] selectedTargets =
        StringUtil.split(ParamUtil.getString(actionRequest, "selectedTargets"));
    String[] unselectedTargets =
        StringUtil.split(ParamUtil.getString(actionRequest, "unselectedTargets"));

    for (Map.Entry<String, List<String>> entry : resourceActionsMap.entrySet()) {

      String selResource = entry.getKey();
      List<String> actions = entry.getValue();

      actions = ListUtil.sort(actions, new ActionComparator(themeDisplay.getLocale()));

      for (String actionId : actions) {
        String target = selResource + actionId;

        boolean selected = ArrayUtil.contains(selectedTargets, target);

        if (!selected && !ArrayUtil.contains(unselectedTargets, target)) {

          continue;
        }

        String[] groupIds =
            StringUtil.split(ParamUtil.getString(actionRequest, "groupIds" + target));

        groupIds = ArrayUtil.distinct(groupIds);

        int scope = ResourceConstants.SCOPE_COMPANY;

        if ((role.getType() == RoleConstants.TYPE_ORGANIZATION)
            || (role.getType() == RoleConstants.TYPE_PROVIDER)
            || (role.getType() == RoleConstants.TYPE_SITE)) {

          scope = ResourceConstants.SCOPE_GROUP_TEMPLATE;
        } else {
          if (groupIds.length > 0) {
            scope = ResourceConstants.SCOPE_GROUP;
          }
        }

        if (ResourceBlockLocalServiceUtil.isSupported(selResource)) {
          updateActions_Blocks(
              role,
              themeDisplay.getScopeGroupId(),
              selResource,
              actionId,
              selected,
              scope,
              groupIds);
        } else {
          updateAction(
              role,
              themeDisplay.getScopeGroupId(),
              selResource,
              actionId,
              selected,
              scope,
              groupIds);
        }

        if (selected && actionId.equals(ActionKeys.ACCESS_IN_CONTROL_PANEL)) {

          updateViewControlPanelPermission(
              role, themeDisplay.getScopeGroupId(), selResource, scope, groupIds);

          rootResourceScope = scope;
          rootResourceGroupIds = groupIds;
        }
      }
    }

    // LPS-38031

    if (rootResourceGroupIds != null) {
      updateViewRootResourcePermission(
          role,
          themeDisplay.getScopeGroupId(),
          portletResource,
          rootResourceScope,
          rootResourceGroupIds);
    }

    // Send redirect

    SessionMessages.add(actionRequest, "permissionsUpdated");

    String redirect = PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect"));

    if (Validator.isNotNull(redirect)) {
      actionResponse.sendRedirect(redirect);
    }
  }
  protected void iteratePortlets(
      TreeNodeView parentNodeView,
      PortletCategory portletCategory,
      Set<String> portletIds,
      int parentNodeId,
      int depth) {

    List<Portlet> portlets = new ArrayList<>();

    String externalPortletCategory = null;

    for (String portletId : portletIds) {
      Portlet portlet = PortletLocalServiceUtil.getPortletById(_user.getCompanyId(), portletId);

      if (portlet != null) {
        if (portlet.isSystem()) {
        } else if (!portlet.isActive()) {
        } else if (portlet.isInstanceable() && !_includeInstanceablePortlets) {
        } else if (!portlet.isInstanceable()
            && _layoutTypePortlet.hasPortletId(portlet.getPortletId())) {

          portlets.add(portlet);
        } else if (!portlet.hasAddPortletPermission(_user.getUserId())) {
        } else {
          portlets.add(portlet);
        }

        PortletApp portletApp = portlet.getPortletApp();

        if (portletApp.isWARFile() && Validator.isNull(externalPortletCategory)) {

          PortletConfig portletConfig = PortletConfigFactoryUtil.create(portlet, _servletContext);

          ResourceBundle resourceBundle = portletConfig.getResourceBundle(getLocale());

          externalPortletCategory =
              ResourceBundleUtil.getString(resourceBundle, portletCategory.getName());
        }
      }
    }

    portlets = ListUtil.sort(portlets, new PortletTitleComparator(getLocale()));

    for (int i = 0; i < portlets.size(); i++) {
      Portlet portlet = portlets.get(i);

      TreeNodeView nodeView = new TreeNodeView(++_nodeId);

      nodeView.setDepth(depth);
      nodeView.setLeaf(true);

      if ((i + 1) == portlets.size()) {
        nodeView.setLs("1");
      } else {
        nodeView.setLs("0");
      }

      nodeView.setName(PortalUtil.getPortletTitle(portlet, _servletContext, getLocale()));
      nodeView.setObjId(portlet.getRootPortletId());
      nodeView.setParentId(parentNodeId);

      if (_hierarchicalTree) {
        parentNodeView.addChild(nodeView);
      } else {
        _list.add(nodeView);
      }
    }
  }
  protected void writeClasspathFile(
      File libDir,
      List<String> dependencyJars,
      String projectDirName,
      String projectName,
      boolean javaProject)
      throws Exception {

    File classpathFile = new File(projectDirName + "/.classpath");

    if (!javaProject) {
      classpathFile.delete();

      return;
    }

    Set<String> globalJars = new LinkedHashSet<String>();
    List<String> portalJars = new ArrayList<String>();

    Set<String> extGlobalJars = new LinkedHashSet<String>();
    Set<String> extPortalJars = new LinkedHashSet<String>();

    String libDirPath =
        StringUtil.replace(libDir.getPath(), StringPool.BACK_SLASH, StringPool.SLASH);

    if (libDirPath.contains("/ext/")) {
      FilenameFilter filenameFilter = new GlobFilenameFilter("*.jar");

      for (String dirName : new String[] {"global", "portal"}) {
        File file = new File(libDirPath + "/../ext-lib/" + dirName);

        List<String> jars = ListUtil.toList(file.list(filenameFilter));

        if (dirName.equals("global")) {
          extGlobalJars.addAll(ListUtil.sort(jars));

          File dir = new File(PropsValues.LIFERAY_LIB_GLOBAL_DIR);

          String[] fileNames = dir.list(filenameFilter);

          globalJars.addAll(ListUtil.sort(ListUtil.toList(fileNames)));
          globalJars.removeAll(extGlobalJars);
        } else if (dirName.equals("portal")) {
          extPortalJars.addAll(ListUtil.sort(jars));

          File dir = new File(PropsValues.LIFERAY_LIB_PORTAL_DIR);

          String[] fileNames = dir.list(filenameFilter);

          portalJars.addAll(ListUtil.sort(ListUtil.toList(fileNames)));
          portalJars.removeAll(extPortalJars);
        }
      }
    } else {
      globalJars.add("portlet.jar");

      portalJars.addAll(dependencyJars);
      portalJars.add("commons-logging.jar");
      portalJars.add("log4j.jar");

      portalJars = ListUtil.unique(portalJars);

      Collections.sort(portalJars);
    }

    String[] customJarsArray = libDir.list(new GlobFilenameFilter("*.jar"));

    List<String> customJars = null;

    if (customJarsArray != null) {
      customJars = ListUtil.toList(customJarsArray);

      for (String jar : portalJars) {
        customJars.remove(jar);
      }

      customJars.remove(projectName + "-service.jar");
      customJars.remove("util-bridges.jar");
      customJars.remove("util-java.jar");
      customJars.remove("util-taglib.jar");

      Collections.sort(customJars);
    } else {
      customJars = new ArrayList<String>();
    }

    StringBundler sb = new StringBundler();

    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n");
    sb.append("<classpath>\n");

    for (String sourceDirName : _SOURCE_DIR_NAMES) {
      if (_fileUtil.exists(projectDirName + "/" + sourceDirName)) {
        sb.append("\t<classpathentry excluding=\"**/.svn/**|.svn/\" ");
        sb.append("kind=\"src\" path=\"");
        sb.append(sourceDirName);
        sb.append("\" />\n");
      }
    }

    sb.append("\t<classpathentry kind=\"src\" path=\"/portal\" />\n");
    sb.append("\t<classpathentry kind=\"con\" ");
    sb.append("path=\"org.eclipse.jdt.launching.JRE_CONTAINER\" />\n");

    boolean addJunitJars = false;

    for (String testType : _TEST_TYPES) {
      String testFolder = "test/" + testType;

      if (_fileUtil.exists(projectDirName + "/" + testFolder)) {
        addJunitJars = true;

        sb.append("\t<classpathentry excluding=\"**/.svn/**|.svn/\" ");
        sb.append("kind=\"src\" path=\"");
        sb.append(testFolder);
        sb.append("\" />\n");
      }
    }

    if (addJunitJars) {
      addClasspathEntry(sb, "/portal/lib/development/junit.jar");
      addClasspathEntry(sb, "/portal/lib/development/mockito.jar");
      addClasspathEntry(sb, "/portal/lib/development/powermock-mockito.jar");
      addClasspathEntry(sb, "/portal/lib/development/spring-test.jar");

      portalJars.add("commons-io.jar");
      portalJars.add("commons-lang.jar");
    }

    addClasspathEntry(sb, "/portal/lib/development/activation.jar");
    addClasspathEntry(sb, "/portal/lib/development/annotations.jar");
    addClasspathEntry(sb, "/portal/lib/development/jsp-api.jar");
    addClasspathEntry(sb, "/portal/lib/development/mail.jar");
    addClasspathEntry(sb, "/portal/lib/development/servlet-api.jar");

    Map<String, String> attributes = new HashMap<String, String>();

    if (libDirPath.contains("/ext/")) {
      attributes.put("optional", "true");
    }

    for (String jar : globalJars) {
      addClasspathEntry(sb, "/portal/lib/global/" + jar, attributes);
    }

    portalJars = ListUtil.unique(portalJars);

    Collections.sort(portalJars);

    for (String jar : portalJars) {
      if (!jar.equals("util-slf4j.jar")) {
        addClasspathEntry(sb, "/portal/lib/portal/" + jar, attributes);
      }
    }

    addClasspathEntry(sb, "/portal/portal-service/portal-service.jar");
    addClasspathEntry(sb, "/portal/util-bridges/util-bridges.jar");
    addClasspathEntry(sb, "/portal/util-java/util-java.jar");

    if (portalJars.contains("util-slf4j.jar")) {
      addClasspathEntry(sb, "/portal/util-slf4j/util-slf4j.jar");
    }

    addClasspathEntry(sb, "/portal/util-taglib/util-taglib.jar");

    for (String jar : extGlobalJars) {
      addClasspathEntry(sb, "docroot/WEB-INF/ext-lib/global/" + jar);
    }

    for (String jar : extPortalJars) {
      addClasspathEntry(sb, "docroot/WEB-INF/ext-lib/portal/" + jar);
    }

    for (String jar : customJars) {
      if (libDirPath.contains("/tmp/WEB-INF/lib")) {
        addClasspathEntry(sb, "tmp/WEB-INF/lib/" + jar);
      } else if (libDirPath.contains("/docroot/WEB-INF/lib")) {
        addClasspathEntry(sb, "docroot/WEB-INF/lib/" + jar);
      } else {
        addClasspathEntry(sb, "lib/" + jar);
      }
    }

    File ivyXmlFile = new File(projectDirName, "ivy.xml");

    if (ivyXmlFile.exists()) {
      String content = _fileUtil.read(ivyXmlFile);

      if (content.contains("arquillian-junit-container")) {
        String ivyDirName = ".ivy";

        for (int i = 0; i < 10; i++) {
          if (_fileUtil.exists(ivyDirName)) {
            break;
          }

          ivyDirName = "../" + ivyDirName;
        }

        addIvyCacheJar(sb, ivyDirName, "org.apache.felix/org.apache.felix.framework");
        addIvyCacheJar(sb, ivyDirName, "org.jboss.arquillian.junit/arquillian-junit-core");
        addIvyCacheJar(sb, ivyDirName, "org.jboss.arquillian.test/arquillian-test-api");
      }
    }

    sb.append("\t<classpathentry kind=\"output\" path=\"bin\" />\n");
    sb.append("</classpath>");

    System.out.println("Updating " + classpathFile);

    String content = StringUtil.replace(sb.toString(), "\"/portal", "\"/portal-" + _BRANCH);

    _fileUtil.write(classpathFile, content);
  }
  public List<Theme> getThemes(long companyId) {
    List<Theme> themes = ListUtil.fromCollection(_getThemes(companyId).values());

    return ListUtil.sort(themes);
  }
  protected void doReIndex(int delay) {
    if (SearchEngineUtil.isIndexReadOnly()) {
      return;
    }

    if (_log.isInfoEnabled()) {
      _log.info("Reindexing Lucene started");
    }

    if (delay < 0) {
      delay = 0;
    }

    try {
      if (delay > 0) {
        Thread.sleep(Time.SECOND * delay);
      }
    } catch (InterruptedException ie) {
    }

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    try {
      SearchEngineUtil.removeCompany(_companyId);

      SearchEngineUtil.initialize(_companyId);

      List<Portlet> portlets = PortletLocalServiceUtil.getPortlets(_companyId);

      portlets = ListUtil.sort(portlets, new PortletLuceneComparator());

      for (Portlet portlet : portlets) {
        if (!portlet.isActive()) {
          continue;
        }

        List<Indexer> indexers = portlet.getIndexerInstances();

        if (indexers == null) {
          continue;
        }

        Set<String> searchEngineIds = new HashSet<>();

        for (Indexer indexer : indexers) {
          String searchEngineId = indexer.getSearchEngineId();

          if (searchEngineIds.add(searchEngineId)) {
            SearchEngineUtil.deletePortletDocuments(
                searchEngineId, _companyId, portlet.getPortletId(), true);
          }

          reindex(indexer);
        }
      }

      if (_log.isInfoEnabled()) {
        _log.info(
            "Reindexing Lucene completed in " + (stopWatch.getTime() / Time.SECOND) + " seconds");
      }
    } catch (Exception e) {
      _log.error("Error encountered while reindexing", e);

      if (_log.isInfoEnabled()) {
        _log.info("Reindexing Lucene failed");
      }
    }

    _finished = true;
  }
  protected void updateActions(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    long roleId = ParamUtil.getLong(actionRequest, "roleId");

    Role role = RoleLocalServiceUtil.getRole(roleId);

    String roleName = role.getName();

    if (roleName.equals(RoleConstants.ADMINISTRATOR)
        || roleName.equals(RoleConstants.ORGANIZATION_ADMINISTRATOR)
        || roleName.equals(RoleConstants.ORGANIZATION_OWNER)
        || roleName.equals(RoleConstants.OWNER)
        || roleName.equals(RoleConstants.SITE_ADMINISTRATOR)
        || roleName.equals(RoleConstants.SITE_OWNER)) {

      throw new RolePermissionsException(roleName);
    }

    String portletResource = ParamUtil.getString(actionRequest, "portletResource");
    String[] modelResources =
        StringUtil.split(ParamUtil.getString(actionRequest, "modelResources"));
    boolean showModelResources = ParamUtil.getBoolean(actionRequest, "showModelResources");

    Map<String, List<String>> resourceActionsMap = new HashMap<String, List<String>>();

    if (showModelResources) {
      for (String modelResource : modelResources) {
        resourceActionsMap.put(
            modelResource, ResourceActionsUtil.getResourceActions(null, modelResource));
      }
    } else if (Validator.isNotNull(portletResource)) {
      resourceActionsMap.put(
          portletResource, ResourceActionsUtil.getResourceActions(portletResource, null));
    }

    String[] selectedTargets =
        StringUtil.split(ParamUtil.getString(actionRequest, "selectedTargets"));

    for (Map.Entry<String, List<String>> entry : resourceActionsMap.entrySet()) {

      String selResource = entry.getKey();
      List<String> actions = entry.getValue();

      actions = ListUtil.sort(actions, new ActionComparator(themeDisplay.getLocale()));

      for (String actionId : actions) {
        String target = selResource + actionId;

        boolean selected = ArrayUtil.contains(selectedTargets, target);

        String[] groupIds =
            StringUtil.split(ParamUtil.getString(actionRequest, "groupIds" + target));

        groupIds = ArrayUtil.distinct(groupIds);

        int scope = ResourceConstants.SCOPE_COMPANY;

        if ((role.getType() == RoleConstants.TYPE_ORGANIZATION)
            || (role.getType() == RoleConstants.TYPE_PROVIDER)
            || (role.getType() == RoleConstants.TYPE_SITE)) {

          scope = ResourceConstants.SCOPE_GROUP_TEMPLATE;
        } else {
          if (groupIds.length > 0) {
            scope = ResourceConstants.SCOPE_GROUP;
          }
        }

        if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) {
          if (ResourceBlockLocalServiceUtil.isSupported(selResource)) {

            updateActions_6Blocks(
                role,
                themeDisplay.getScopeGroupId(),
                selResource,
                actionId,
                selected,
                scope,
                groupIds);
          } else {
            updateAction_6(
                role,
                themeDisplay.getScopeGroupId(),
                selResource,
                actionId,
                selected,
                scope,
                groupIds);
          }
        } else {
          updateAction_1to5(
              role,
              themeDisplay.getScopeGroupId(),
              selResource,
              actionId,
              selected,
              scope,
              groupIds);
        }
      }
    }

    // Send redirect

    SessionMessages.add(actionRequest, "permissionsUpdated");

    String redirect = PortalUtil.escapeRedirect(ParamUtil.getString(actionRequest, "redirect"));

    if (Validator.isNotNull(redirect)) {
      redirect = redirect + "&" + Constants.CMD + "=" + Constants.VIEW;

      actionResponse.sendRedirect(redirect);
    }
  }
  public List<ColorScheme> getColorSchemes() {
    List<ColorScheme> colorSchemes = ListUtil.fromMapValues(_colorSchemesMap);

    return ListUtil.sort(colorSchemes);
  }
  protected void iteratePortletCategories(
      TreeNodeView parentNodeView,
      List<PortletCategory> portletCategories,
      long parentId,
      int depth)
      throws PortalException {

    portletCategories =
        ListUtil.sort(portletCategories, new PortletCategoryComparator(getLocale()));

    for (int i = 0; i < portletCategories.size(); i++) {
      PortletCategory portletCategory = portletCategories.get(i);

      if (portletCategory.isHidden()) {
        continue;
      }

      if (i == 0) {
        depth++;

        if (depth > _depth) {
          _depth = depth;
        }
      }

      TreeNodeView nodeView = new TreeNodeView(++_nodeId);

      nodeView.setDepth(depth);
      nodeView.setLeaf(false);

      if ((i + 1) == portletCategories.size()) {
        nodeView.setLs("1");
      } else {
        nodeView.setLs("0");
      }

      nodeView.setName(LanguageUtil.get(getLocale(), portletCategory.getName()));
      nodeView.setObjId(portletCategory.getPath());
      nodeView.setParentId(parentId);

      if (_hierarchicalTree) {
        if (parentNodeView != null) {
          parentNodeView.addChild(nodeView);
        }
      } else {
        _list.add(nodeView);
      }

      int nodeId = _nodeId;

      List<PortletCategory> subCategories =
          ListUtil.fromCollection(portletCategory.getCategories());

      iteratePortletCategories(nodeView, subCategories, nodeId, depth);

      if (_iteratePortlets) {
        iteratePortlets(
            nodeView, portletCategory, portletCategory.getPortletIds(), nodeId, depth + 1);
      }
    }
  }