@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;
  }
  @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);
  }
  public TitlesDepartmentUnitUnitGroup addTitlesDepartmentUnitUnitGroup(
      long titlesId,
      long departmentId,
      long unitId,
      long unitGroupId,
      ServiceContext serviceContext) {
    try {
      TitlesDepartmentUnitUnitGroup o =
          titlesDepartmentUnitUnitGroupPersistence.create(counterLocalService.increment());

      o.setTitlesId(titlesId);
      o.setUnitGroupId(unitGroupId);
      o.setUnitId(unitId);
      o.setDepartmentId(departmentId);

      o.setCreateDate(new Date());
      o.setModifiedDate(new Date());
      o.setGroupId(serviceContext.getScopeGroupId());
      o.setCompanyId(serviceContext.getCompanyId());
      o.setUserId(serviceContext.getUserId());

      return super.addTitlesDepartmentUnitUnitGroup(o);
    } catch (SystemException e) {
      LOGGER.info(e);
    }
    return null;
  }
  @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 Department addDepartment(String name, long devisionId, ServiceContext serviceContext) {
    try {
      Department department = departmentPersistence.create(counterLocalService.increment());
      department.setName(name);
      department.setDevisionId(devisionId);
      department.setGroupId(serviceContext.getScopeGroupId());
      department.setCompanyId(serviceContext.getCompanyId());
      department.setUserId(serviceContext.getUserId());
      department.setCreateDate(new Date());
      department.setModifiedDate(new Date());

      department = super.addDepartment(department);

      // add permission
      resourceLocalService.addResources(
          department.getCompanyId(),
          department.getGroupId(),
          serviceContext.getUserId(),
          Department.class.getName(),
          department.getDepartmentId(),
          false,
          true,
          true);
      return department;
    } catch (SystemException e) {
      LOGGER.info(e);
    } catch (PortalException e) {
      LOGGER.info(e);
    }
    return null;
  }
  @Override
  public Department addDepartment(Department department, ServiceContext serviceContext) {
    try {
      department.setGroupId(serviceContext.getScopeGroupId());
      department.setCompanyId(serviceContext.getCompanyId());
      department.setUserId(serviceContext.getUserId());
      department.setCreateDate(new Date());
      department.setModifiedDate(new Date());

      department = super.addDepartment(department); // NOSONAR

      // add permission
      resourceLocalService.addResources(
          department.getCompanyId(),
          department.getGroupId(),
          serviceContext.getUserId(),
          Department.class.getName(),
          department.getDepartmentId(),
          false,
          true,
          true);
      return department;
    } catch (SystemException e) {
      LOGGER.info(e);
    } catch (PortalException e) {
      LOGGER.info(e);
    }
    return null;
  }
  /*
   * 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);
  }
  protected DynamicQuery buildDynamicQuery(
      String kaleoDefinitionName,
      int kaleoDefinitionVersion,
      boolean completed,
      ServiceContext serviceContext) {

    DynamicQuery dynamicQuery =
        DynamicQueryFactoryUtil.forClass(KaleoInstance.class, getClassLoader());

    Property companyIdProperty = PropertyFactoryUtil.forName("companyId");

    dynamicQuery.add(companyIdProperty.eq(serviceContext.getCompanyId()));

    Property kaleoDefinitionNameProperty = PropertyFactoryUtil.forName("kaleoDefinitionName");

    dynamicQuery.add(kaleoDefinitionNameProperty.eq(kaleoDefinitionName));

    Property kaleoDefinitionVersionProperty = PropertyFactoryUtil.forName("kaleoDefinitionVersion");

    dynamicQuery.add(kaleoDefinitionVersionProperty.eq(kaleoDefinitionVersion));

    if (completed) {
      Property completionDateProperty = PropertyFactoryUtil.forName("completionDate");

      dynamicQuery.add(completionDateProperty.isNotNull());
    } else {
      Property completionDateProperty = PropertyFactoryUtil.forName("completionDate");

      dynamicQuery.add(completionDateProperty.isNull());
    }

    return dynamicQuery;
  }
  public void addAttachment(
      String dirName, String shortFileName, InputStream inputStream, ServiceContext serviceContext)
      throws PortalException, SystemException {

    DLStoreUtil.addFile(
        serviceContext.getCompanyId(),
        CompanyConstants.SYSTEM,
        dirName + StringPool.SLASH + shortFileName,
        inputStream);
  }
  protected DynamicQuery buildDynamicQuery(Boolean completed, ServiceContext serviceContext) {

    DynamicQuery dynamicQuery =
        DynamicQueryFactoryUtil.forClass(KaleoTaskInstanceToken.class, getClassLoader());

    dynamicQuery.add(PropertyFactoryUtil.forName("companyId").eq(serviceContext.getCompanyId()));

    addCompletedCriterion(dynamicQuery, completed);

    return dynamicQuery;
  }
  /**
   * 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);
  }
  protected void addKBArticleAttachments(
      KBArticle kbArticle, String dirName, ServiceContext serviceContext)
      throws PortalException, SystemException {

    try {
      DLStoreUtil.addDirectory(
          serviceContext.getCompanyId(),
          CompanyConstants.SYSTEM,
          kbArticle.getAttachmentsDirName());
    } catch (DuplicateDirectoryException dde) {
      _log.error("Directory already exists for " + dde.getMessage());
    }

    if (Validator.isNull(dirName)) {
      return;
    }

    String[] fileNames =
        DLStoreUtil.getFileNames(serviceContext.getCompanyId(), CompanyConstants.SYSTEM, dirName);

    for (String fileName : fileNames) {
      InputStream inputStream = null;

      try {
        inputStream =
            DLStoreUtil.getFileAsStream(
                serviceContext.getCompanyId(), CompanyConstants.SYSTEM, fileName);

        addAttachment(
            kbArticle.getAttachmentsDirName(),
            FileUtil.getShortFileName(fileName),
            inputStream,
            serviceContext);
      } catch (DuplicateFileException dfe) {
        _log.error("File already exists for " + dfe.getMessage());
      } finally {
        StreamUtil.cleanUp(inputStream);
      }
    }
  }
  public int getSubmittingUserKaleoTaskInstanceTokensCount(
      long userId, Boolean completed, ServiceContext serviceContext) throws SystemException {

    DynamicQuery dynamicQuery =
        DynamicQueryFactoryUtil.forClass(KaleoTaskInstanceToken.class, getClassLoader());

    dynamicQuery.add(PropertyFactoryUtil.forName("companyId").eq(serviceContext.getCompanyId()));
    dynamicQuery.add(PropertyFactoryUtil.forName("workflowContext").like("\"userId\":" + userId));

    addCompletedCriterion(dynamicQuery, completed);

    return (int) dynamicQueryCount(dynamicQuery);
  }
  @Override
  public KaleoInstance addKaleoInstance(
      long kaleoDefinitionId,
      String kaleoDefinitionName,
      int kaleoDefinitionVersion,
      Map<String, Serializable> workflowContext,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    User user = userPersistence.fetchByPrimaryKey(serviceContext.getUserId());

    if (user == null) {
      user = userLocalService.getDefaultUser(serviceContext.getCompanyId());
    }

    Date now = new Date();

    long kaleoInstanceId = counterLocalService.increment();

    KaleoInstance kaleoInstance = kaleoInstancePersistence.create(kaleoInstanceId);

    long groupId = StagingUtil.getLiveGroupId(serviceContext.getScopeGroupId());

    kaleoInstance.setGroupId(groupId);

    kaleoInstance.setCompanyId(user.getCompanyId());
    kaleoInstance.setUserId(user.getUserId());
    kaleoInstance.setUserName(user.getFullName());
    kaleoInstance.setCreateDate(now);
    kaleoInstance.setModifiedDate(now);
    kaleoInstance.setKaleoDefinitionId(kaleoDefinitionId);
    kaleoInstance.setKaleoDefinitionName(kaleoDefinitionName);
    kaleoInstance.setKaleoDefinitionVersion(kaleoDefinitionVersion);
    kaleoInstance.setClassName(
        (String) workflowContext.get(WorkflowConstants.CONTEXT_ENTRY_CLASS_NAME));

    if (workflowContext.containsKey(WorkflowConstants.CONTEXT_ENTRY_CLASS_PK)) {

      kaleoInstance.setClassPK(
          GetterUtil.getLong(
              (String) workflowContext.get(WorkflowConstants.CONTEXT_ENTRY_CLASS_PK)));
    }

    kaleoInstance.setCompleted(false);
    kaleoInstance.setWorkflowContext(WorkflowContextUtil.convert(workflowContext));

    kaleoInstancePersistence.update(kaleoInstance);

    return kaleoInstance;
  }
  /**
   * 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 EmpDiscipline createPrePersistedEntity(ServiceContext serviceContext) {
    try {
      final long id = counterLocalService.increment();
      EmpDiscipline obj = empDisciplinePersistence.create(id);

      obj.setCompanyId(serviceContext.getCompanyId());
      obj.setGroupId(serviceContext.getScopeGroupId());
      obj.setUserId(serviceContext.getUserId());
      obj.setCreateDate(new Date());

      return obj;
    } catch (SystemException e) {
      LOGGER.info(e);
    }
    return null;
  }
  public List<KaleoTaskInstanceToken> getSubmittingUserKaleoTaskInstanceTokens(
      long userId,
      Boolean completed,
      int start,
      int end,
      OrderByComparator orderByComparator,
      ServiceContext serviceContext)
      throws SystemException {

    DynamicQuery dynamicQuery =
        DynamicQueryFactoryUtil.forClass(KaleoTaskInstanceToken.class, getClassLoader());

    dynamicQuery.add(PropertyFactoryUtil.forName("companyId").eq(serviceContext.getCompanyId()));
    dynamicQuery.add(PropertyFactoryUtil.forName("workflowContext").like("\"userId\":" + userId));

    addCompletedCriterion(dynamicQuery, completed);

    return dynamicQuery(dynamicQuery, start, end, orderByComparator);
  }
  protected DynamicQuery buildDynamicQuery(
      Long userId,
      String[] assetClassNames,
      Long[] assetClassPKs,
      Boolean completed,
      ServiceContext serviceContext) {

    DynamicQuery dynamicQuery =
        DynamicQueryFactoryUtil.forClass(KaleoInstance.class, getClassLoader());

    Property companyIdProperty = PropertyFactoryUtil.forName("companyId");

    dynamicQuery.add(companyIdProperty.eq(serviceContext.getCompanyId()));

    if (userId != null) {
      Property userIdProperty = PropertyFactoryUtil.forName("userId");

      dynamicQuery.add(userIdProperty.eq(userId));
    }

    if (ArrayUtil.isNotEmpty(assetClassNames)) {
      dynamicQuery.add(getAssetClassNames(assetClassNames));
    }

    if (ArrayUtil.isNotEmpty(assetClassPKs)) {
      dynamicQuery.add(getAssetClassPKs(assetClassPKs));
    }

    if (completed != null) {
      if (completed) {
        Property completionDateProperty = PropertyFactoryUtil.forName("completionDate");

        dynamicQuery.add(completionDateProperty.isNotNull());
      } else {
        Property completionDateProperty = PropertyFactoryUtil.forName("completionDate");

        dynamicQuery.add(completionDateProperty.isNull());
      }
    }

    return dynamicQuery;
  }
  @Override
  protected String getBody(
      UserNotificationEvent userNotificationEvent, ServiceContext serviceContext) throws Exception {

    JSONObject jsonObject = JSONFactoryUtil.createJSONObject(userNotificationEvent.getPayload());

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

    WorkflowTask workflowTask =
        WorkflowTaskManagerUtil.fetchWorkflowTask(serviceContext.getCompanyId(), workflowTaskId);

    if (workflowTask == null) {
      _userNotificationEventLocalService.deleteUserNotificationEvent(
          userNotificationEvent.getUserNotificationEventId());

      return null;
    }

    return HtmlUtil.escape(jsonObject.getString("notificationMessage"));
  }
  @Override
  public String getURLEditWorkflowTask(long workflowTaskId, ServiceContext serviceContext)
      throws PortalException, SystemException {

    try {
      LiferayPortletURL liferayPortletURL =
          PortletURLFactoryUtil.create(
              serviceContext.getRequest(),
              PortletKeys.MY_WORKFLOW_TASKS,
              PortalUtil.getControlPanelPlid(serviceContext.getCompanyId()),
              PortletRequest.RENDER_PHASE);

      liferayPortletURL.setControlPanelCategory("my");
      liferayPortletURL.setParameter("struts_action", "/my_workflow_tasks/edit_workflow_task");
      liferayPortletURL.setParameter("workflowTaskId", String.valueOf(workflowTaskId));
      liferayPortletURL.setWindowState(WindowState.MAXIMIZED);

      return liferayPortletURL.toString();
    } catch (WindowStateException wse) {
      throw new PortalException(wse);
    }
  }
  public String updateAttachments(
      long resourcePrimKey, String dirName, ServiceContext serviceContext)
      throws PortalException, SystemException {

    if (Validator.isNotNull(dirName)) {
      return dirName;
    }

    dirName = "knowledgebase/temp/attachments/" + counterLocalService.increment();

    DLStoreUtil.addDirectory(serviceContext.getCompanyId(), CompanyConstants.SYSTEM, dirName);

    if (resourcePrimKey <= 0) {
      return dirName;
    }

    KBArticle kbArticle = getLatestKBArticle(resourcePrimKey, WorkflowConstants.STATUS_ANY);

    for (String fileName : kbArticle.getAttachmentsFileNames()) {
      String shortFileName = FileUtil.getShortFileName(fileName);

      InputStream inputStream = null;

      try {
        inputStream =
            DLStoreUtil.getFileAsStream(
                kbArticle.getCompanyId(), CompanyConstants.SYSTEM, fileName);

        addAttachment(dirName, shortFileName, inputStream, serviceContext);
      } finally {
        StreamUtil.cleanUp(inputStream);
      }
    }

    return dirName;
  }
  protected void subscribeUsers(MicroblogsEntry microblogsEntry, ServiceContext serviceContext)
      throws PortalException {

    long rootMicroblogsEntryId = MicroblogsUtil.getRootMicroblogsEntryId(microblogsEntry);

    subscriptionLocalService.addSubscription(
        microblogsEntry.getUserId(),
        serviceContext.getScopeGroupId(),
        MicroblogsEntry.class.getName(),
        rootMicroblogsEntryId);

    List<String> screenNames = MicroblogsUtil.getScreenNames(microblogsEntry.getContent());

    for (String screenName : screenNames) {
      long userId =
          userLocalService.getUserIdByScreenName(serviceContext.getCompanyId(), screenName);

      subscriptionLocalService.addSubscription(
          userId,
          serviceContext.getScopeGroupId(),
          MicroblogsEntry.class.getName(),
          rootMicroblogsEntryId);
    }
  }
  protected DDLRecordSet updateRecordSet(ActionRequest actionRequest) throws Exception {

    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

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

    long groupId = ParamUtil.getLong(actionRequest, "groupId");
    long ddmStructureId = ParamUtil.getLong(actionRequest, "ddmStructureId");
    Map<Locale, String> nameMap = LocalizationUtil.getLocalizationMap(actionRequest, "name");
    Map<Locale, String> descriptionMap =
        LocalizationUtil.getLocalizationMap(actionRequest, "description");
    int scope = ParamUtil.getInteger(actionRequest, "scope");

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

    DDLRecordSet recordSet = null;

    if (cmd.equals(Constants.ADD)) {
      recordSet =
          DDLRecordSetServiceUtil.addRecordSet(
              groupId,
              ddmStructureId,
              null,
              nameMap,
              descriptionMap,
              DDLRecordSetConstants.MIN_DISPLAY_ROWS_DEFAULT,
              scope,
              serviceContext);
    } else {
      recordSet =
          DDLRecordSetServiceUtil.updateRecordSet(
              recordSetId,
              ddmStructureId,
              nameMap,
              descriptionMap,
              DDLRecordSetConstants.MIN_DISPLAY_ROWS_DEFAULT,
              serviceContext);
    }

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

    WorkflowDefinitionLinkLocalServiceUtil.updateWorkflowDefinitionLink(
        serviceContext.getUserId(),
        serviceContext.getCompanyId(),
        groupId,
        DDLRecordSet.class.getName(),
        recordSet.getRecordSetId(),
        0,
        workflowDefinition);

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

    if (Validator.isNotNull(portletResource)) {
      PortletPreferences preferences =
          PortletPreferencesFactoryUtil.getPortletSetup(actionRequest, portletResource);

      preferences.reset("detailDDMTemplateId");
      preferences.reset("editable");
      preferences.reset("listDDMTemplateId");
      preferences.reset("spreadsheet");

      preferences.setValue("recordSetId", String.valueOf(recordSet.getRecordSetId()));

      preferences.store();
    }

    return recordSet;
  }
  protected Criteria buildTaskInstanceExtensionSearchCriteria(
      String taskName,
      String assetType,
      Long[] assetPrimaryKeys,
      Date dueDateGT,
      Date dueDateLT,
      Boolean completed,
      Boolean searchByUserRoles,
      boolean andOperator,
      ServiceContext serviceContext)
      throws SystemException {

    Criteria criteria = _session.createCriteria(TaskInstanceExtensionImpl.class);

    criteria.createAlias("taskInstance", "taskInstance");

    criteria.add(Restrictions.eq("companyId", serviceContext.getCompanyId()));

    if (Validator.isNotNull(taskName)
        || Validator.isNotNull(assetType)
        || (dueDateGT != null)
        || (dueDateLT != null)) {

      Junction junction = null;

      if (andOperator) {
        junction = Restrictions.conjunction();
      } else {
        junction = Restrictions.disjunction();
      }

      if (Validator.isNotNull(taskName)) {
        String[] taskNameKeywords = StringUtil.split(taskName, StringPool.SPACE);

        for (String taskNameKeyword : taskNameKeywords) {
          junction.add(Restrictions.like("taskInstance.name", "%" + taskNameKeyword + "%"));
        }
      }

      if (Validator.isNotNull(assetType)) {
        String[] assetTypeKeywords = StringUtil.split(assetType, StringPool.SPACE);

        for (String assetTypeKeyword : assetTypeKeywords) {
          junction.add(
              Restrictions.like(
                  "workflowContext", "%\"entryType\":\"%" + assetTypeKeyword + "%\"%"));
        }
      }

      if (Validator.isNotNull(assetPrimaryKeys)) {
        for (Long assetPrimaryKey : assetPrimaryKeys) {
          junction.add(
              Restrictions.like(
                  "workflowContext", "%\"entryClassPK\":\"%" + assetPrimaryKey + "%\"%"));
        }
      }

      if (dueDateGT != null) {
        junction.add(Restrictions.ge("taskInstance.dueDate", dueDateGT));
      }

      if (dueDateLT != null) {
        junction.add(Restrictions.lt("taskInstance.dueDate", dueDateGT));
      }

      criteria.add(junction);
    }

    addSearchByUserRolesCriterion(criteria, searchByUserRoles, serviceContext);

    if (completed != null) {
      if (completed.booleanValue()) {
        criteria.add(Restrictions.isNotNull("taskInstance.end"));
      } else {
        criteria.add(Restrictions.isNull("taskInstance.end"));
      }
    }

    return criteria;
  }
Esempio n. 25
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());
    }
  }
  protected void notifySubscribers(KBComment kbComment, ServiceContext serviceContext)
      throws PortalException {

    PortletPreferences preferences =
        portletPreferencesLocalService.getPreferences(
            kbComment.getCompanyId(),
            kbComment.getGroupId(),
            PortletKeys.PREFS_OWNER_TYPE_GROUP,
            PortletKeys.PREFS_PLID_SHARED,
            PortletKeys.KNOWLEDGE_BASE_ADMIN,
            null);

    if (!AdminUtil.isSuggestionStatusChangeNotificationEnabled(
        kbComment.getStatus(), preferences)) {

      return;
    }

    String fromName = AdminUtil.getEmailFromName(preferences, serviceContext.getCompanyId());
    String fromAddress = AdminUtil.getEmailFromAddress(preferences, kbComment.getCompanyId());

    String subject =
        AdminUtil.getEmailKBArticleSuggestionNotificationSubject(
            kbComment.getStatus(), preferences);
    String body =
        AdminUtil.getEmailKBArticleSuggestionNotificationBody(kbComment.getStatus(), preferences);

    KBArticle kbArticle =
        kbArticleLocalService.getLatestKBArticle(
            kbComment.getClassPK(), WorkflowConstants.STATUS_APPROVED);

    String kbArticleContent =
        StringUtil.replace(
            kbArticle.getContent(),
            new String[] {"href=\"/", "src=\"/"},
            new String[] {
              "href=\"" + serviceContext.getPortalURL() + "/",
              "src=\"" + serviceContext.getPortalURL() + "/"
            });

    SubscriptionSender subscriptionSender = new AdminSubscriptionSender(kbArticle, serviceContext);

    subscriptionSender.setBody(body);
    subscriptionSender.setCompanyId(kbArticle.getCompanyId());
    subscriptionSender.setContextAttribute("[$ARTICLE_CONTENT$]", kbArticleContent, false);
    subscriptionSender.setContextAttribute("[$ARTICLE_TITLE$]", kbArticle.getTitle(), false);
    subscriptionSender.setContextAttribute("[$COMMENT_CONTENT$]", kbComment.getContent(), false);
    subscriptionSender.setContextUserPrefix("ARTICLE");
    subscriptionSender.setFrom(fromAddress, fromName);
    subscriptionSender.setHtmlFormat(true);
    subscriptionSender.setMailId("kb_article", kbArticle.getKbArticleId());
    subscriptionSender.setPortletId(serviceContext.getPortletId());
    subscriptionSender.setReplyToAddress(fromAddress);
    subscriptionSender.setScopeGroupId(kbArticle.getGroupId());
    subscriptionSender.setSubject(subject);
    subscriptionSender.setUserId(kbArticle.getUserId());

    User user = userLocalService.getUser(kbComment.getUserId());

    subscriptionSender.addRuntimeSubscribers(user.getEmailAddress(), user.getFullName());

    subscriptionSender.flushNotificationsAsync();
  }
  public Task addTask(
      long projectId,
      String name,
      int type,
      int startDateMonth,
      int startDateDay,
      int startDateYear,
      int startDateHour,
      int startDateMinute,
      int endDateMonth,
      int endDateDay,
      int endDateYear,
      int endDateHour,
      int endDateMinute,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    User user = userPersistence.findByPrimaryKey(serviceContext.getUserId());

    Date startDate =
        PortalUtil.getDate(
            startDateMonth,
            startDateDay,
            startDateYear,
            startDateHour,
            startDateMinute,
            new PortalException());

    Date endDate =
        PortalUtil.getDate(
            endDateMonth,
            endDateDay,
            endDateYear,
            endDateHour,
            endDateMinute,
            new PortalException());

    validate(name, startDate, endDate);

    long taskId = counterLocalService.increment();

    Project project = ProjectLocalServiceUtil.getProject(projectId);

    Task task = taskPersistence.create(taskId);

    task.setUserId(user.getUserId());
    task.setProjectId(projectId);
    task.setName(name);
    task.setStartDate(startDate);
    task.setEndDate(endDate);
    task.setType(type);

    taskPersistence.update(task, false);

    // Resources

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

      addTaskResources(
          task,
          serviceContext.getCompanyId(),
          serviceContext.getScopeGroupId(),
          project.getUserId(),
          serviceContext.getAddGroupPermissions(),
          serviceContext.getAddGuestPermissions());
    } else {
      addTaskResources(
          task,
          serviceContext.getCompanyId(),
          serviceContext.getScopeGroupId(),
          project.getUserId(),
          serviceContext.getGroupPermissions(),
          serviceContext.getGuestPermissions());
    }

    return task;
  }
  protected void setAssignee(
      KaleoTaskAssignment kaleoTaskAssignment, Assignment assignment, ServiceContext serviceContext)
      throws PortalException, SystemException {

    AssignmentType assignmentType = assignment.getAssignmentType();

    if (assignmentType.equals(AssignmentType.RESOURCE_ACTION)) {
      kaleoTaskAssignment.setAssigneeClassName(ResourceAction.class.getName());

      ResourceActionAssignment resourceActionAssignment = (ResourceActionAssignment) assignment;

      String actionId = resourceActionAssignment.getActionId();

      kaleoTaskAssignment.setAssigneeActionId(actionId);
    } else if (assignmentType.equals(AssignmentType.ROLE)) {
      kaleoTaskAssignment.setAssigneeClassName(Role.class.getName());

      RoleAssignment roleAssignment = (RoleAssignment) assignment;

      Role role = null;

      if (Validator.isNotNull(roleAssignment.getRoleName())) {
        int roleType = RoleUtil.getRoleType(roleAssignment.getRoleType());

        role =
            RoleUtil.getRole(
                roleAssignment.getRoleName(), roleType,
                roleAssignment.isAutoCreate(), serviceContext);
      } else {
        role = roleLocalService.getRole(roleAssignment.getRoleId());
      }

      kaleoTaskAssignment.setAssigneeClassPK(role.getRoleId());
    } else if (assignmentType.equals(AssignmentType.SCRIPT)) {
      kaleoTaskAssignment.setAssigneeClassName(AssignmentType.SCRIPT.name());

      ScriptAssignment scriptAssignment = (ScriptAssignment) assignment;

      kaleoTaskAssignment.setAssigneeScript(scriptAssignment.getScript());

      ScriptLanguage scriptLanguage = scriptAssignment.getScriptLanguage();

      kaleoTaskAssignment.setAssigneeScriptLanguage(scriptLanguage.getValue());
      kaleoTaskAssignment.setAssigneeScriptRequiredContexts(
          scriptAssignment.getScriptRequiredContexts());
    } else if (assignmentType.equals(AssignmentType.USER)) {
      kaleoTaskAssignment.setAssigneeClassName(User.class.getName());

      UserAssignment userAssignment = (UserAssignment) assignment;

      User user = null;

      if (userAssignment.getUserId() > 0) {
        user = userLocalService.getUser(userAssignment.getUserId());
      } else if (Validator.isNotNull(userAssignment.getEmailAddress())) {
        user =
            userLocalService.getUserByEmailAddress(
                serviceContext.getCompanyId(), userAssignment.getEmailAddress());
      } else if (Validator.isNotNull(userAssignment.getScreenName())) {
        user =
            userLocalService.getUserByScreenName(
                serviceContext.getCompanyId(), userAssignment.getScreenName());
      }

      if (user != null) {
        kaleoTaskAssignment.setAssigneeClassPK(user.getUserId());
      } else {
        kaleoTaskAssignment.setAssigneeClassPK(0);
      }
    }
  }
  @Indexable(type = IndexableType.REINDEX)
  public DLFolder updateFolder(
      long folderId,
      long parentFolderId,
      String name,
      String description,
      long defaultFileEntryTypeId,
      List<Long> fileEntryTypeIds,
      boolean overrideFileEntryTypes,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    boolean hasLock = hasFolderLock(serviceContext.getUserId(), folderId);

    Lock lock = null;

    if (!hasLock) {

      // Lock

      lock =
          lockFolder(
              serviceContext.getUserId(), folderId, null, false, DLFolderImpl.LOCK_EXPIRATION_TIME);
    }

    try {

      // File entry types

      DLFolder dlFolder = null;

      if (folderId > DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
        dlFolder =
            dlFolderLocalService.updateFolderAndFileEntryTypes(
                serviceContext.getUserId(),
                folderId,
                parentFolderId,
                name,
                description,
                defaultFileEntryTypeId,
                fileEntryTypeIds,
                overrideFileEntryTypes,
                serviceContext);

        dlFileEntryTypeLocalService.cascadeFileEntryTypes(serviceContext.getUserId(), dlFolder);
      }

      // Workflow definitions

      List<ObjectValuePair<Long, String>> workflowDefinitionOVPs =
          new ArrayList<ObjectValuePair<Long, String>>();

      if (fileEntryTypeIds.isEmpty()) {
        fileEntryTypeIds.add(DLFileEntryTypeConstants.FILE_ENTRY_TYPE_ID_ALL);
      } else {
        workflowDefinitionOVPs.add(
            new ObjectValuePair<Long, String>(
                DLFileEntryTypeConstants.FILE_ENTRY_TYPE_ID_ALL, StringPool.BLANK));
      }

      for (long fileEntryTypeId : fileEntryTypeIds) {
        String workflowDefinition =
            ParamUtil.getString(serviceContext, "workflowDefinition" + fileEntryTypeId);

        workflowDefinitionOVPs.add(
            new ObjectValuePair<Long, String>(fileEntryTypeId, workflowDefinition));
      }

      workflowDefinitionLinkLocalService.updateWorkflowDefinitionLinks(
          serviceContext.getUserId(),
          serviceContext.getCompanyId(),
          serviceContext.getScopeGroupId(),
          DLFolder.class.getName(),
          folderId,
          workflowDefinitionOVPs);

      return dlFolder;
    } finally {
      if (!hasLock) {

        // Unlock

        unlockFolder(folderId, lock.getUuid());
      }
    }
  }