@Override
  protected BooleanClause doGetFacetClause() {
    SearchContext searchContext = getSearchContext();

    FacetConfiguration facetConfiguration = getFacetConfiguration();

    JSONObject dataJSONObject = facetConfiguration.getData();

    String[] values = null;

    if (isStatic() && dataJSONObject.has("values")) {
      JSONArray valuesJSONArray = dataJSONObject.getJSONArray("values");

      values = new String[valuesJSONArray.length()];

      for (int i = 0; i < valuesJSONArray.length(); i++) {
        values[i] = valuesJSONArray.getString(i);
      }
    }

    String[] valuesParam =
        StringUtil.split(GetterUtil.getString(searchContext.getAttribute(getFieldName())));

    if (!isStatic() && (valuesParam != null) && (valuesParam.length > 0)) {
      values = valuesParam;
    }

    if ((values == null) || (values.length == 0)) {
      return null;
    }

    BooleanQuery facetQuery = BooleanQueryFactoryUtil.create(searchContext);

    for (String value : values) {
      FacetValueValidator facetValueValidator = getFacetValueValidator();

      if ((searchContext.getUserId() > 0) && !facetValueValidator.check(searchContext, value)) {

        continue;
      }

      TermQuery termQuery = TermQueryFactoryUtil.create(searchContext, getFieldName(), value);

      try {
        facetQuery.add(termQuery, BooleanClauseOccur.SHOULD);
      } catch (ParseException pe) {
        _log.error(pe, pe);
      }
    }

    if (!facetQuery.hasClauses()) {
      return null;
    }

    return BooleanClauseFactoryUtil.create(
        searchContext, facetQuery, BooleanClauseOccur.MUST.getName());
  }
  protected long[] getLayoutIds(long groupId, boolean privateLayout, String layoutIdsJSON)
      throws Exception {

    if (Validator.isNull(layoutIdsJSON)) {
      return new long[0];
    }

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

    JSONArray jsonArray = JSONFactoryUtil.createJSONArray(layoutIdsJSON);

    for (int i = 0; i < jsonArray.length(); ++i) {
      JSONObject jsonObject = jsonArray.getJSONObject(i);

      long layoutId = jsonObject.getLong("layoutId");

      if (layoutId > 0) {
        layoutIds.add(layoutId);
      }

      if (jsonObject.getBoolean("includeChildren")) {
        addLayoutIds(layoutIds, groupId, privateLayout, layoutId);
      }
    }

    return ArrayUtil.toArray(layoutIds.toArray(new Long[layoutIds.size()]));
  }
  protected void updateBasicConfiguration(
      PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    boolean displayScopeFacet =
        GetterUtil.getBoolean(getParameter(actionRequest, "displayScopeFacet"));
    boolean displayAssetCategoriesFacet =
        GetterUtil.getBoolean(getParameter(actionRequest, "displayAssetCategoriesFacet"));
    boolean displayAssetTagsFacet =
        GetterUtil.getBoolean(getParameter(actionRequest, "displayAssetTagsFacet"));
    boolean displayAssetTypeFacet =
        GetterUtil.getBoolean(getParameter(actionRequest, "displayAssetTypeFacet"));
    boolean displayFolderFacet =
        GetterUtil.getBoolean(getParameter(actionRequest, "displayFolderFacet"));
    boolean displayUserFacet =
        GetterUtil.getBoolean(getParameter(actionRequest, "displayUserFacet"));
    boolean displayModifiedRangeFacet =
        GetterUtil.getBoolean(getParameter(actionRequest, "displayModifiedRangeFacet"));

    String searchConfiguration = ContentUtil.get(SearchWebConfigurationValues.FACET_CONFIGURATION);

    JSONObject configurationJSONObject = JSONFactoryUtil.createJSONObject(searchConfiguration);

    JSONArray oldFacetsJSONArray = configurationJSONObject.getJSONArray("facets");

    if (oldFacetsJSONArray == null) {
      if (_log.isWarnEnabled()) {
        _log.warn(
            "The resource "
                + SearchWebConfigurationValues.FACET_CONFIGURATION
                + " is missing a valid facets JSON array");
      }
    }

    JSONArray newFacetsJSONArray = JSONFactoryUtil.createJSONArray();

    for (int i = 0; i < oldFacetsJSONArray.length(); i++) {
      JSONObject oldFacetJSONObject = oldFacetsJSONArray.getJSONObject(i);

      String fieldName = oldFacetJSONObject.getString("fieldName");

      if ((displayScopeFacet && fieldName.equals("groupId"))
          || (displayAssetCategoriesFacet && fieldName.equals("assetCategoryIds"))
          || (displayAssetTagsFacet && fieldName.equals("assetTagNames"))
          || (displayAssetTypeFacet && fieldName.equals("entryClassName"))
          || (displayFolderFacet && fieldName.equals("folderId"))
          || (displayUserFacet && fieldName.equals("userId"))
          || (displayModifiedRangeFacet && fieldName.equals("modified"))) {

        newFacetsJSONArray.put(oldFacetJSONObject);
      }
    }

    configurationJSONObject.put("facets", newFacetsJSONArray);

    searchConfiguration = configurationJSONObject.toString();

    setPreference(actionRequest, "searchConfiguration", searchConfiguration);
  }
  protected String interpretJIRAChangeItems(
      JSONArray jiraChangeItemsJSONArray, ServiceContext serviceContext) {

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

    if (jiraChangeItemsJSONArray.length() == 0) {
      return (serviceContext.translate("activity-social-coding-jira-add-change-default"));
    }

    StringBundler sb = new StringBundler(jiraChangeItemsJSONArray.length());

    for (int i = 0; i < jiraChangeItemsJSONArray.length(); i++) {
      JSONObject jiraChangeItemJSONObject = jiraChangeItemsJSONArray.getJSONObject(i);

      sb.append(interpretJIRAChangeItem(jiraChangeItemJSONObject, serviceContext));
    }

    return sb.toString();
  }
  protected void addLayouts(long parentLayoutId, JSONArray layoutsJSONArray) throws Exception {

    if (layoutsJSONArray == null) {
      return;
    }

    for (int i = 0; i < layoutsJSONArray.length(); i++) {
      JSONObject layoutJSONObject = layoutsJSONArray.getJSONObject(i);

      addLayout(parentLayoutId, layoutJSONObject);
    }
  }
  protected void addLayoutColumns(Layout layout, JSONArray columnsJSONArray) throws Exception {

    if (columnsJSONArray == null) {
      return;
    }

    for (int i = 0; i < columnsJSONArray.length(); i++) {
      JSONArray columnJSONArray = columnsJSONArray.getJSONArray(i);

      addLayoutColumn(layout, "column-" + (i + 1), columnJSONArray);
    }
  }
  protected void updateActivitySettings(ActionRequest actionRequest) throws Exception {

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

    String settingsJSON = ParamUtil.getString(actionRequest, "settingsJSON");

    JSONObject settingsJSONObject = JSONFactoryUtil.createJSONObject(settingsJSON);

    JSONArray actionsJSONArray = settingsJSONObject.getJSONArray("actions");

    String modelName = settingsJSONObject.getString("modelName");

    for (int i = 0; i < actionsJSONArray.length(); i++) {
      JSONObject actionJSONObject = actionsJSONArray.getJSONObject(i);

      int activityType = actionJSONObject.getInt("activityType");

      SocialActivityDefinition activityDefinition =
          SocialActivitySettingServiceUtil.getActivityDefinition(
              themeDisplay.getSiteGroupIdOrLiveGroupId(), modelName, activityType);

      if (activityDefinition == null) {
        continue;
      }

      List<SocialActivityCounterDefinition> activityCounterDefinitions = new ArrayList<>();

      activityCounterDefinitions.add(
          updateActivityCounterDefinition(
              actionJSONObject,
              activityDefinition,
              SocialActivityCounterConstants.NAME_CONTRIBUTION));

      activityCounterDefinitions.add(
          updateActivityCounterDefinition(
              actionJSONObject,
              activityDefinition,
              SocialActivityCounterConstants.NAME_PARTICIPATION));

      activityCounterDefinitions.add(
          updateActivityCounterDefinition(
              actionJSONObject,
              activityDefinition,
              SocialActivityCounterConstants.NAME_POPULARITY));

      SocialActivitySettingServiceUtil.updateActivitySettings(
          themeDisplay.getSiteGroupIdOrLiveGroupId(),
          modelName,
          activityType,
          activityCounterDefinitions);
    }
  }
  @Test
  public void testGetSelectedLayoutsJSONSelectNoLayouts() throws Exception {
    Layout layout = LayoutTestUtil.addLayout(_stagingGroup);

    LayoutTestUtil.addLayout(_stagingGroup, layout.getPlid());

    String selectedLayoutsJSON =
        ExportImportHelperUtil.getSelectedLayoutsJSON(
            _stagingGroup.getGroupId(), false, StringUtil.merge(new long[0]));

    JSONArray selectedLayoutsJSONArray = JSONFactoryUtil.createJSONArray(selectedLayoutsJSON);

    Assert.assertEquals(0, selectedLayoutsJSONArray.length());
  }
  private static String toHTMLTable(
      JSONArray json, JSONArray columns, int limit, String tableId, String tableClass) {
    if ((json == null) || (json.length() <= 0)) {
      return (null);
    }

    // Check for objects or arrays
    if (json.getJSONObject(0) != null) {
      return (SQLRenderUtil.toHTMLTable(json, limit, tableId, tableClass));
    } else if (json.getJSONArray(0) != null) {
      return (SQLRenderUtil.toHTMLTable(json, toJSONTitles(columns), limit, tableId, tableClass));
    }
    return (null);
  }
  @Override
  @Transactional(enabled = false)
  public Map<String, Object> updateFileEntries(File zipFile) throws PortalException {

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

    ZipReader zipReader = null;

    try {
      zipReader = ZipReaderFactoryUtil.getZipReader(zipFile);

      String manifest = zipReader.getEntryAsString("/manifest.json");

      JSONArray jsonArray = JSONFactoryUtil.createJSONArray(manifest);

      for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);

        JSONWebServiceActionParametersMap jsonWebServiceActionParametersMap =
            JSONFactoryUtil.looseDeserialize(
                jsonObject.toString(), JSONWebServiceActionParametersMap.class);

        String zipFileId = MapUtil.getString(jsonWebServiceActionParametersMap, "zipFileId");

        try {
          responseMap.put(
              zipFileId,
              updateFileEntries(zipReader, zipFileId, jsonWebServiceActionParametersMap));
        } catch (Exception e) {
          String message = e.getMessage();

          if (!message.startsWith(StringPool.QUOTE) && !message.endsWith(StringPool.QUOTE)) {

            message = StringUtil.quote(message, StringPool.QUOTE);
          }

          String json = "{\"exception\": " + message + "}";

          responseMap.put(zipFileId, json);
        }
      }
    } finally {
      if (zipReader != null) {
        zipReader.close();
      }
    }

    return responseMap;
  }
  protected Map<String, String> getTemplateParams(JSONArray templateParamsJSONArray) {

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

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

    for (int i = 0; i < templateParamsJSONArray.length(); i++) {
      JSONObject templateParamJSONObject = templateParamsJSONArray.getJSONObject(i);

      JSONArray namesJSONArray = templateParamJSONObject.names();

      for (int j = 0; j < namesJSONArray.length(); j++) {
        String name = namesJSONArray.getString(j);

        String value = templateParamJSONObject.getString(name);

        templateParams.put(name, value);
      }
    }

    return templateParams;
  }
  public static JSONArray toJSONTitles(JSONArray columns) {
    if (columns == null) {
      return (null);
    }

    JSONArray titles = JSONFactoryUtil.createJSONArray();
    int columnsLength = columns.length();
    for (int column = 0; column < columnsLength; column++) {
      JSONObject jsonObject = columns.getJSONObject(column);
      if (jsonObject != null) {
        titles.put(
            jsonObject.getString("title", jsonObject.getString("data", String.valueOf(column))));
      }
    }
    return (titles);
  }
  protected void addLayoutColumn(Layout layout, String columnId, JSONArray columnJSONArray)
      throws Exception {

    if (columnJSONArray == null) {
      return;
    }

    for (int i = 0; i < columnJSONArray.length(); i++) {
      JSONObject portletJSONObject = columnJSONArray.getJSONObject(i);

      if (portletJSONObject == null) {
        String articleId = getJournalArticleId(columnJSONArray.getString(i));

        portletJSONObject = getDefaultPortletJSONObject(articleId);
      }

      addLayoutColumnPortlet(layout, columnId, portletJSONObject);
    }
  }
  protected List<MediaItem> getMediaItems(JSONArray mediaItemsJSONArray) {
    if (mediaItemsJSONArray == null) {
      return null;
    }

    List<MediaItem> mediaItems = new ArrayList<MediaItem>();

    for (int i = 0; i < mediaItemsJSONArray.length(); i++) {
      JSONObject mediaItemsJsonObject = mediaItemsJSONArray.getJSONObject(i);

      MediaItem mediaItem =
          new MediaItemImpl(
              mediaItemsJsonObject.getString("mimeType"),
              Type.valueOf(mediaItemsJsonObject.getString("type")),
              mediaItemsJsonObject.getString("url"));

      mediaItems.add(mediaItem);
    }

    return mediaItems;
  }
  @Test
  public void testGetSelectedLayoutsJSONSelectChildLayout() throws Exception {
    Layout layout = LayoutTestUtil.addLayout(_stagingGroup);

    Layout childLayout = LayoutTestUtil.addLayout(_stagingGroup, layout.getPlid());

    long[] selectedLayoutIds = new long[] {childLayout.getLayoutId()};

    String selectedLayoutsJSON =
        ExportImportHelperUtil.getSelectedLayoutsJSON(
            _stagingGroup.getGroupId(), false, StringUtil.merge(selectedLayoutIds));

    JSONArray selectedLayoutsJSONArray = JSONFactoryUtil.createJSONArray(selectedLayoutsJSON);

    Assert.assertEquals(1, selectedLayoutsJSONArray.length());

    JSONObject layoutJSONObject = selectedLayoutsJSONArray.getJSONObject(0);

    Assert.assertTrue(layoutJSONObject.getBoolean("includeChildren"));
    Assert.assertEquals(childLayout.getPlid(), layoutJSONObject.getLong("plid"));
  }
  protected String getDDMFormFieldValueString(DDMFormFieldValue ddmFormFieldValue) {

    Value value = ddmFormFieldValue.getValue();

    String valueString = value.getString(_locale);

    String type = getDDMFormFieldType(ddmFormFieldValue.getName());

    if (type.equals(DDMFormFieldType.SELECT)) {
      try {
        JSONArray jsonArray = _jsonFactory.createJSONArray(valueString);

        if (jsonArray.length() == 1) {
          valueString = jsonArray.getString(0);
        }
      } catch (JSONException je) {
        ReflectionUtil.throwException(je);
      }
    }

    return valueString;
  }
  public JSONArray getJSONSearch(
      long groupId, String name, long[] vocabularyIds, int start, int end)
      throws PortalException, SystemException {

    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

    for (AssetVocabulary vocabulary : assetVocabularyService.getVocabularies(vocabularyIds)) {

      List<AssetCategory> vocabularyCategory =
          assetCategoryFinder.findByG_N_V(
              groupId, name, vocabulary.getVocabularyId(), start, end, null);

      JSONArray vocabularyCategoryJSONArray = toJSONArray(vocabularyCategory);

      for (int i = 0; i < vocabularyCategoryJSONArray.length(); ++i) {
        JSONObject vocabularyCategoryJSONObject = vocabularyCategoryJSONArray.getJSONObject(i);

        jsonArray.put(vocabularyCategoryJSONObject);
      }
    }

    return jsonArray;
  }