public PollsVote addVote(
      long userId, long questionId, long choiceId, ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Choice

    Date now = new Date();

    PollsChoice choice = pollsChoicePersistence.findByPrimaryKey(choiceId);

    if (choice.getQuestionId() != questionId) {
      throw new NoSuchQuestionException();
    }

    // Question

    PollsQuestion question = pollsQuestionPersistence.findByPrimaryKey(questionId);

    if (question.isExpired(serviceContext, now)) {
      throw new QuestionExpiredException();
    }

    question.setLastVoteDate(serviceContext.getCreateDate(now));

    pollsQuestionPersistence.update(question, false);

    // Vote

    PollsVote vote = pollsVotePersistence.fetchByQ_U(questionId, userId);

    if (vote != null) {
      throw new DuplicateVoteException();
    } else {
      User user = userPersistence.findByPrimaryKey(userId);

      long voteId = counterLocalService.increment();

      vote = pollsVotePersistence.create(voteId);

      vote.setCompanyId(user.getCompanyId());
      vote.setUserId(user.getUserId());
      vote.setUserName(user.getFullName());
      vote.setCreateDate(serviceContext.getCreateDate(now));
      vote.setModifiedDate(serviceContext.getModifiedDate(now));
      vote.setQuestionId(questionId);
      vote.setChoiceId(choiceId);
      vote.setVoteDate(serviceContext.getCreateDate(now));

      pollsVotePersistence.update(vote, false);
    }

    return vote;
  }
  @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 AnonymousUser addAnonymousUser(
      long userId, String lastIp, String typeSettings, ServiceContext serviceContext)
      throws PortalException, SystemException {

    User user = UserLocalServiceUtil.fetchUser(userId);

    Date now = new Date();

    long anonymousUserId = CounterLocalServiceUtil.increment();

    AnonymousUser anonymousUser = anonymousUserPersistence.create(anonymousUserId);

    anonymousUser.setCompanyId(serviceContext.getCompanyId());

    if (user != null) {
      anonymousUser.setUserId(user.getUserId());
      anonymousUser.setUserName(user.getFullName());
    }

    anonymousUser.setCreateDate(serviceContext.getCreateDate(now));
    anonymousUser.setModifiedDate(serviceContext.getModifiedDate(now));
    anonymousUser.setLastIp(lastIp);
    anonymousUser.setTypeSettings(typeSettings);

    anonymousUserPersistence.update(anonymousUser);

    return anonymousUser;
  }
  /*
   * NOTE FOR DEVELOPERS:
   *
   * Never reference this interface directly. Always use {@link org.oep.core.datamgt.parameter.service.DefaultParameterLocalServiceUtil} to access the default parameter local service.
   */
  @Indexable(type = IndexableType.REINDEX)
  public DefaultParameter addDefaultParameter(
      String applicationName,
      String title,
      String parameterName,
      String parameterValue,
      int changeable,
      ServiceContext serviceContext)
      throws SystemException, PortalException {
    validate(applicationName, title, parameterName, parameterValue);
    long id = counterLocalService.increment();
    DefaultParameter defaultParameter = defaultParameterPersistence.create(id);
    Date now = new Date();

    defaultParameter.setApplicationName(applicationName);
    defaultParameter.setTitle(title);
    defaultParameter.setParameterName(parameterName);
    defaultParameter.setParameterValue(parameterValue);
    defaultParameter.setCreateDate(serviceContext.getCreateDate(now));
    defaultParameter.setCompanyId(serviceContext.getCompanyId());
    defaultParameter.setChangeable(changeable);

    defaultParameterPersistence.update(defaultParameter);

    if (_log.isInfoEnabled()) {
      _log.info("Create new default parameter " + id);
    }

    return getDefaultParameter(id);
  }
  @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);
  }
  @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 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;
  }
  /**
   * Thêm mới một thống kê hồ sơ theo lĩnh vực
   *
   * <p>Version: OEP 2.0
   *
   * <p>History: DATE AUTHOR DESCRIPTION -------------------------------------------------
   * 21-September-2015 trungdk Tạo mới
   *
   * @param month tháng thống kê
   * @param year năm thống kê
   * @param dossierDomain lĩnh vực hồ sơ theo cấp 1
   * @param receiveNumber số hồ sơ được tiếp nhận
   * @param onlineNumber số hồ sơ trực tuyến
   * @param onlineRatio tỉ lệ hồ sơ trực tuyến
   * @param finishNumber số hồ sơ được hoàn thành
   * @param ontimeNumber số hồ sơ hoàn thành đúng hẹn
   * @param ontimeRatio tỉ lệ hồ sơ hoàn thành đúng hẹn
   * @param delayDaysAvg số ngày trễ hẹn trung bình
   * @param serviceContext ngữ cảnh dịch vụ
   * @return: thống kê hồ sơ mới được tạo
   */
  @Indexable(type = IndexableType.REINDEX)
  public StatisticByDomain addStatisticByDomain(
      int month,
      int year,
      String dossierDomain,
      int receiveNumber,
      int onlineNumber,
      double onlineRatio,
      int finishNumber,
      int ontimeNumber,
      double ontimeRatio,
      double delayDaysAvg,
      ServiceContext serviceContext)
      throws SystemException, PortalException {
    long id = counterLocalService.increment();
    StatisticByDomain statisticByDomain = statisticByDomainPersistence.create(id);
    Date now = new Date();

    statisticByDomain.setCompanyId(serviceContext.getCompanyId());
    statisticByDomain.setGroupId(serviceContext.getScopeGroupId());
    statisticByDomain.setCreateDate(serviceContext.getCreateDate(now));
    statisticByDomain.setMonth(month);
    statisticByDomain.setYear(year);
    statisticByDomain.setDossierDomain(dossierDomain);
    statisticByDomain.setReceiveNumber(receiveNumber);
    statisticByDomain.setOnlineNumber(onlineNumber);
    statisticByDomain.setOnlineRatio(onlineRatio);
    statisticByDomain.setFinishNumber(finishNumber);
    statisticByDomain.setOntimeNumber(ontimeNumber);
    statisticByDomain.setOnlineRatio(onlineRatio);
    statisticByDomain.setDelayDaysAvg(delayDaysAvg);

    statisticByDomainPersistence.update(statisticByDomain);

    if (_log.isInfoEnabled()) {
      _log.info("Create new statistic by domain " + id);
    }

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {
      addStatisticByDomainResources(
          statisticByDomain,
          serviceContext.isAddGroupPermissions(),
          serviceContext.isAddGuestPermissions(),
          serviceContext);
    } else {
      addStatisticByDomainResources(
          statisticByDomain,
          serviceContext.getGroupPermissions(),
          serviceContext.getGuestPermissions(),
          serviceContext);
    }
    return getStatisticByDomain(id);
  }
  @Override
  public BackgroundTask addBackgroundTask(
      long userId,
      long groupId,
      String name,
      String[] servletContextNames,
      Class<?> taskExecutorClass,
      Map<String, Serializable> taskContextMap,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

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

    final long backgroundTaskId = counterLocalService.increment();

    BackgroundTask backgroundTask = backgroundTaskPersistence.create(backgroundTaskId);

    backgroundTask.setCompanyId(user.getCompanyId());
    backgroundTask.setCreateDate(serviceContext.getCreateDate(now));
    backgroundTask.setGroupId(groupId);
    backgroundTask.setModifiedDate(serviceContext.getModifiedDate(now));
    backgroundTask.setUserId(userId);
    backgroundTask.setUserName(user.getFullName());
    backgroundTask.setName(name);
    backgroundTask.setServletContextNames(StringUtil.merge(servletContextNames));
    backgroundTask.setTaskExecutorClassName(taskExecutorClass.getName());

    if (taskContextMap != null) {
      String taskContext = JSONFactoryUtil.serialize(taskContextMap);

      backgroundTask.setTaskContext(taskContext);
    }

    backgroundTask.setStatus(BackgroundTaskConstants.STATUS_NEW);

    backgroundTaskPersistence.update(backgroundTask);

    TransactionCommitCallbackRegistryUtil.registerCallback(
        new Callable<Void>() {

          @Override
          public Void call() throws Exception {
            backgroundTaskLocalService.triggerBackgroundTask(backgroundTaskId);

            return null;
          }
        });

    return backgroundTask;
  }
  @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;
  }
  /**
   * Thêm bước trong quy trình mới
   *
   * <p>Version: OEP 2.0
   *
   * <p>History: DATE AUTHOR DESCRIPTION -------------------------------------------------
   * 21-September-2015 trungdk Tạo mới
   *
   * @param dossierProcessId mã quy trình xử lý thủ tục hành chính
   * @param title tiêu đề bước xử lý
   * @param sequenceNo số thứ tự bước xử lý
   * @param daysDuration số ngày cần thiết để xử lý quy trình
   * @param doForm Form xử lý riêng cho quy trình
   * @param formLabel Tên hiển thị nút xử lý hồ sơ
   * @param rollback cờ đánh dấu cho việc roolback trong quy trình
   * @return: bước trong quy trình mới
   */
  @Indexable(type = IndexableType.REINDEX)
  public DossierStep addDossierStep(
      long dossierProcessId,
      String title,
      int sequenceNo,
      int daysDuration,
      String doForm,
      String formLabel,
      int rollback,
      ServiceContext serviceContext)
      throws SystemException, PortalException {
    validate(dossierProcessId, title, sequenceNo);
    long id = counterLocalService.increment();
    DossierStep dossierStep = dossierStepPersistence.create(id);
    Date now = new Date();

    dossierStep.setUserId(serviceContext.getUserId());
    dossierStep.setGroupId(serviceContext.getScopeGroupId());
    dossierStep.setCompanyId(serviceContext.getCompanyId());
    dossierStep.setDossierProcessId(dossierProcessId);
    dossierStep.setTitle(title);
    dossierStep.setSequenceNo(sequenceNo);
    dossierStep.setDaysDuration(daysDuration);
    dossierStep.setDoForm(doForm);
    dossierStep.setFormLabel(formLabel);
    dossierStep.setRollback(rollback);
    dossierStep.setCreateDate(serviceContext.getCreateDate(now));

    dossierStepPersistence.update(dossierStep);

    if (_log.isInfoEnabled()) {
      _log.info("Create new dossier step " + id);
    }

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {
      addDossierStepResources(
          dossierStep,
          serviceContext.isAddGroupPermissions(),
          serviceContext.isAddGuestPermissions(),
          serviceContext);
    } else {
      addDossierStepResources(
          dossierStep,
          serviceContext.getGroupPermissions(),
          serviceContext.getGuestPermissions(),
          serviceContext);
    }
    return getDossierStep(id);
  }
  public DLFileRank addFileRank(
      long groupId,
      long companyId,
      long userId,
      long folderId,
      String name,
      ServiceContext serviceContext)
      throws SystemException {

    long fileRankId = counterLocalService.increment();

    DLFileRank fileRank = dlFileRankPersistence.create(fileRankId);

    fileRank.setGroupId(groupId);
    fileRank.setCompanyId(companyId);
    fileRank.setUserId(userId);
    fileRank.setCreateDate(serviceContext.getCreateDate(null));
    fileRank.setFolderId(folderId);
    fileRank.setName(name);

    try {
      dlFileRankPersistence.update(fileRank, false);
    } catch (SystemException se) {
      if (_log.isWarnEnabled()) {
        _log.warn(
            "Add failed, fetch {companyId="
                + companyId
                + ", userId="
                + userId
                + ", folderId="
                + folderId
                + ", name="
                + name
                + "}");
      }

      fileRank = dlFileRankPersistence.fetchByC_U_F_N(companyId, userId, folderId, name, false);

      if (fileRank == null) {
        throw se;
      }
    }

    return fileRank;
  }
  public void addFoo(
      String field1,
      boolean field2,
      int field3,
      Date field4,
      String field5,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Foo

    User user = userLocalService.getUserById(serviceContext.getUserId());
    long groupId = serviceContext.getScopeGroupId();
    Date now = new Date();

    long fooId = counterLocalService.increment();

    Foo foo = fooPersistence.create(fooId);

    foo.setGroupId(groupId);
    foo.setCompanyId(user.getCompanyId());
    foo.setUserId(user.getUserId());
    foo.setUserName(user.getFullName());
    foo.setCreateDate(serviceContext.getCreateDate(now));
    foo.setModifiedDate(serviceContext.getModifiedDate(now));
    foo.setField1(field1);
    foo.setField2(field2);
    foo.setField3(field3);
    foo.setField4(field4);
    foo.setField5(field5);
    foo.setExpandoBridgeAttributes(serviceContext);

    fooPersistence.update(foo, false);

    // Asset

    updateAsset(
        user.getUserId(),
        foo,
        serviceContext.getAssetCategoryIds(),
        serviceContext.getAssetTagNames());
  }
  public DLFileRank updateFileRank(
      long groupId,
      long companyId,
      long userId,
      long folderId,
      String name,
      ServiceContext serviceContext)
      throws SystemException {

    if (!PropsValues.DL_FILE_RANK_ENABLED) {
      return null;
    }

    DLFileRank fileRank = dlFileRankPersistence.fetchByC_U_F_N(companyId, userId, folderId, name);

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

      dlFileRankPersistence.update(fileRank, false);
    } else {
      fileRank = addFileRank(groupId, companyId, userId, folderId, name, serviceContext);
    }

    if (dlFileRankPersistence.countByG_U(groupId, userId) > 5) {
      List<DLFileRank> fileRanks = getFileRanks(groupId, userId);

      DLFileRank lastFileRank = fileRanks.get(fileRanks.size() - 1);

      long lastFileRankId = lastFileRank.getFileRankId();

      try {
        dlFileRankPersistence.remove(lastFileRank);
      } catch (Exception e) {
        _log.warn(
            "Failed to remove file rank "
                + lastFileRankId
                + " because another thread already removed it");
      }
    }

    return fileRank;
  }
  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;
  }
  @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 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;
  }
  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;
  }
  @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;
  }
Ejemplo n.º 20
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());
    }
  }
  @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 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;
  }
  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;
  }
  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;
  }
  @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;
  }