@Override
  protected void doDispatch(RenderRequest renderRequest, RenderResponse renderResponse)
      throws IOException, PortletException {

    try {
      getGroup(renderRequest);
    } catch (Exception e) {
      if (e instanceof NoSuchGroupException || e instanceof PrincipalException) {

        SessionErrors.add(renderRequest, e.getClass());
      } else {
        throw new PortletException(e);
      }
    }

    if (SessionErrors.contains(renderRequest, NoSuchGroupException.class.getName())
        || SessionErrors.contains(renderRequest, PrincipalException.getNestedClasses())) {

      include("/error.jsp", renderRequest, renderResponse);
    } else {
      try {
        ServiceContext serviceContext = ServiceContextFactory.getInstance(renderRequest);

        ServiceContextThreadLocal.pushServiceContext(serviceContext);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn(e, e);
        }
      }

      renderRequest.setAttribute(ApplicationListWebKeys.GROUP_PROVIDER, groupProvider);

      super.doDispatch(renderRequest, renderResponse);
    }
  }
  public void updateSAPEntry(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    String allowedServiceSignatures =
        ParamUtil.getString(actionRequest, "allowedServiceSignatures");
    boolean defaultSAPEntry = ParamUtil.getBoolean(actionRequest, "defaultSAPEntry");
    boolean enabled = ParamUtil.getBoolean(actionRequest, "enabled");
    String name = ParamUtil.getString(actionRequest, "name");
    Map<Locale, String> titleMap = LocalizationUtil.getLocalizationMap(actionRequest, "title");

    ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);

    if (sapEntryId > 0) {
      _sapEntryService.updateSAPEntry(
          sapEntryId,
          allowedServiceSignatures,
          defaultSAPEntry,
          enabled,
          name,
          titleMap,
          serviceContext);
    } else {
      _sapEntryService.addSAPEntry(
          allowedServiceSignatures, defaultSAPEntry, enabled, name, titleMap, serviceContext);
    }
  }
  public void enableLayout(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    LayoutRevision incompleteLayoutRevision =
        layoutRevisionLocalService.getLayoutRevision(incompleteLayoutRevisionId);

    long layoutBranchId =
        ParamUtil.getLong(
            actionRequest, "layoutBranchId", incompleteLayoutRevision.getLayoutBranchId());

    ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);

    serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);

    layoutRevisionLocalService.updateLayoutRevision(
        serviceContext.getUserId(),
        incompleteLayoutRevision.getLayoutRevisionId(),
        layoutBranchId,
        incompleteLayoutRevision.getName(),
        incompleteLayoutRevision.getTitle(),
        incompleteLayoutRevision.getDescription(),
        incompleteLayoutRevision.getKeywords(),
        incompleteLayoutRevision.getRobots(),
        incompleteLayoutRevision.getTypeSettings(),
        incompleteLayoutRevision.getIconImage(),
        incompleteLayoutRevision.getIconImageId(),
        incompleteLayoutRevision.getThemeId(),
        incompleteLayoutRevision.getColorSchemeId(),
        incompleteLayoutRevision.getCss(),
        serviceContext);
  }
  protected void moveEntries(ActionRequest actionRequest) throws Exception {
    long newFolderId = ParamUtil.getLong(actionRequest, "newFolderId");

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(DLFileEntry.class.getName(), actionRequest);

    long[] folderIds = ParamUtil.getLongValues(actionRequest, "rowIdsFolder");

    for (long folderId : folderIds) {
      _dlAppService.moveFolder(folderId, newFolderId, serviceContext);
    }

    long[] fileEntryIds = ParamUtil.getLongValues(actionRequest, "rowIdsFileEntry");

    for (long fileEntryId : fileEntryIds) {
      _dlAppService.moveFileEntry(fileEntryId, newFolderId, serviceContext);
    }

    long[] fileShortcutIds = ParamUtil.getLongValues(actionRequest, "rowIdsDLFileShortcut");

    for (long fileShortcutId : fileShortcutIds) {
      if (fileShortcutId == 0) {
        continue;
      }

      FileShortcut fileShortcut = _dlAppService.getFileShortcut(fileShortcutId);

      _dlAppService.updateFileShortcut(
          fileShortcutId, newFolderId, fileShortcut.getToFileEntryId(), serviceContext);
    }
  }
  protected void checkOutEntries(ActionRequest actionRequest) throws Exception {

    long[] fileEntryIds = ParamUtil.getLongValues(actionRequest, "rowIdsFileEntry");

    ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);

    for (long fileEntryId : fileEntryIds) {
      _dlAppService.checkOutFileEntry(fileEntryId, serviceContext);
    }
  }
  public void editUserGroup(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    String name = ParamUtil.getString(actionRequest, "name");
    String description = ParamUtil.getString(actionRequest, "description");

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(UserGroup.class.getName(), actionRequest);

    UserGroup userGroup = null;

    try (ProxyModeThreadLocalCloseable proxyModeThreadLocalCloseable =
        new ProxyModeThreadLocalCloseable()) {

      ProxyModeThreadLocal.setForceSync(true);

      if (userGroupId <= 0) {

        // Add user group

        userGroup = _userGroupService.addUserGroup(name, description, serviceContext);
      } else {

        // Update user group

        userGroup =
            _userGroupService.updateUserGroup(userGroupId, name, description, serviceContext);
      }
    }

    // Layout set prototypes

    long publicLayoutSetPrototypeId =
        ParamUtil.getLong(actionRequest, "publicLayoutSetPrototypeId");
    long privateLayoutSetPrototypeId =
        ParamUtil.getLong(actionRequest, "privateLayoutSetPrototypeId");
    boolean publicLayoutSetPrototypeLinkEnabled =
        ParamUtil.getBoolean(actionRequest, "publicLayoutSetPrototypeLinkEnabled");
    boolean privateLayoutSetPrototypeLinkEnabled =
        ParamUtil.getBoolean(actionRequest, "privateLayoutSetPrototypeLinkEnabled");

    if ((privateLayoutSetPrototypeId > 0) || (publicLayoutSetPrototypeId > 0)) {

      SitesUtil.updateLayoutSetPrototypesLinks(
          userGroup.getGroup(),
          publicLayoutSetPrototypeId,
          privateLayoutSetPrototypeId,
          publicLayoutSetPrototypeLinkEnabled,
          privateLayoutSetPrototypeLinkEnabled);
    }
  }
  protected FileEntry updateFileEntry(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

    long fileEntryId = ParamUtil.getLong(uploadPortletRequest, "fileEntryId");

    String sourceFileName = uploadPortletRequest.getFileName("imageEditorFileName");

    FileEntry fileEntry = _dlAppLocalService.getFileEntry(fileEntryId);

    InputStream inputStream = uploadPortletRequest.getFileAsStream("imageEditorFileName");
    String contentType = uploadPortletRequest.getContentType("imageEditorFileName");
    long size = uploadPortletRequest.getSize("imageEditorFileName");

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(DLFileEntry.class.getName(), uploadPortletRequest);

    fileEntry =
        _dlAppService.updateFileEntry(
            fileEntryId,
            sourceFileName,
            contentType,
            fileEntry.getTitle(),
            fileEntry.getDescription(),
            StringPool.BLANK,
            false,
            inputStream,
            size,
            serviceContext);

    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

    jsonObject.put("success", Boolean.TRUE);

    ResourceBundle resourceBundle =
        _resourceBundleLoader.loadResourceBundle(
            LanguageUtil.getLanguageId(themeDisplay.getLocale()));

    SessionMessages.add(
        actionRequest,
        "requestProcessed",
        LanguageUtil.get(resourceBundle, "the-image-was-edited-successfully"));

    JSONPortletResponseUtil.writeJSON(actionRequest, actionResponse, jsonObject);

    return fileEntry;
  }
  protected DDMTemplate addTemplate(ActionRequest actionRequest) throws Exception {

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

    long groupId = ParamUtil.getLong(uploadPortletRequest, "groupId");
    long classNameId = ParamUtil.getLong(uploadPortletRequest, "classNameId");
    long classPK = ParamUtil.getLong(uploadPortletRequest, "classPK");
    long resourceClassNameId = ParamUtil.getLong(uploadPortletRequest, "resourceClassNameId");
    String templateKey = ParamUtil.getString(uploadPortletRequest, "templateKey");
    Map<Locale, String> nameMap = LocalizationUtil.getLocalizationMap(uploadPortletRequest, "name");
    Map<Locale, String> descriptionMap =
        LocalizationUtil.getLocalizationMap(uploadPortletRequest, "description");
    String type = ParamUtil.getString(uploadPortletRequest, "type");
    String mode = ParamUtil.getString(uploadPortletRequest, "mode");
    String language =
        ParamUtil.getString(uploadPortletRequest, "language", TemplateConstants.LANG_TYPE_VM);

    String script = getScript(uploadPortletRequest);

    boolean cacheable = ParamUtil.getBoolean(uploadPortletRequest, "cacheable");
    boolean smallImage = ParamUtil.getBoolean(uploadPortletRequest, "smallImage");
    String smallImageURL = ParamUtil.getString(uploadPortletRequest, "smallImageURL");
    File smallImageFile = uploadPortletRequest.getFile("smallImageFile");

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(DDMTemplate.class.getName(), uploadPortletRequest);

    return _ddmTemplateService.addTemplate(
        groupId,
        classNameId,
        classPK,
        resourceClassNameId,
        templateKey,
        nameMap,
        descriptionMap,
        type,
        mode,
        language,
        script,
        cacheable,
        smallImage,
        smallImageURL,
        smallImageFile,
        serviceContext);
  }
  protected void updateFolder(ActionRequest actionRequest) throws Exception {
    long folderId = ParamUtil.getLong(actionRequest, "folderId");

    long parentFolderId = ParamUtil.getLong(actionRequest, "parentFolderId");
    String name = ParamUtil.getString(actionRequest, "name");
    String description = ParamUtil.getString(actionRequest, "description");

    boolean mergeWithParentFolder = ParamUtil.getBoolean(actionRequest, "mergeWithParentFolder");

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(BookmarksFolder.class.getName(), actionRequest);

    if (folderId <= 0) {
      _bookmarksFolderService.addFolder(parentFolderId, name, description, serviceContext);
    } else if (mergeWithParentFolder) {
      _bookmarksFolderService.mergeFolders(folderId, parentFolderId);
    } else {
      _bookmarksFolderService.updateFolder(
          folderId, parentFolderId, name, description, serviceContext);
    }
  }
  protected MBMessage updateMessage(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

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

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

    long groupId = themeDisplay.getScopeGroupId();
    long categoryId = ParamUtil.getLong(actionRequest, "mbCategoryId");
    long threadId = ParamUtil.getLong(actionRequest, "threadId");
    long parentMessageId = ParamUtil.getLong(actionRequest, "parentMessageId");
    String subject = ParamUtil.getString(actionRequest, "subject");
    String body = ParamUtil.getString(actionRequest, "body");

    MBGroupServiceSettings mbGroupServiceSettings = MBGroupServiceSettings.getInstance(groupId);

    List<ObjectValuePair<String, InputStream>> inputStreamOVPs = new ArrayList<>(5);

    try {
      UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

      for (int i = 1; i <= 5; i++) {
        String fileName = uploadPortletRequest.getFileName("msgFile" + i);
        InputStream inputStream = uploadPortletRequest.getFileAsStream("msgFile" + i);

        if ((inputStream == null) || Validator.isNull(fileName)) {
          continue;
        }

        ObjectValuePair<String, InputStream> inputStreamOVP =
            new ObjectValuePair<>(fileName, inputStream);

        inputStreamOVPs.add(inputStreamOVP);
      }

      boolean question = ParamUtil.getBoolean(actionRequest, "question");
      boolean anonymous = ParamUtil.getBoolean(actionRequest, "anonymous");
      double priority = ParamUtil.getDouble(actionRequest, "priority");
      boolean allowPingbacks = ParamUtil.getBoolean(actionRequest, "allowPingbacks");

      ServiceContext serviceContext =
          ServiceContextFactory.getInstance(MBMessage.class.getName(), actionRequest);

      boolean preview = ParamUtil.getBoolean(actionRequest, "preview");

      serviceContext.setAttribute("preview", preview);

      MBMessage message = null;

      if (messageId <= 0) {
        if (PropsValues.CAPTCHA_CHECK_PORTLET_MESSAGE_BOARDS_EDIT_MESSAGE) {

          CaptchaUtil.check(actionRequest);
        }

        if (threadId <= 0) {

          // Post new thread

          message =
              _mbMessageService.addMessage(
                  groupId,
                  categoryId,
                  subject,
                  body,
                  mbGroupServiceSettings.getMessageFormat(),
                  inputStreamOVPs,
                  anonymous,
                  priority,
                  allowPingbacks,
                  serviceContext);

          if (question) {
            _mbThreadLocalService.updateQuestion(message.getThreadId(), true);
          }
        } else {

          // Post reply

          message =
              _mbMessageService.addMessage(
                  parentMessageId,
                  subject,
                  body,
                  mbGroupServiceSettings.getMessageFormat(),
                  inputStreamOVPs,
                  anonymous,
                  priority,
                  allowPingbacks,
                  serviceContext);
        }
      } else {
        List<String> existingFiles = new ArrayList<>();

        for (int i = 1; i <= 5; i++) {
          String path = ParamUtil.getString(actionRequest, "existingPath" + i);

          if (Validator.isNotNull(path)) {
            existingFiles.add(path);
          }
        }

        // Update message

        message =
            _mbMessageService.updateMessage(
                messageId,
                subject,
                body,
                inputStreamOVPs,
                existingFiles,
                priority,
                allowPingbacks,
                serviceContext);

        if (message.isRoot()) {
          _mbThreadLocalService.updateQuestion(message.getThreadId(), question);
        }
      }

      PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();

      boolean subscribe = ParamUtil.getBoolean(actionRequest, "subscribe");

      if (!preview
          && subscribe
          && MBMessagePermission.contains(permissionChecker, message, ActionKeys.SUBSCRIBE)) {

        _mbMessageService.subscribeMessage(message.getMessageId());
      }

      return message;
    } finally {
      for (ObjectValuePair<String, InputStream> inputStreamOVP : inputStreamOVPs) {

        InputStream inputStream = inputStreamOVP.getValue();

        StreamUtil.cleanUp(inputStream);
      }
    }
  }
  protected void addUser(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);

    HttpSession session = request.getSession();

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

    Company company = themeDisplay.getCompany();

    boolean autoPassword = true;
    String password1 = null;
    String password2 = null;
    boolean autoScreenName = isAutoScreenName();
    String screenName = ParamUtil.getString(actionRequest, "screenName");
    String emailAddress = ParamUtil.getString(actionRequest, "emailAddress");
    long facebookId = ParamUtil.getLong(actionRequest, "facebookId");
    String openId = ParamUtil.getString(actionRequest, "openId");
    String languageId = ParamUtil.getString(actionRequest, "languageId");
    String firstName = ParamUtil.getString(actionRequest, "firstName");
    String middleName = ParamUtil.getString(actionRequest, "middleName");
    String lastName = ParamUtil.getString(actionRequest, "lastName");
    long prefixId = ParamUtil.getInteger(actionRequest, "prefixId");
    long suffixId = ParamUtil.getInteger(actionRequest, "suffixId");
    boolean male = ParamUtil.getBoolean(actionRequest, "male", true);
    int birthdayMonth = ParamUtil.getInteger(actionRequest, "birthdayMonth");
    int birthdayDay = ParamUtil.getInteger(actionRequest, "birthdayDay");
    int birthdayYear = ParamUtil.getInteger(actionRequest, "birthdayYear");
    String jobTitle = ParamUtil.getString(actionRequest, "jobTitle");
    long[] groupIds = null;
    long[] organizationIds = null;
    long[] roleIds = null;
    long[] userGroupIds = null;
    boolean sendEmail = true;

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(User.class.getName(), actionRequest);

    if (PropsValues.LOGIN_CREATE_ACCOUNT_ALLOW_CUSTOM_PASSWORD) {
      autoPassword = false;

      password1 = ParamUtil.getString(actionRequest, "password1");
      password2 = ParamUtil.getString(actionRequest, "password2");
    }

    boolean openIdPending = false;

    Boolean openIdLoginPending = (Boolean) session.getAttribute(WebKeys.OPEN_ID_LOGIN_PENDING);

    if ((openIdLoginPending != null)
        && openIdLoginPending.booleanValue()
        && Validator.isNotNull(openId)) {

      sendEmail = false;
      openIdPending = true;
    }

    User user =
        _userService.addUserWithWorkflow(
            company.getCompanyId(),
            autoPassword,
            password1,
            password2,
            autoScreenName,
            screenName,
            emailAddress,
            facebookId,
            openId,
            LocaleUtil.fromLanguageId(languageId),
            firstName,
            middleName,
            lastName,
            prefixId,
            suffixId,
            male,
            birthdayMonth,
            birthdayDay,
            birthdayYear,
            jobTitle,
            groupIds,
            organizationIds,
            roleIds,
            userGroupIds,
            sendEmail,
            serviceContext);

    if (openIdPending) {
      session.setAttribute(WebKeys.OPEN_ID_LOGIN, Long.valueOf(user.getUserId()));

      session.removeAttribute(WebKeys.OPEN_ID_LOGIN_PENDING);
    } else {

      // Session messages

      if (user.getStatus() == WorkflowConstants.STATUS_APPROVED) {
        SessionMessages.add(request, "userAdded", user.getEmailAddress());
        SessionMessages.add(request, "userAddedPassword", user.getPasswordUnencrypted());
      } else {
        SessionMessages.add(request, "userPending", user.getEmailAddress());
      }
    }

    // Send redirect

    sendRedirect(actionRequest, actionResponse, themeDisplay, user, user.getPasswordUnencrypted());
  }
  protected void updateIncompleteUser(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    HttpServletRequest request =
        PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(actionRequest));

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

    boolean autoPassword = true;
    String password1 = null;
    String password2 = null;
    boolean autoScreenName = false;
    String screenName = ParamUtil.getString(actionRequest, "screenName");
    String emailAddress = ParamUtil.getString(actionRequest, "emailAddress");

    HttpSession session = request.getSession();

    long facebookId = GetterUtil.getLong(session.getAttribute(WebKeys.FACEBOOK_INCOMPLETE_USER_ID));
    String googleUserId =
        GetterUtil.getString(session.getAttribute(WebKeys.GOOGLE_INCOMPLETE_USER_ID));

    if (Validator.isNotNull(googleUserId)) {
      autoPassword = false;
    }

    if ((facebookId > 0) || Validator.isNotNull(googleUserId)) {
      password1 = PwdGenerator.getPassword();
      password2 = password1;
    }

    String openId = ParamUtil.getString(actionRequest, "openId");
    String firstName = ParamUtil.getString(actionRequest, "firstName");
    String middleName = ParamUtil.getString(actionRequest, "middleName");
    String lastName = ParamUtil.getString(actionRequest, "lastName");
    long prefixId = ParamUtil.getInteger(actionRequest, "prefixId");
    long suffixId = ParamUtil.getInteger(actionRequest, "suffixId");
    boolean male = ParamUtil.getBoolean(actionRequest, "male", true);
    int birthdayMonth = ParamUtil.getInteger(actionRequest, "birthdayMonth");
    int birthdayDay = ParamUtil.getInteger(actionRequest, "birthdayDay");
    int birthdayYear = ParamUtil.getInteger(actionRequest, "birthdayYear");
    String jobTitle = ParamUtil.getString(actionRequest, "jobTitle");
    boolean updateUserInformation = true;

    boolean sendEmail = true;

    if (Validator.isNotNull(googleUserId)) {
      sendEmail = false;
    }

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(User.class.getName(), actionRequest);

    User user =
        _userService.updateIncompleteUser(
            themeDisplay.getCompanyId(),
            autoPassword,
            password1,
            password2,
            autoScreenName,
            screenName,
            emailAddress,
            facebookId,
            openId,
            themeDisplay.getLocale(),
            firstName,
            middleName,
            lastName,
            prefixId,
            suffixId,
            male,
            birthdayMonth,
            birthdayDay,
            birthdayYear,
            jobTitle,
            updateUserInformation,
            sendEmail,
            serviceContext);

    if (facebookId > 0) {
      session.removeAttribute(WebKeys.FACEBOOK_INCOMPLETE_USER_ID);

      updateUserAndSendRedirect(actionRequest, actionResponse, themeDisplay, user, password1);

      return;
    }

    if (Validator.isNotNull(googleUserId)) {
      _userLocalService.updateGoogleUserId(user.getUserId(), googleUserId);

      session.removeAttribute(WebKeys.GOOGLE_INCOMPLETE_USER_ID);

      updateUserAndSendRedirect(actionRequest, actionResponse, themeDisplay, user, password1);

      return;
    }

    // Session messages

    if (user.getStatus() == WorkflowConstants.STATUS_APPROVED) {
      SessionMessages.add(request, "userAdded", user.getEmailAddress());
      SessionMessages.add(request, "userAddedPassword", user.getPasswordUnencrypted());
    } else {
      SessionMessages.add(request, "userPending", user.getEmailAddress());
    }

    // Send redirect

    sendRedirect(actionRequest, actionResponse, themeDisplay, user, user.getPasswordUnencrypted());
  }
  public void editLayout(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

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

    long groupId = ParamUtil.getLong(actionRequest, "groupId");
    long liveGroupId = ParamUtil.getLong(actionRequest, "liveGroupId");
    long stagingGroupId = ParamUtil.getLong(actionRequest, "stagingGroupId");
    boolean privateLayout = ParamUtil.getBoolean(actionRequest, "privateLayout");
    long layoutId = ParamUtil.getLong(actionRequest, "layoutId");
    Map<Locale, String> nameMap = LocalizationUtil.getLocalizationMap(actionRequest, "name");
    Map<Locale, String> titleMap = LocalizationUtil.getLocalizationMap(actionRequest, "title");
    Map<Locale, String> descriptionMap =
        LocalizationUtil.getLocalizationMap(actionRequest, "description");
    Map<Locale, String> keywordsMap =
        LocalizationUtil.getLocalizationMap(actionRequest, "keywords");
    Map<Locale, String> robotsMap = LocalizationUtil.getLocalizationMap(actionRequest, "robots");
    String type = ParamUtil.getString(uploadPortletRequest, "type");
    boolean hidden = ParamUtil.getBoolean(uploadPortletRequest, "hidden");
    Map<Locale, String> friendlyURLMap =
        LocalizationUtil.getLocalizationMap(actionRequest, "friendlyURL");
    boolean deleteLogo = ParamUtil.getBoolean(actionRequest, "deleteLogo");

    byte[] iconBytes = null;

    long fileEntryId = ParamUtil.getLong(uploadPortletRequest, "fileEntryId");

    if (fileEntryId > 0) {
      FileEntry fileEntry = dlAppLocalService.getFileEntry(fileEntryId);

      iconBytes = FileUtil.getBytes(fileEntry.getContentStream());
    }

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(Layout.class.getName(), actionRequest);

    Layout layout = layoutLocalService.getLayout(groupId, privateLayout, layoutId);

    layout =
        layoutService.updateLayout(
            groupId,
            privateLayout,
            layoutId,
            layout.getParentLayoutId(),
            nameMap,
            titleMap,
            descriptionMap,
            keywordsMap,
            robotsMap,
            type,
            hidden,
            friendlyURLMap,
            !deleteLogo,
            iconBytes,
            serviceContext);

    UnicodeProperties layoutTypeSettingsProperties = layout.getTypeSettingsProperties();

    UnicodeProperties formTypeSettingsProperties =
        PropertiesParamUtil.getProperties(actionRequest, "TypeSettingsProperties--");

    LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

    if (type.equals(LayoutConstants.TYPE_PORTLET)) {
      String layoutTemplateId =
          ParamUtil.getString(
              uploadPortletRequest, "layoutTemplateId", PropsValues.DEFAULT_LAYOUT_TEMPLATE_ID);

      layoutTypePortlet.setLayoutTemplateId(themeDisplay.getUserId(), layoutTemplateId);

      layoutTypeSettingsProperties.putAll(formTypeSettingsProperties);

      layoutService.updateLayout(
          groupId, privateLayout, layoutId, layoutTypeSettingsProperties.toString());
    } else {
      layout.setTypeSettingsProperties(formTypeSettingsProperties);

      layoutTypeSettingsProperties.putAll(layout.getTypeSettingsProperties());

      layoutService.updateLayout(groupId, privateLayout, layoutId, layout.getTypeSettings());
    }

    HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);

    EventsProcessorUtil.process(
        PropsKeys.LAYOUT_CONFIGURATION_ACTION_UPDATE,
        layoutTypePortlet.getConfigurationActionUpdate(),
        uploadPortletRequest,
        response);

    updateLookAndFeel(
        actionRequest,
        themeDisplay.getCompanyId(),
        liveGroupId,
        stagingGroupId,
        privateLayout,
        layout.getLayoutId(),
        layoutTypeSettingsProperties);
  }
  public void addLayout(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

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

    long groupId = ParamUtil.getLong(actionRequest, "groupId");
    long liveGroupId = ParamUtil.getLong(actionRequest, "liveGroupId");
    long stagingGroupId = ParamUtil.getLong(actionRequest, "stagingGroupId");
    boolean privateLayout = ParamUtil.getBoolean(actionRequest, "privateLayout");
    long parentLayoutId = ParamUtil.getLong(uploadPortletRequest, "parentLayoutId");
    Map<Locale, String> nameMap = LocalizationUtil.getLocalizationMap(actionRequest, "name");
    Map<Locale, String> titleMap = LocalizationUtil.getLocalizationMap(actionRequest, "title");
    Map<Locale, String> descriptionMap =
        LocalizationUtil.getLocalizationMap(actionRequest, "description");
    Map<Locale, String> keywordsMap =
        LocalizationUtil.getLocalizationMap(actionRequest, "keywords");
    Map<Locale, String> robotsMap = LocalizationUtil.getLocalizationMap(actionRequest, "robots");
    String type = ParamUtil.getString(uploadPortletRequest, "type");
    boolean hidden = ParamUtil.getBoolean(uploadPortletRequest, "hidden");
    Map<Locale, String> friendlyURLMap =
        LocalizationUtil.getLocalizationMap(actionRequest, "friendlyURL");

    long layoutPrototypeId = ParamUtil.getLong(uploadPortletRequest, "layoutPrototypeId");

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(Layout.class.getName(), actionRequest);

    Layout layout = null;

    boolean inheritFromParentLayoutId =
        ParamUtil.getBoolean(uploadPortletRequest, "inheritFromParentLayoutId");

    UnicodeProperties typeSettingsProperties =
        PropertiesParamUtil.getProperties(actionRequest, "TypeSettingsProperties--");

    if (inheritFromParentLayoutId && (parentLayoutId > 0)) {
      Layout parentLayout = layoutLocalService.getLayout(groupId, privateLayout, parentLayoutId);

      layout =
          layoutService.addLayout(
              groupId,
              privateLayout,
              parentLayoutId,
              nameMap,
              titleMap,
              parentLayout.getDescriptionMap(),
              parentLayout.getKeywordsMap(),
              parentLayout.getRobotsMap(),
              parentLayout.getType(),
              parentLayout.getTypeSettings(),
              hidden,
              friendlyURLMap,
              serviceContext);

      inheritMobileRuleGroups(layout, serviceContext);

      if (parentLayout.isTypePortlet()) {
        ActionUtil.copyPreferences(actionRequest, layout, parentLayout);

        SitesUtil.copyLookAndFeel(layout, parentLayout);
      }
    } else if (layoutPrototypeId > 0) {
      LayoutPrototype layoutPrototype =
          layoutPrototypeService.getLayoutPrototype(layoutPrototypeId);

      boolean layoutPrototypeLinkEnabled =
          ParamUtil.getBoolean(
              uploadPortletRequest, "layoutPrototypeLinkEnabled" + layoutPrototype.getUuid());

      serviceContext.setAttribute("layoutPrototypeLinkEnabled", layoutPrototypeLinkEnabled);

      serviceContext.setAttribute("layoutPrototypeUuid", layoutPrototype.getUuid());

      layout =
          layoutService.addLayout(
              groupId,
              privateLayout,
              parentLayoutId,
              nameMap,
              titleMap,
              descriptionMap,
              keywordsMap,
              robotsMap,
              LayoutConstants.TYPE_PORTLET,
              typeSettingsProperties.toString(),
              hidden,
              friendlyURLMap,
              serviceContext);

      // Force propagation from page template to page.
      // See LPS-48430.

      SitesUtil.mergeLayoutPrototypeLayout(layout.getGroup(), layout);
    } else {
      long copyLayoutId = ParamUtil.getLong(uploadPortletRequest, "copyLayoutId");

      Layout copyLayout = null;

      String layoutTemplateId =
          ParamUtil.getString(
              uploadPortletRequest, "layoutTemplateId", PropsValues.DEFAULT_LAYOUT_TEMPLATE_ID);

      if (copyLayoutId > 0) {
        copyLayout = layoutLocalService.fetchLayout(groupId, privateLayout, copyLayoutId);

        if ((copyLayout != null) && copyLayout.isTypePortlet()) {
          LayoutTypePortlet copyLayoutTypePortlet = (LayoutTypePortlet) copyLayout.getLayoutType();

          layoutTemplateId = copyLayoutTypePortlet.getLayoutTemplateId();

          typeSettingsProperties = copyLayout.getTypeSettingsProperties();
        }
      }

      layout =
          layoutService.addLayout(
              groupId,
              privateLayout,
              parentLayoutId,
              nameMap,
              titleMap,
              descriptionMap,
              keywordsMap,
              robotsMap,
              type,
              typeSettingsProperties.toString(),
              hidden,
              friendlyURLMap,
              serviceContext);

      LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

      layoutTypePortlet.setLayoutTemplateId(themeDisplay.getUserId(), layoutTemplateId);

      layoutService.updateLayout(
          groupId, privateLayout, layout.getLayoutId(), layout.getTypeSettings());

      if ((copyLayout != null) && copyLayout.isTypePortlet()) {
        ActionUtil.copyPreferences(actionRequest, layout, copyLayout);

        SitesUtil.copyLookAndFeel(layout, copyLayout);
      }
    }

    updateLookAndFeel(
        actionRequest,
        themeDisplay.getCompanyId(),
        liveGroupId,
        stagingGroupId,
        privateLayout,
        layout.getLayoutId(),
        layout.getTypeSettingsProperties());
  }
  protected void updateCategory(ActionRequest actionRequest) throws Exception {

    long categoryId = ParamUtil.getLong(actionRequest, "mbCategoryId");

    long parentCategoryId = ParamUtil.getLong(actionRequest, "parentCategoryId");
    String name = ParamUtil.getString(actionRequest, "name");
    String description = ParamUtil.getString(actionRequest, "description");
    String displayStyle = ParamUtil.getString(actionRequest, "displayStyle");

    String emailAddress = ParamUtil.getString(actionRequest, "emailAddress");
    String inProtocol = ParamUtil.getString(actionRequest, "inProtocol");
    String inServerName = ParamUtil.getString(actionRequest, "inServerName");
    int inServerPort = ParamUtil.getInteger(actionRequest, "inServerPort");
    boolean inUseSSL = ParamUtil.getBoolean(actionRequest, "inUseSSL");
    String inUserName = ParamUtil.getString(actionRequest, "inUserName");
    String inPassword = ParamUtil.getString(actionRequest, "inPassword");
    int inReadInterval = ParamUtil.getInteger(actionRequest, "inReadInterval");
    String outEmailAddress = ParamUtil.getString(actionRequest, "outEmailAddress");
    boolean outCustom = ParamUtil.getBoolean(actionRequest, "outCustom");
    String outServerName = ParamUtil.getString(actionRequest, "outServerName");
    int outServerPort = ParamUtil.getInteger(actionRequest, "outServerPort");
    boolean outUseSSL = ParamUtil.getBoolean(actionRequest, "outUseSSL");
    String outUserName = ParamUtil.getString(actionRequest, "outUserName");
    String outPassword = ParamUtil.getString(actionRequest, "outPassword");
    boolean allowAnonymous = ParamUtil.getBoolean(actionRequest, "allowAnonymous");
    boolean mailingListActive = ParamUtil.getBoolean(actionRequest, "mailingListActive");

    boolean mergeWithParentCategory =
        ParamUtil.getBoolean(actionRequest, "mergeWithParentCategory");

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(MBCategory.class.getName(), actionRequest);

    if (categoryId <= 0) {
      if (PropsValues.CAPTCHA_CHECK_PORTLET_MESSAGE_BOARDS_EDIT_CATEGORY) {

        CaptchaUtil.check(actionRequest);
      }

      // Add category

      _mbCategoryService.addCategory(
          parentCategoryId,
          name,
          description,
          displayStyle,
          emailAddress,
          inProtocol,
          inServerName,
          inServerPort,
          inUseSSL,
          inUserName,
          inPassword,
          inReadInterval,
          outEmailAddress,
          outCustom,
          outServerName,
          outServerPort,
          outUseSSL,
          outUserName,
          outPassword,
          allowAnonymous,
          mailingListActive,
          serviceContext);
    } else {

      // Update category

      _mbCategoryService.updateCategory(
          categoryId,
          parentCategoryId,
          name,
          description,
          displayStyle,
          emailAddress,
          inProtocol,
          inServerName,
          inServerPort,
          inUseSSL,
          inUserName,
          inPassword,
          inReadInterval,
          outEmailAddress,
          outCustom,
          outServerName,
          outServerPort,
          outUseSSL,
          outUserName,
          outPassword,
          allowAnonymous,
          mailingListActive,
          mergeWithParentCategory,
          serviceContext);
    }
  }