@Override
  public PollsChoice addChoice(
      long userId, long questionId, String name, String description, ServiceContext serviceContext)
      throws PortalException {

    validate(name, description);

    User user = userPersistence.findByPrimaryKey(userId);
    Date now = new Date();

    long choiceId = counterLocalService.increment();

    PollsChoice choice = pollsChoicePersistence.create(choiceId);

    choice.setUuid(serviceContext.getUuid());
    choice.setGroupId(serviceContext.getScopeGroupId());
    choice.setCompanyId(user.getCompanyId());
    choice.setUserId(user.getUserId());
    choice.setUserName(user.getFullName());
    choice.setCreateDate(serviceContext.getCreateDate(now));
    choice.setModifiedDate(serviceContext.getModifiedDate(now));
    choice.setQuestionId(questionId);
    choice.setName(name);
    choice.setDescription(description);

    pollsChoicePersistence.update(choice);

    return choice;
  }
  @Override
  public MDRRuleGroup addRuleGroup(
      long groupId,
      Map<Locale, String> nameMap,
      Map<Locale, String> descriptionMap,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    User user = userPersistence.findByPrimaryKey(serviceContext.getUserId());
    Date now = new Date();

    long ruleGroupId = counterLocalService.increment();

    MDRRuleGroup ruleGroup = createMDRRuleGroup(ruleGroupId);

    ruleGroup.setUuid(serviceContext.getUuid());
    ruleGroup.setGroupId(groupId);
    ruleGroup.setCompanyId(serviceContext.getCompanyId());
    ruleGroup.setCreateDate(serviceContext.getCreateDate(now));
    ruleGroup.setModifiedDate(serviceContext.getModifiedDate(now));
    ruleGroup.setUserId(user.getUserId());
    ruleGroup.setUserName(user.getFullName());
    ruleGroup.setNameMap(nameMap);
    ruleGroup.setDescriptionMap(descriptionMap);

    return updateMDRRuleGroup(ruleGroup);
  }
  @Before
  public void setUp() throws Exception {
    ServiceTestUtil.setUser(TestPropsValues.getUser());

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext();

    _repository =
        RepositoryLocalServiceUtil.addRepository(
            TestPropsValues.getUserId(),
            TestPropsValues.getGroupId(),
            ClassNameLocalServiceUtil.getClassNameId(_REPOSITORY_CLASS_NAME),
            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
            StringUtil.randomString(),
            StringUtil.randomString(),
            StringUtil.randomString(),
            new UnicodeProperties(),
            true,
            serviceContext);

    _repositoryEntry =
        RepositoryEntryLocalServiceUtil.createRepositoryEntry(_repository.getDlFolderId());

    _repositoryEntry.setUuid(serviceContext.getUuid());
    _repositoryEntry.setGroupId(serviceContext.getScopeGroupId());
    _repositoryEntry.setCompanyId(serviceContext.getCompanyId());
    _repositoryEntry.setUserId(serviceContext.getUserId());
    _repositoryEntry.setUserName(StringUtil.randomString());
    _repositoryEntry.setCreateDate(serviceContext.getCreateDate(null));
    _repositoryEntry.setModifiedDate(serviceContext.getModifiedDate(null));
    _repositoryEntry.setRepositoryId(_repository.getRepositoryId());
    _repositoryEntry.setMappedId(_MAPPED_ID);

    RepositoryEntryLocalServiceUtil.addRepositoryEntry(_repositoryEntry);
  }
  @Override
  public KBComment addKBComment(
      long userId,
      long classNameId,
      long classPK,
      String content,
      boolean helpful,
      ServiceContext serviceContext)
      throws PortalException {

    // KB comment

    User user = userPersistence.findByPrimaryKey(userId);
    long groupId = serviceContext.getScopeGroupId();
    Date now = new Date();

    validate(content);

    long kbCommentId = counterLocalService.increment();

    KBComment kbComment = kbCommentPersistence.create(kbCommentId);

    kbComment.setUuid(serviceContext.getUuid());
    kbComment.setGroupId(groupId);
    kbComment.setCompanyId(user.getCompanyId());
    kbComment.setUserId(user.getUserId());
    kbComment.setUserName(user.getFullName());
    kbComment.setCreateDate(serviceContext.getCreateDate(now));
    kbComment.setModifiedDate(serviceContext.getModifiedDate(now));
    kbComment.setClassNameId(classNameId);
    kbComment.setClassPK(classPK);
    kbComment.setContent(content);
    kbComment.setHelpful(helpful);
    kbComment.setStatus(KBCommentConstants.STATUS_NEW);

    kbCommentPersistence.update(kbComment);

    // Social

    JSONObject extraDataJSONObject = JSONFactoryUtil.createJSONObject();

    putTitle(extraDataJSONObject, kbComment);

    socialActivityLocalService.addActivity(
        userId,
        kbComment.getGroupId(),
        KBComment.class.getName(),
        kbCommentId,
        AdminActivityKeys.ADD_KB_COMMENT,
        extraDataJSONObject.toString(),
        0);

    // Subscriptions

    notifySubscribers(kbComment, serviceContext);

    return kbComment;
  }
  @Indexable(type = IndexableType.REINDEX)
  @Override
  public AssetVocabulary addVocabulary(
      long userId,
      long groupId,
      String title,
      Map<Locale, String> titleMap,
      Map<Locale, String> descriptionMap,
      String settings,
      ServiceContext serviceContext)
      throws PortalException {

    // Vocabulary

    User user = userPersistence.findByPrimaryKey(userId);
    String name = titleMap.get(LocaleUtil.getSiteDefault());

    validate(groupId, name);

    long vocabularyId = counterLocalService.increment();

    AssetVocabulary vocabulary = assetVocabularyPersistence.create(vocabularyId);

    vocabulary.setUuid(serviceContext.getUuid());
    vocabulary.setGroupId(groupId);
    vocabulary.setCompanyId(user.getCompanyId());
    vocabulary.setUserId(user.getUserId());
    vocabulary.setUserName(user.getFullName());
    vocabulary.setName(name);

    if (Validator.isNotNull(title)) {
      vocabulary.setTitle(title);
    } else {
      vocabulary.setTitleMap(titleMap);
    }

    vocabulary.setDescriptionMap(descriptionMap);
    vocabulary.setSettings(settings);

    assetVocabularyPersistence.update(vocabulary);

    // Resources

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {

      addVocabularyResources(
          vocabulary,
          serviceContext.isAddGroupPermissions(),
          serviceContext.isAddGuestPermissions());
    } else {
      addVocabularyResources(
          vocabulary, serviceContext.getGroupPermissions(), serviceContext.getGuestPermissions());
    }

    return vocabulary;
  }
  @Override
  public KBTemplate addKBTemplate(
      long userId, String title, String content, ServiceContext serviceContext)
      throws PortalException {

    // KB template

    User user = userPersistence.findByPrimaryKey(userId);
    long groupId = serviceContext.getScopeGroupId();
    Date now = new Date();

    validate(title, content);

    long kbTemplateId = counterLocalService.increment();

    KBTemplate kbTemplate = kbTemplatePersistence.create(kbTemplateId);

    kbTemplate.setUuid(serviceContext.getUuid());
    kbTemplate.setGroupId(groupId);
    kbTemplate.setCompanyId(user.getCompanyId());
    kbTemplate.setUserId(user.getUserId());
    kbTemplate.setUserName(user.getFullName());
    kbTemplate.setCreateDate(serviceContext.getCreateDate(now));
    kbTemplate.setModifiedDate(serviceContext.getModifiedDate(now));
    kbTemplate.setTitle(title);
    kbTemplate.setContent(content);

    kbTemplatePersistence.update(kbTemplate);

    // Resources

    resourceLocalService.addModelResources(kbTemplate, serviceContext);

    // Social

    JSONObject extraDataJSONObject = JSONFactoryUtil.createJSONObject();

    extraDataJSONObject.put("title", kbTemplate.getTitle());

    socialActivityLocalService.addActivity(
        userId,
        groupId,
        KBTemplate.class.getName(),
        kbTemplateId,
        AdminActivityKeys.ADD_KB_TEMPLATE,
        extraDataJSONObject.toString(),
        0);

    return kbTemplate;
  }
  public JournalStructure addStructure(
      long userId,
      long groupId,
      String structureId,
      boolean autoStructureId,
      String parentStructureId,
      String name,
      String description,
      String xsd,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Structure

    User user = userPersistence.findByPrimaryKey(userId);
    structureId = structureId.trim().toUpperCase();
    Date now = new Date();

    try {
      xsd = JournalUtil.formatXML(xsd);
    } catch (Exception e) {
      throw new StructureXsdException();
    }

    if (autoStructureId) {
      structureId = String.valueOf(counterLocalService.increment());
    }

    validate(groupId, structureId, autoStructureId, parentStructureId, name, description, xsd);

    long id = counterLocalService.increment();

    JournalStructure structure = journalStructurePersistence.create(id);

    structure.setUuid(serviceContext.getUuid());
    structure.setGroupId(groupId);
    structure.setCompanyId(user.getCompanyId());
    structure.setUserId(user.getUserId());
    structure.setUserName(user.getFullName());
    structure.setCreateDate(serviceContext.getCreateDate(now));
    structure.setModifiedDate(serviceContext.getModifiedDate(now));
    structure.setStructureId(structureId);
    structure.setParentStructureId(parentStructureId);
    structure.setName(name);
    structure.setDescription(description);
    structure.setXsd(xsd);

    journalStructurePersistence.update(structure, false);

    // Resources

    if (serviceContext.getAddCommunityPermissions() || serviceContext.getAddGuestPermissions()) {

      addStructureResources(
          structure,
          serviceContext.getAddCommunityPermissions(),
          serviceContext.getAddGuestPermissions());
    } else {
      addStructureResources(
          structure,
          serviceContext.getCommunityPermissions(),
          serviceContext.getGuestPermissions());
    }

    // Expando

    ExpandoBridge expandoBridge = structure.getExpandoBridge();

    expandoBridge.setAttributes(serviceContext);

    return structure;
  }
  /**
   * Adds a user group.
   *
   * <p>This method handles the creation and bookkeeping of the user group, including its resources,
   * metadata, and internal data structures. It is not necessary to make subsequent calls to setup
   * default groups and resources for the user group.
   *
   * @param userId the primary key of the user
   * @param companyId the primary key of the user group's company
   * @param name the user group's name
   * @param description the user group's description
   * @param serviceContext the service context to be applied (optionally <code>null</code>). Can set
   *     expando bridge attributes for the user group.
   * @return the user group
   */
  @Override
  public UserGroup addUserGroup(
      long userId, long companyId, String name, String description, ServiceContext serviceContext)
      throws PortalException {

    // User group

    validate(0, companyId, name);

    User user = userPersistence.findByPrimaryKey(userId);

    long userGroupId = counterLocalService.increment();

    UserGroup userGroup = userGroupPersistence.create(userGroupId);

    if (serviceContext != null) {
      userGroup.setUuid(serviceContext.getUuid());
    }

    userGroup.setCompanyId(companyId);
    userGroup.setUserId(user.getUserId());
    userGroup.setUserName(user.getFullName());
    userGroup.setParentUserGroupId(UserGroupConstants.DEFAULT_PARENT_USER_GROUP_ID);
    userGroup.setName(name);
    userGroup.setDescription(description);
    userGroup.setAddedByLDAPImport(UserGroupImportTransactionThreadLocal.isOriginatesFromImport());
    userGroup.setExpandoBridgeAttributes(serviceContext);

    userGroupPersistence.update(userGroup);

    // Group

    groupLocalService.addGroup(
        userId,
        GroupConstants.DEFAULT_PARENT_GROUP_ID,
        UserGroup.class.getName(),
        userGroup.getUserGroupId(),
        GroupConstants.DEFAULT_LIVE_GROUP_ID,
        getLocalizationMap(String.valueOf(userGroupId)),
        null,
        0,
        true,
        GroupConstants.DEFAULT_MEMBERSHIP_RESTRICTION,
        null,
        false,
        true,
        null);

    // Resources

    resourceLocalService.addResources(
        companyId,
        0,
        userId,
        UserGroup.class.getName(),
        userGroup.getUserGroupId(),
        false,
        false,
        false);

    // Indexer

    Indexer<UserGroup> indexer = IndexerRegistryUtil.nullSafeGetIndexer(UserGroup.class);

    indexer.reindex(userGroup);

    return userGroup;
  }
  public DLFileEntryType addFileEntryType(
      long userId,
      long groupId,
      String name,
      String description,
      long[] ddmStructureIds,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    User user = userPersistence.findByPrimaryKey(userId);

    String fileEntryTypeUuid = serviceContext.getUuid();

    if (Validator.isNull(fileEntryTypeUuid)) {
      fileEntryTypeUuid = PortalUUIDUtil.generate();
    }

    long fileEntryTypeId = counterLocalService.increment();

    long ddmStructureId =
        updateDDMStructure(
            userId, fileEntryTypeUuid, fileEntryTypeId, groupId, name, description, serviceContext);

    if (ddmStructureId > 0) {
      ddmStructureIds = ArrayUtil.append(ddmStructureIds, ddmStructureId);
    }

    Date now = new Date();

    validate(fileEntryTypeId, groupId, name, ddmStructureIds);

    DLFileEntryType dlFileEntryType = dlFileEntryTypePersistence.create(fileEntryTypeId);

    dlFileEntryType.setUuid(fileEntryTypeUuid);
    dlFileEntryType.setGroupId(groupId);
    dlFileEntryType.setCompanyId(user.getCompanyId());
    dlFileEntryType.setUserId(user.getUserId());
    dlFileEntryType.setUserName(user.getFullName());
    dlFileEntryType.setCreateDate(serviceContext.getCreateDate(now));
    dlFileEntryType.setModifiedDate(serviceContext.getModifiedDate(now));
    dlFileEntryType.setName(name);
    dlFileEntryType.setDescription(description);

    dlFileEntryTypePersistence.update(dlFileEntryType);

    dlFileEntryTypePersistence.addDDMStructures(fileEntryTypeId, ddmStructureIds);

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {

      addFileEntryTypeResources(
          dlFileEntryType,
          serviceContext.isAddGroupPermissions(),
          serviceContext.isAddGuestPermissions());
    } else {
      addFileEntryTypeResources(
          dlFileEntryType,
          serviceContext.getGroupPermissions(),
          serviceContext.getGuestPermissions());
    }

    return dlFileEntryType;
  }
  public JournalTemplate addTemplate(
      long userId,
      long groupId,
      String templateId,
      boolean autoTemplateId,
      String structureId,
      Map<Locale, String> nameMap,
      Map<Locale, String> descriptionMap,
      String xsl,
      boolean formatXsl,
      String langType,
      boolean cacheable,
      boolean smallImage,
      String smallImageURL,
      File smallImageFile,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Template

    User user = userPersistence.findByPrimaryKey(userId);
    templateId = templateId.trim().toUpperCase();
    Date now = new Date();

    try {
      if (formatXsl) {
        if (langType.equals(JournalTemplateConstants.LANG_TYPE_VM)) {
          xsl = JournalUtil.formatVM(xsl);
        } else {
          xsl = DDMXMLUtil.formatXML(xsl);
        }
      }
    } catch (Exception e) {
      throw new TemplateXslException();
    }

    byte[] smallImageBytes = null;

    try {
      smallImageBytes = FileUtil.getBytes(smallImageFile);
    } catch (IOException ioe) {
    }

    validate(
        groupId,
        templateId,
        autoTemplateId,
        nameMap,
        xsl,
        smallImage,
        smallImageURL,
        smallImageFile,
        smallImageBytes);

    if (autoTemplateId) {
      templateId = String.valueOf(counterLocalService.increment());
    }

    long id = counterLocalService.increment();

    JournalTemplate template = journalTemplatePersistence.create(id);

    template.setUuid(serviceContext.getUuid());
    template.setGroupId(groupId);
    template.setCompanyId(user.getCompanyId());
    template.setUserId(user.getUserId());
    template.setUserName(user.getFullName());
    template.setCreateDate(serviceContext.getCreateDate(now));
    template.setModifiedDate(serviceContext.getModifiedDate(now));
    template.setTemplateId(templateId);
    template.setStructureId(structureId);
    template.setNameMap(nameMap);
    template.setDescriptionMap(descriptionMap);
    template.setXsl(xsl);
    template.setLangType(langType);
    template.setCacheable(cacheable);
    template.setSmallImage(smallImage);
    template.setSmallImageId(counterLocalService.increment());
    template.setSmallImageURL(smallImageURL);

    journalTemplatePersistence.update(template, false);

    // Resources

    if (serviceContext.getAddGroupPermissions() || serviceContext.getAddGuestPermissions()) {

      addTemplateResources(
          template,
          serviceContext.getAddGroupPermissions(),
          serviceContext.getAddGuestPermissions());
    } else {
      addTemplateResources(
          template, serviceContext.getGroupPermissions(), serviceContext.getGuestPermissions());
    }

    // Expando

    ExpandoBridge expandoBridge = template.getExpandoBridge();

    expandoBridge.setAttributes(serviceContext);

    // Small image

    saveImages(smallImage, template.getSmallImageId(), smallImageFile, smallImageBytes);

    return template;
  }
  @Override
  public MBCategory addCategory(
      long userId,
      long parentCategoryId,
      String name,
      String description,
      String displayStyle,
      String emailAddress,
      String inProtocol,
      String inServerName,
      int inServerPort,
      boolean inUseSSL,
      String inUserName,
      String inPassword,
      int inReadInterval,
      String outEmailAddress,
      boolean outCustom,
      String outServerName,
      int outServerPort,
      boolean outUseSSL,
      String outUserName,
      String outPassword,
      boolean allowAnonymous,
      boolean mailingListActive,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Category

    User user = userPersistence.findByPrimaryKey(userId);
    long groupId = serviceContext.getScopeGroupId();
    parentCategoryId = getParentCategoryId(groupId, parentCategoryId);
    Date now = new Date();

    validate(name);

    long categoryId = counterLocalService.increment();

    MBCategory category = mbCategoryPersistence.create(categoryId);

    category.setUuid(serviceContext.getUuid());
    category.setGroupId(groupId);
    category.setCompanyId(user.getCompanyId());
    category.setUserId(user.getUserId());
    category.setUserName(user.getFullName());
    category.setCreateDate(serviceContext.getCreateDate(now));
    category.setModifiedDate(serviceContext.getModifiedDate(now));
    category.setParentCategoryId(parentCategoryId);
    category.setName(name);
    category.setDescription(description);
    category.setDisplayStyle(displayStyle);
    category.setExpandoBridgeAttributes(serviceContext);

    mbCategoryPersistence.update(category);

    // Resources

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {

      addCategoryResources(
          category, serviceContext.isAddGroupPermissions(), serviceContext.isAddGuestPermissions());
    } else {
      addCategoryResources(
          category, serviceContext.getGroupPermissions(), serviceContext.getGuestPermissions());
    }

    // Mailing list

    mbMailingListLocalService.addMailingList(
        userId,
        groupId,
        category.getCategoryId(),
        emailAddress,
        inProtocol,
        inServerName,
        inServerPort,
        inUseSSL,
        inUserName,
        inPassword,
        inReadInterval,
        outEmailAddress,
        outCustom,
        outServerName,
        outServerPort,
        outUseSSL,
        outUserName,
        outPassword,
        allowAnonymous,
        mailingListActive,
        serviceContext);

    return category;
  }
  @Override
  public CalendarResource addCalendarResource(
      long userId,
      long groupId,
      long classNameId,
      long classPK,
      String classUuid,
      String code,
      Map<Locale, String> nameMap,
      Map<Locale, String> descriptionMap,
      boolean active,
      ServiceContext serviceContext)
      throws PortalException {

    // Calendar resource

    User user = userPersistence.findByPrimaryKey(userId);

    long calendarResourceId = counterLocalService.increment();

    if (classNameId == classNameLocalService.getClassNameId(CalendarResource.class)) {

      classPK = calendarResourceId;
    }

    if (PortletPropsValues.CALENDAR_RESOURCE_FORCE_AUTOGENERATE_CODE || Validator.isNull(code)) {

      code = String.valueOf(calendarResourceId);
    } else {
      code = code.trim();
      code = StringUtil.toUpperCase(code);
    }

    Date now = new Date();

    validate(groupId, classNameId, classPK, code, nameMap);

    CalendarResource calendarResource = calendarResourcePersistence.create(calendarResourceId);

    calendarResource.setUuid(serviceContext.getUuid());
    calendarResource.setGroupId(groupId);
    calendarResource.setCompanyId(user.getCompanyId());
    calendarResource.setUserId(user.getUserId());
    calendarResource.setUserName(user.getFullName());
    calendarResource.setCreateDate(serviceContext.getCreateDate(now));
    calendarResource.setModifiedDate(serviceContext.getModifiedDate(now));
    calendarResource.setClassNameId(classNameId);
    calendarResource.setClassPK(classPK);
    calendarResource.setClassUuid(classUuid);
    calendarResource.setCode(code);
    calendarResource.setNameMap(nameMap);
    calendarResource.setDescriptionMap(descriptionMap);
    calendarResource.setActive(active);

    calendarResourcePersistence.update(calendarResource);

    // Resources

    resourceLocalService.addModelResources(calendarResource, serviceContext);

    // Calendar

    if (!ExportImportThreadLocal.isImportInProcess()) {
      serviceContext.setAddGroupPermissions(true);
      serviceContext.setAddGuestPermissions(true);

      calendarLocalService.addCalendar(
          userId,
          calendarResource.getGroupId(),
          calendarResourceId,
          nameMap,
          descriptionMap,
          calendarResource.getTimeZoneId(),
          PortletPropsValues.CALENDAR_COLOR_DEFAULT,
          true,
          false,
          false,
          serviceContext);
    }

    // Asset

    updateAsset(
        calendarResource.getUserId(),
        calendarResource,
        serviceContext.getAssetCategoryIds(),
        serviceContext.getAssetTagNames());

    return calendarResource;
  }
  @Override
  public DLFileEntryType addFileEntryType(
      long userId,
      long groupId,
      String fileEntryTypeKey,
      Map<Locale, String> nameMap,
      Map<Locale, String> descriptionMap,
      long[] ddmStructureIds,
      ServiceContext serviceContext)
      throws PortalException {

    User user = userPersistence.findByPrimaryKey(userId);

    if (Validator.isNull(fileEntryTypeKey)) {
      fileEntryTypeKey = String.valueOf(counterLocalService.increment());
    } else {
      fileEntryTypeKey = StringUtil.toUpperCase(fileEntryTypeKey.trim());
    }

    String fileEntryTypeUuid = serviceContext.getUuid();

    if (Validator.isNull(fileEntryTypeUuid)) {
      fileEntryTypeUuid = PortalUUIDUtil.generate();
    }

    long fileEntryTypeId = counterLocalService.increment();

    long ddmStructureId =
        updateDDMStructure(
            userId,
            fileEntryTypeUuid,
            fileEntryTypeId,
            groupId,
            nameMap,
            descriptionMap,
            serviceContext);

    if (ddmStructureId > 0) {
      ddmStructureIds = ArrayUtil.append(ddmStructureIds, ddmStructureId);
    }

    validate(fileEntryTypeId, groupId, fileEntryTypeKey, ddmStructureIds);

    DLFileEntryType dlFileEntryType = dlFileEntryTypePersistence.create(fileEntryTypeId);

    dlFileEntryType.setUuid(fileEntryTypeUuid);
    dlFileEntryType.setGroupId(groupId);
    dlFileEntryType.setCompanyId(user.getCompanyId());
    dlFileEntryType.setUserId(user.getUserId());
    dlFileEntryType.setUserName(user.getFullName());
    dlFileEntryType.setFileEntryTypeKey(fileEntryTypeKey);
    dlFileEntryType.setNameMap(nameMap);
    dlFileEntryType.setDescriptionMap(descriptionMap);

    dlFileEntryTypePersistence.update(dlFileEntryType);

    addDDMStructureLinks(fileEntryTypeId, SetUtil.fromArray(ddmStructureIds));

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {

      addFileEntryTypeResources(
          dlFileEntryType,
          serviceContext.isAddGroupPermissions(),
          serviceContext.isAddGuestPermissions());
    } else {
      addFileEntryTypeResources(
          dlFileEntryType,
          serviceContext.getGroupPermissions(),
          serviceContext.getGuestPermissions());
    }

    return dlFileEntryType;
  }
  @Indexable(type = IndexableType.REINDEX)
  @Override
  public AssetCategory addCategory(
      long userId,
      long parentCategoryId,
      Map<Locale, String> titleMap,
      Map<Locale, String> descriptionMap,
      long vocabularyId,
      String[] categoryProperties,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Category

    User user = userPersistence.findByPrimaryKey(userId);
    long groupId = serviceContext.getScopeGroupId();

    String name = titleMap.get(LocaleUtil.getSiteDefault());

    name = ModelHintsUtil.trimString(AssetCategory.class.getName(), "name", name);

    if (categoryProperties == null) {
      categoryProperties = new String[0];
    }

    Date now = new Date();

    validate(0, parentCategoryId, name, vocabularyId);

    if (parentCategoryId > 0) {
      assetCategoryPersistence.findByPrimaryKey(parentCategoryId);
    }

    assetVocabularyPersistence.findByPrimaryKey(vocabularyId);

    long categoryId = counterLocalService.increment();

    AssetCategory category = assetCategoryPersistence.create(categoryId);

    category.setUuid(serviceContext.getUuid());
    category.setGroupId(groupId);
    category.setCompanyId(user.getCompanyId());
    category.setUserId(user.getUserId());
    category.setUserName(user.getFullName());
    category.setCreateDate(now);
    category.setModifiedDate(now);
    category.setParentCategoryId(parentCategoryId);
    category.setName(name);
    category.setTitleMap(titleMap);
    category.setDescriptionMap(descriptionMap);
    category.setVocabularyId(vocabularyId);

    assetCategoryPersistence.update(category);

    // Resources

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {

      addCategoryResources(
          category, serviceContext.isAddGroupPermissions(), serviceContext.isAddGuestPermissions());
    } else {
      addCategoryResources(
          category, serviceContext.getGroupPermissions(), serviceContext.getGuestPermissions());
    }

    // Properties

    for (int i = 0; i < categoryProperties.length; i++) {
      String[] categoryProperty =
          StringUtil.split(
              categoryProperties[i], AssetCategoryConstants.PROPERTY_KEY_VALUE_SEPARATOR);

      if (categoryProperty.length <= 1) {
        categoryProperty = StringUtil.split(categoryProperties[i], CharPool.COLON);
      }

      String key = StringPool.BLANK;
      String value = StringPool.BLANK;

      if (categoryProperty.length > 1) {
        key = GetterUtil.getString(categoryProperty[0]);
        value = GetterUtil.getString(categoryProperty[1]);
      }

      if (Validator.isNotNull(key)) {
        assetCategoryPropertyLocalService.addCategoryProperty(userId, categoryId, key, value);
      }
    }

    return category;
  }
  @Override
  public JournalFeed addFeed(
      long userId,
      long groupId,
      String feedId,
      boolean autoFeedId,
      String name,
      String description,
      String type,
      String structureId,
      String templateId,
      String rendererTemplateId,
      int delta,
      String orderByCol,
      String orderByType,
      String targetLayoutFriendlyUrl,
      String targetPortletId,
      String contentField,
      String feedFormat,
      double feedVersion,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Feed

    User user = userPersistence.findByPrimaryKey(userId);
    feedId = StringUtil.toUpperCase(feedId.trim());
    Date now = new Date();

    validate(
        user.getCompanyId(),
        groupId,
        feedId,
        autoFeedId,
        name,
        structureId,
        targetLayoutFriendlyUrl,
        contentField);

    if (autoFeedId) {
      feedId = String.valueOf(counterLocalService.increment());
    }

    long id = counterLocalService.increment();

    JournalFeed feed = journalFeedPersistence.create(id);

    feed.setUuid(serviceContext.getUuid());
    feed.setGroupId(groupId);
    feed.setCompanyId(user.getCompanyId());
    feed.setUserId(user.getUserId());
    feed.setUserName(user.getFullName());
    feed.setCreateDate(serviceContext.getCreateDate(now));
    feed.setModifiedDate(serviceContext.getModifiedDate(now));
    feed.setFeedId(feedId);
    feed.setName(name);
    feed.setDescription(description);
    feed.setType(type);
    feed.setStructureId(structureId);
    feed.setTemplateId(templateId);
    feed.setRendererTemplateId(rendererTemplateId);
    feed.setDelta(delta);
    feed.setOrderByCol(orderByCol);
    feed.setOrderByType(orderByType);
    feed.setTargetLayoutFriendlyUrl(targetLayoutFriendlyUrl);
    feed.setTargetPortletId(targetPortletId);
    feed.setContentField(contentField);

    if (Validator.isNull(feedFormat)) {
      feed.setFeedFormat(RSSUtil.FORMAT_DEFAULT);
      feed.setFeedVersion(RSSUtil.VERSION_DEFAULT);
    } else {
      feed.setFeedFormat(feedFormat);
      feed.setFeedVersion(feedVersion);
    }

    feed.setExpandoBridgeAttributes(serviceContext);

    journalFeedPersistence.update(feed);

    // Resources

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {

      addFeedResources(
          feed, serviceContext.isAddGroupPermissions(), serviceContext.isAddGuestPermissions());
    } else {
      addFeedResources(
          feed, serviceContext.getGroupPermissions(), serviceContext.getGuestPermissions());
    }

    return feed;
  }
  @Indexable(type = IndexableType.REINDEX)
  public Album addAlbum(
      long userId,
      long artistId,
      String name,
      int year,
      InputStream inputStream,
      ServiceContext serviceContext)
      throws PortalException {

    long groupId = serviceContext.getScopeGroupId();

    User user = userPersistence.findByPrimaryKey(userId);

    Date now = new Date();

    validate(name);

    long albumId = counterLocalService.increment();

    Album album = albumPersistence.create(albumId);

    album.setUuid(serviceContext.getUuid());
    album.setGroupId(groupId);
    album.setCompanyId(user.getCompanyId());
    album.setUserId(user.getUserId());
    album.setUserName(user.getFullName());
    album.setCreateDate(serviceContext.getCreateDate(now));
    album.setModifiedDate(serviceContext.getModifiedDate(now));
    album.setArtistId(artistId);
    album.setName(name);
    album.setYear(year);
    album.setExpandoBridgeAttributes(serviceContext);

    albumPersistence.update(album);

    if (inputStream != null) {
      PortletFileRepositoryUtil.addPortletFileEntry(
          groupId,
          userId,
          Album.class.getName(),
          album.getAlbumId(),
          Constants.JUKEBOX_PORTLET_REPOSITORY,
          DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
          inputStream,
          String.valueOf(album.getAlbumId()),
          StringPool.BLANK,
          true);
    }

    // Resources

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {

      addEntryResources(
          album, serviceContext.isAddGroupPermissions(), serviceContext.isAddGuestPermissions());
    } else {
      addEntryResources(
          album, serviceContext.getGroupPermissions(), serviceContext.getGuestPermissions());
    }

    // Message boards

    mbMessageLocalService.addDiscussionMessage(
        userId,
        album.getUserName(),
        groupId,
        Album.class.getName(),
        albumId,
        WorkflowConstants.ACTION_PUBLISH);

    // Asset

    updateAsset(
        userId,
        album,
        serviceContext.getAssetCategoryIds(),
        serviceContext.getAssetTagNames(),
        serviceContext.getAssetLinkEntryIds());

    return album;
  }
  public CalendarBooking addCalendarBooking(
      long userId,
      long calendarId,
      long[] childCalendarIds,
      long parentCalendarBookingId,
      Map<Locale, String> titleMap,
      Map<Locale, String> descriptionMap,
      String location,
      long startDate,
      long endDate,
      boolean allDay,
      String recurrence,
      long firstReminder,
      String firstReminderType,
      long secondReminder,
      String secondReminderType,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Calendar booking

    User user = userPersistence.findByPrimaryKey(userId);
    Calendar calendar = calendarPersistence.findByPrimaryKey(calendarId);

    java.util.Calendar startDateJCalendar = JCalendarUtil.getJCalendar(startDate);
    java.util.Calendar endDateJCalendar = JCalendarUtil.getJCalendar(endDate);

    if (allDay) {
      startDateJCalendar = JCalendarUtil.toMidnightJCalendar(startDateJCalendar);
      endDateJCalendar = JCalendarUtil.toLastHourJCalendar(endDateJCalendar);
    }

    if (firstReminder < secondReminder) {
      long originalSecondReminder = secondReminder;

      secondReminder = firstReminder;
      firstReminder = originalSecondReminder;
    }

    Date now = new Date();

    validate(titleMap, startDateJCalendar, endDateJCalendar);

    long calendarBookingId = counterLocalService.increment();

    CalendarBooking calendarBooking = calendarBookingPersistence.create(calendarBookingId);

    calendarBooking.setUuid(serviceContext.getUuid());
    calendarBooking.setGroupId(calendar.getGroupId());
    calendarBooking.setCompanyId(user.getCompanyId());
    calendarBooking.setUserId(user.getUserId());
    calendarBooking.setUserName(user.getFullName());
    calendarBooking.setCreateDate(serviceContext.getCreateDate(now));
    calendarBooking.setModifiedDate(serviceContext.getModifiedDate(now));
    calendarBooking.setCalendarId(calendarId);
    calendarBooking.setCalendarResourceId(calendar.getCalendarResourceId());

    if (parentCalendarBookingId > 0) {
      calendarBooking.setParentCalendarBookingId(parentCalendarBookingId);
    } else {
      calendarBooking.setParentCalendarBookingId(calendarBookingId);
    }

    calendarBooking.setTitleMap(titleMap);
    calendarBooking.setDescriptionMap(descriptionMap);
    calendarBooking.setLocation(location);
    calendarBooking.setStartDate(startDateJCalendar.getTimeInMillis());
    calendarBooking.setEndDate(endDateJCalendar.getTimeInMillis());
    calendarBooking.setAllDay(allDay);
    calendarBooking.setRecurrence(recurrence);
    calendarBooking.setFirstReminder(firstReminder);
    calendarBooking.setFirstReminderType(firstReminderType);
    calendarBooking.setSecondReminder(secondReminder);
    calendarBooking.setSecondReminderType(secondReminderType);

    int status = CalendarBookingWorkflowConstants.STATUS_PENDING;

    if (parentCalendarBookingId == 0) {
      status = CalendarBookingWorkflowConstants.STATUS_APPROVED;
    }

    calendarBooking.setStatus(status);

    calendarBooking.setStatusDate(serviceContext.getModifiedDate(now));

    calendarBookingPersistence.update(calendarBooking, false);

    addChildCalendarBookings(calendarBooking, childCalendarIds, serviceContext);

    // Workflow

    calendarBookingApprovalWorkflow.startWorkflow(userId, calendarBookingId, serviceContext);

    return calendarBooking;
  }
Пример #18
0
  public void merge(ServiceContext serviceContext) {
    setAddGroupPermissions(serviceContext.isAddGroupPermissions());
    setAddGuestPermissions(serviceContext.isAddGuestPermissions());

    if (serviceContext.getAssetCategoryIds() != null) {
      setAssetCategoryIds(serviceContext.getAssetCategoryIds());
    }

    if (serviceContext.getAssetLinkEntryIds() != null) {
      setAssetLinkEntryIds(serviceContext.getAssetLinkEntryIds());
    }

    if (serviceContext.getAssetTagNames() != null) {
      setAssetTagNames(serviceContext.getAssetTagNames());
    }

    if (serviceContext.getAttributes() != null) {
      setAttributes(serviceContext.getAttributes());
    }

    if (Validator.isNotNull(serviceContext.getCommand())) {
      setCommand(serviceContext.getCommand());
    }

    if (serviceContext.getCompanyId() > 0) {
      setCompanyId(serviceContext.getCompanyId());
    }

    if (serviceContext.getCreateDate() != null) {
      setCreateDate(serviceContext.getCreateDate());
    }

    if (Validator.isNotNull(serviceContext.getCurrentURL())) {
      setCurrentURL(serviceContext.getCurrentURL());
    }

    if (serviceContext.getExpandoBridgeAttributes() != null) {
      setExpandoBridgeAttributes(serviceContext.getExpandoBridgeAttributes());
    }

    if (serviceContext.getGroupPermissions() != null) {
      setGroupPermissions(serviceContext.getGroupPermissions());
    }

    if (serviceContext.getGuestPermissions() != null) {
      setGuestPermissions(serviceContext.getGuestPermissions());
    }

    if (serviceContext.getHeaders() != null) {
      setHeaders(serviceContext.getHeaders());
    }

    setFailOnPortalException(serviceContext.isFailOnPortalException());
    setLanguageId(serviceContext.getLanguageId());

    if (Validator.isNotNull(serviceContext.getLayoutFullURL())) {
      setLayoutFullURL(serviceContext.getLayoutFullURL());
    }

    if (Validator.isNotNull(serviceContext.getLayoutURL())) {
      setLayoutURL(serviceContext.getLayoutURL());
    }

    if (serviceContext.getModifiedDate() != null) {
      setModifiedDate(serviceContext.getModifiedDate());
    }

    if (Validator.isNotNull(serviceContext.getPathMain())) {
      setPathMain(serviceContext.getPathMain());
    }

    if (serviceContext.getPlid() > 0) {
      setPlid(serviceContext.getPlid());
    }

    if (Validator.isNotNull(serviceContext.getPortalURL())) {
      setPortalURL(serviceContext.getPortalURL());
    }

    if (serviceContext.getPortletPreferencesIds() != null) {
      setPortletPreferencesIds(serviceContext.getPortletPreferencesIds());
    }

    if (Validator.isNotNull(serviceContext.getRemoteAddr())) {
      setRemoteAddr(serviceContext.getRemoteAddr());
    }

    if (Validator.isNotNull(serviceContext.getRemoteHost())) {
      setRemoteHost(serviceContext.getRemoteHost());
    }

    if (serviceContext.getScopeGroupId() > 0) {
      setScopeGroupId(serviceContext.getScopeGroupId());
    }

    setSignedIn(serviceContext.isSignedIn());

    if (Validator.isNotNull(serviceContext.getUserDisplayURL())) {
      setUserDisplayURL(serviceContext.getUserDisplayURL());
    }

    if (serviceContext.getUserId() > 0) {
      setUserId(serviceContext.getUserId());
    }

    if (Validator.isNotNull(serviceContext.getUuid())) {
      setUuid(serviceContext.getUuid());
    }

    if (serviceContext.getWorkflowAction() > 0) {
      setWorkflowAction(serviceContext.getWorkflowAction());
    }
  }
  public KBArticle addKBArticle(
      long userId,
      long parentResourcePrimKey,
      String title,
      String content,
      String description,
      String[] sections,
      String dirName,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // KB article

    User user = userPersistence.findByPrimaryKey(userId);
    long groupId = serviceContext.getScopeGroupId();
    double priority = getPriority(groupId, parentResourcePrimKey);
    Date now = new Date();

    validate(title, content);

    long kbArticleId = counterLocalService.increment();

    long resourcePrimKey = counterLocalService.increment();

    long rootResourcePrimKey = getRootResourcePrimKey(resourcePrimKey, parentResourcePrimKey);

    KBArticle kbArticle = kbArticlePersistence.create(kbArticleId);

    kbArticle.setUuid(serviceContext.getUuid());
    kbArticle.setResourcePrimKey(resourcePrimKey);
    kbArticle.setGroupId(groupId);
    kbArticle.setCompanyId(user.getCompanyId());
    kbArticle.setUserId(user.getUserId());
    kbArticle.setUserName(user.getFullName());
    kbArticle.setCreateDate(serviceContext.getCreateDate(now));
    kbArticle.setModifiedDate(serviceContext.getModifiedDate(now));
    kbArticle.setRootResourcePrimKey(rootResourcePrimKey);
    kbArticle.setParentResourcePrimKey(parentResourcePrimKey);
    kbArticle.setVersion(KBArticleConstants.DEFAULT_VERSION);
    kbArticle.setTitle(title);
    kbArticle.setContent(content);
    kbArticle.setDescription(description);
    kbArticle.setPriority(priority);
    kbArticle.setSections(StringUtil.merge(AdminUtil.escapeSections(sections)));
    kbArticle.setViewCount(0);
    kbArticle.setLatest(true);
    kbArticle.setMain(false);
    kbArticle.setStatus(WorkflowConstants.STATUS_DRAFT);

    kbArticlePersistence.update(kbArticle, false);

    // Resources

    resourceLocalService.addModelResources(kbArticle, serviceContext);

    // Asset

    updateKBArticleAsset(
        userId, kbArticle, serviceContext.getAssetCategoryIds(), serviceContext.getAssetTagNames());

    // Attachments

    addKBArticleAttachments(kbArticle, dirName, serviceContext);

    // Workflow

    WorkflowHandlerRegistryUtil.startWorkflowInstance(
        user.getCompanyId(),
        groupId,
        userId,
        KBArticle.class.getName(),
        resourcePrimKey,
        kbArticle,
        serviceContext);

    return kbArticle;
  }
  @Override
  public LayoutPrototype addLayoutPrototype(
      long userId,
      long companyId,
      Map<Locale, String> nameMap,
      String description,
      boolean active,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Layout prototype

    User user = userPersistence.findByPrimaryKey(userId);
    Date now = new Date();

    long layoutPrototypeId = counterLocalService.increment();

    LayoutPrototype layoutPrototype = layoutPrototypePersistence.create(layoutPrototypeId);

    layoutPrototype.setUuid(serviceContext.getUuid());
    layoutPrototype.setCompanyId(companyId);
    layoutPrototype.setUserId(userId);
    layoutPrototype.setUserName(user.getFullName());
    layoutPrototype.setCreateDate(serviceContext.getCreateDate(now));
    layoutPrototype.setModifiedDate(serviceContext.getModifiedDate(now));
    layoutPrototype.setNameMap(nameMap);
    layoutPrototype.setDescription(description);
    layoutPrototype.setActive(active);

    layoutPrototypePersistence.update(layoutPrototype);

    // Resources

    if (userId > 0) {
      resourceLocalService.addResources(
          companyId,
          0,
          userId,
          LayoutPrototype.class.getName(),
          layoutPrototype.getLayoutPrototypeId(),
          false,
          false,
          false);
    }

    // Group

    String friendlyURL = "/template-" + layoutPrototype.getLayoutPrototypeId();

    Group group =
        groupLocalService.addGroup(
            userId,
            GroupConstants.DEFAULT_PARENT_GROUP_ID,
            LayoutPrototype.class.getName(),
            layoutPrototype.getLayoutPrototypeId(),
            GroupConstants.DEFAULT_LIVE_GROUP_ID,
            layoutPrototype.getName(LocaleUtil.getDefault()),
            null,
            0,
            true,
            GroupConstants.DEFAULT_MEMBERSHIP_RESTRICTION,
            friendlyURL,
            false,
            true,
            null);

    if (GetterUtil.getBoolean(serviceContext.getAttribute("addDefaultLayout"), true)) {

      layoutLocalService.addLayout(
          userId,
          group.getGroupId(),
          true,
          LayoutConstants.DEFAULT_PARENT_LAYOUT_ID,
          layoutPrototype.getName(LocaleUtil.getDefault()),
          null,
          null,
          LayoutConstants.TYPE_PORTLET,
          false,
          "/layout",
          serviceContext);
    }

    return layoutPrototype;
  }
  @Override
  public MBThread addThread(long categoryId, MBMessage message, ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Thread

    Date now = new Date();

    long threadId = message.getThreadId();

    if (!message.isRoot() || (threadId <= 0)) {
      threadId = counterLocalService.increment();
    }

    MBThread thread = mbThreadPersistence.create(threadId);

    thread.setUuid(serviceContext.getUuid());
    thread.setGroupId(message.getGroupId());
    thread.setCompanyId(message.getCompanyId());
    thread.setUserId(message.getUserId());
    thread.setUserName(message.getUserName());
    thread.setCreateDate(serviceContext.getCreateDate(now));
    thread.setModifiedDate(serviceContext.getModifiedDate(now));
    thread.setCategoryId(categoryId);
    thread.setRootMessageId(message.getMessageId());
    thread.setRootMessageUserId(message.getUserId());

    if (message.isAnonymous()) {
      thread.setLastPostByUserId(0);
    } else {
      thread.setLastPostByUserId(message.getUserId());
    }

    thread.setLastPostDate(message.getCreateDate());

    if (message.getPriority() != MBThreadConstants.PRIORITY_NOT_GIVEN) {
      thread.setPriority(message.getPriority());
    }

    thread.setStatus(message.getStatus());
    thread.setStatusByUserId(message.getStatusByUserId());
    thread.setStatusByUserName(message.getStatusByUserName());
    thread.setStatusDate(message.getStatusDate());

    mbThreadPersistence.update(thread);

    // Asset

    if (categoryId >= 0) {
      assetEntryLocalService.updateEntry(
          message.getUserId(),
          message.getGroupId(),
          thread.getStatusDate(),
          thread.getLastPostDate(),
          MBThread.class.getName(),
          thread.getThreadId(),
          thread.getUuid(),
          0,
          new long[0],
          new String[0],
          false,
          null,
          null,
          null,
          null,
          String.valueOf(thread.getRootMessageId()),
          null,
          null,
          null,
          null,
          0,
          0,
          null,
          false);
    }

    return thread;
  }
  public DLFolder addFolder(
      long userId,
      long groupId,
      long repositoryId,
      boolean mountPoint,
      long parentFolderId,
      String name,
      String description,
      boolean hidden,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Folder

    User user = userPersistence.findByPrimaryKey(userId);
    parentFolderId = getParentFolderId(groupId, parentFolderId);
    Date now = new Date();

    validateFolder(groupId, parentFolderId, name);

    long folderId = counterLocalService.increment();

    DLFolder dlFolder = dlFolderPersistence.create(folderId);

    dlFolder.setUuid(serviceContext.getUuid());
    dlFolder.setGroupId(groupId);
    dlFolder.setCompanyId(user.getCompanyId());
    dlFolder.setUserId(user.getUserId());
    dlFolder.setCreateDate(serviceContext.getCreateDate(now));
    dlFolder.setModifiedDate(serviceContext.getModifiedDate(now));
    dlFolder.setRepositoryId(repositoryId);
    dlFolder.setMountPoint(mountPoint);
    dlFolder.setParentFolderId(parentFolderId);
    dlFolder.setName(name);
    dlFolder.setDescription(description);
    dlFolder.setHidden(hidden);
    dlFolder.setOverrideFileEntryTypes(false);
    dlFolder.setExpandoBridgeAttributes(serviceContext);

    dlFolderPersistence.update(dlFolder);

    // Resources

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {

      addFolderResources(
          dlFolder, serviceContext.isAddGroupPermissions(), serviceContext.isAddGuestPermissions());
    } else {
      if (serviceContext.isDeriveDefaultPermissions()) {
        serviceContext.deriveDefaultPermissions(repositoryId, DLFolderConstants.getClassName());
      }

      addFolderResources(
          dlFolder, serviceContext.getGroupPermissions(), serviceContext.getGuestPermissions());
    }

    // Parent folder

    if (parentFolderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
      DLFolder parentDLFolder = dlFolderPersistence.findByPrimaryKey(parentFolderId);

      parentDLFolder.setLastPostDate(now);

      dlFolderPersistence.update(parentDLFolder);
    }

    // App helper

    dlAppHelperLocalService.addFolder(userId, new LiferayFolder(dlFolder), serviceContext);

    return dlFolder;
  }