@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;
  }
  public List<KaleoTaskInstanceToken> getKaleoTaskInstanceTokens(
      long kaleoInstanceId,
      Boolean completed,
      int start,
      int end,
      OrderByComparator orderByComparator,
      ServiceContext serviceContext)
      throws SystemException {

    long userId = serviceContext.getUserId();

    if (userId == 0) {
      DynamicQuery dynamicQuery = buildDynamicQuery(kaleoInstanceId, completed, serviceContext);

      return dynamicQuery(dynamicQuery, start, end, orderByComparator);
    } else {
      KaleoTaskInstanceTokenQuery kaleoTaskInstanceTokenQuery =
          new KaleoTaskInstanceTokenQuery(serviceContext);

      kaleoTaskInstanceTokenQuery.setAssigneeClassName(User.class.getName());
      kaleoTaskInstanceTokenQuery.setAssigneeClassPK(serviceContext.getUserId());
      kaleoTaskInstanceTokenQuery.setCompleted(completed);
      kaleoTaskInstanceTokenQuery.setEnd(end);
      kaleoTaskInstanceTokenQuery.setKaleoInstanceId(kaleoInstanceId);
      kaleoTaskInstanceTokenQuery.setOrderByComparator(orderByComparator);
      kaleoTaskInstanceTokenQuery.setStart(start);

      return kaleoTaskInstanceTokenFinder.findKaleoTaskInstanceTokens(kaleoTaskInstanceTokenQuery);
    }
  }
Beispiel #4
0
  protected String getUserName(long userId, ServiceContext serviceContext) {
    try {
      if (userId <= 0) {
        return StringPool.BLANK;
      }

      User user = UserLocalServiceUtil.getUserById(userId);

      if (user.getUserId() == serviceContext.getUserId()) {
        return HtmlUtil.escape(user.getFirstName());
      }

      String userName = user.getFullName();

      Group group = user.getGroup();

      if (group.getGroupId() == serviceContext.getScopeGroupId()) {
        return HtmlUtil.escape(userName);
      }

      String userDisplayURL = user.getDisplayURL(serviceContext.getThemeDisplay());

      userName =
          "******"user\" href=\"" + userDisplayURL + "\">" + HtmlUtil.escape(userName) + "</a>";

      return userName;
    } catch (Exception e) {
      return StringPool.BLANK;
    }
  }
  @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;
  }
  public KaleoTaskInstanceToken completeKaleoTaskInstanceToken(
      long kaleoTaskInstanceTokenId, ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Kaleo task instance token

    KaleoTaskInstanceToken kaleoTaskInstanceToken =
        kaleoTaskInstanceTokenPersistence.findByPrimaryKey(kaleoTaskInstanceTokenId);

    kaleoTaskInstanceToken.setCompletionUserId(serviceContext.getUserId());
    kaleoTaskInstanceToken.setCompleted(true);
    kaleoTaskInstanceToken.setCompletionDate(new Date());

    kaleoTaskInstanceTokenPersistence.update(kaleoTaskInstanceToken, false);

    // Kaleo task assignment instance

    kaleoTaskAssignmentInstanceLocalService.completeKaleoTaskInstanceToken(
        kaleoTaskInstanceTokenId, serviceContext);

    // Kaleo timers

    kaleoTimerInstanceTokenLocalService.completeKaleoTimerInstanceTokens(
        kaleoTaskInstanceToken.getKaleoInstanceTokenId(), serviceContext);

    return kaleoTaskInstanceToken;
  }
  @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);
  }
  public void updateFoo(
      long fooId,
      String field1,
      boolean field2,
      int field3,
      Date field4,
      String field5,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

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

    Foo foo = fooPersistence.findByPrimaryKey(fooId);

    foo.setModifiedDate(new Date());
    foo.setField1(field1);
    foo.setField2(field2);
    foo.setField3(field3);
    foo.setField4(field4);
    foo.setField5(field5);
    foo.setExpandoBridgeAttributes(serviceContext);

    fooPersistence.update(foo, false);

    updateAsset(
        user.getUserId(),
        foo,
        serviceContext.getAssetCategoryIds(),
        serviceContext.getAssetTagNames());
  }
  protected void addSearchByUserRolesCriterion(
      Criteria criteria, Boolean searchByUserRoles, ServiceContext serviceContext)
      throws SystemException {

    if (searchByUserRoles == null) {
      return;
    }

    Criteria assigneesCriteria = criteria.createCriteria("assignees");

    if (!searchByUserRoles) {
      assigneesCriteria.add(Restrictions.eq("assigneeClassName", User.class.getName()));
      assigneesCriteria.add(Restrictions.eq("assigneeClassPK", serviceContext.getUserId()));

      return;
    }

    List<Long> roleIds = RoleRetrievalUtil.getRoleIds(serviceContext);

    List<UserGroupRole> userGroupRoles =
        UserGroupRoleLocalServiceUtil.getUserGroupRoles(serviceContext.getUserId());

    if (userGroupRoles.isEmpty()) {
      assigneesCriteria.add(Restrictions.eq("assigneeClassName", Role.class.getName()));
      assigneesCriteria.add(
          Restrictions.in("assigneeClassPK", roleIds.toArray(new Long[roleIds.size()])));
    } else {
      Junction junction = Restrictions.disjunction();

      junction.add(
          Restrictions.and(
              Restrictions.eq("assigneeClassName", Role.class.getName()),
              Restrictions.in("assigneeClassPK", roleIds.toArray(new Long[roleIds.size()]))));

      for (UserGroupRole userGroupRole : userGroupRoles) {
        junction.add(
            Restrictions.and(
                Restrictions.eq("groupId", userGroupRole.getGroupId()),
                Restrictions.and(
                    Restrictions.eq("assigneeClassName", Role.class.getName()),
                    Restrictions.eq("assigneeClassPK", userGroupRole.getRoleId()))));
      }

      assigneesCriteria.add(junction);
    }
  }
Beispiel #11
0
  public void processAction(
      ActionMapping mapping,
      ActionForm form,
      PortletConfig portletConfig,
      ActionRequest actionRequest,
      ActionResponse actionResponse)
      throws Exception {

    UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
    String fileLogoParam = "file";
    File file = uploadRequest.getFile(fileLogoParam);
    ServiceContext sc;

    try {

      sc = ServiceContextFactory.getInstance(this.getClass().getName(), actionRequest);
      // Make sure the uploaded images can be view by any one;
      sc.setAddCommunityPermissions(true);
      sc.setAddGuestPermissions(true);

      IGFolder folder = Functions.getIGFolder(sc);
      // String fileName = uploadRequest.getFileName(fileLogoParam);
      String contentType = uploadRequest.getContentType(fileLogoParam);

      IGImage image =
          IGImageLocalServiceUtil.addImage(
              sc.getUserId(),
              folder.getFolderId(),
              file.getName() + (new Time()).toString(),
              file.getName(),
              file,
              contentType,
              sc);

      HttpServletRequest servletRequest = PortalUtil.getHttpServletRequest(actionRequest);
      String res =
          image.getImageId()
              + "|"
              + ProGateUtil.getImageURL(image.getSmallImageId(), servletRequest)
              + "|"
              + ProGateUtil.getImageURL(image.getLargeImageId(), servletRequest);
      ProGateUtil.servletPrint(actionResponse, res);

    } catch (PortalException e) {
      // TODO Auto-generated catch block

      e.printStackTrace();
    } catch (SystemException se) {

      se.printStackTrace();
    } catch (NullPointerException e2) {

      e2.printStackTrace();
    }
  }
  public int getKaleoTaskInstanceTokensCount(
      long kaleoInstanceId, Boolean completed, ServiceContext serviceContext)
      throws SystemException {

    long userId = serviceContext.getUserId();

    if (userId == 0) {
      DynamicQuery dynamicQuery = buildDynamicQuery(kaleoInstanceId, completed, serviceContext);

      return (int) dynamicQueryCount(dynamicQuery);
    } else {
      KaleoTaskInstanceTokenQuery kaleoTaskInstanceTokenQuery =
          new KaleoTaskInstanceTokenQuery(serviceContext);

      kaleoTaskInstanceTokenQuery.setAssigneeClassName(User.class.getName());
      kaleoTaskInstanceTokenQuery.setAssigneeClassPK(serviceContext.getUserId());
      kaleoTaskInstanceTokenQuery.setCompleted(completed);

      return kaleoTaskInstanceTokenFinder.countKaleoTaskInstanceTokens(kaleoTaskInstanceTokenQuery);
    }
  }
Beispiel #13
0
  public TtUser getLoggedInUser() {
    // TODO if this does not work this must be done in Vaadin application where
    // portlet request must be passed to PortalUtil class
    Long userId = serviceContext.getUserId();
    TtUser usr = new TtUser();
    usr.setUserId(userId);
    try {
      usr.setUserName(usrService.getUser(userId).getLogin());
    } catch (Exception exp) {

    }
    throw new UnsupportedOperationException("Not supported yet.");
  }
  @Override
  public DLFileEntry updateFileEntryFileEntryType(
      DLFileEntry dlFileEntry, ServiceContext serviceContext) throws PortalException {

    long groupId = serviceContext.getScopeGroupId();
    long folderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;

    DLFolder dlFolder = dlFolderPersistence.fetchByPrimaryKey(dlFileEntry.getFolderId());

    if (dlFolder != null) {
      groupId = dlFolder.getGroupId();
      folderId = dlFolder.getFolderId();
    }

    List<DLFileEntryType> dlFileEntryTypes =
        getFolderFileEntryTypes(
            PortalUtil.getCurrentAndAncestorSiteGroupIds(groupId), folderId, true);

    List<Long> fileEntryTypeIds = getFileEntryTypeIds(dlFileEntryTypes);

    if (fileEntryTypeIds.contains(dlFileEntry.getFileEntryTypeId())) {
      return dlFileEntry;
    }

    long defaultFileEntryTypeId = getDefaultFileEntryTypeId(folderId);

    DLFileVersion dlFileVersion =
        dlFileVersionLocalService.getLatestFileVersion(dlFileEntry.getFileEntryId(), true);

    if (dlFileVersion.isPending()) {
      workflowInstanceLinkLocalService.deleteWorkflowInstanceLink(
          dlFileVersion.getCompanyId(), dlFileEntry.getGroupId(),
          DLFileEntry.class.getName(), dlFileVersion.getFileVersionId());
    }

    return dlFileEntryLocalService.updateFileEntry(
        serviceContext.getUserId(),
        dlFileEntry.getFileEntryId(),
        null,
        null,
        null,
        null,
        null,
        false,
        defaultFileEntryTypeId,
        null,
        null,
        null,
        0,
        serviceContext);
  }
  @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 void addDossierStepResources(
     DossierStep dossierStep,
     String[] groupPermissions,
     String[] guestPermissions,
     ServiceContext serviceContext)
     throws PortalException, SystemException {
   resourceLocalService.addModelResources(
       dossierStep.getCompanyId(),
       serviceContext.getScopeGroupId(),
       serviceContext.getUserId(),
       DossierStep.class.getName(),
       dossierStep.getDossierStepId(),
       groupPermissions,
       guestPermissions);
 }
 private void addStatisticByDomainResources(
     StatisticByDomain statisticByDomain,
     String[] groupPermissions,
     String[] guestPermissions,
     ServiceContext serviceContext)
     throws PortalException, SystemException {
   resourceLocalService.addModelResources(
       statisticByDomain.getCompanyId(),
       serviceContext.getScopeGroupId(),
       serviceContext.getUserId(),
       StatisticByDomain.class.getName(),
       statisticByDomain.getStatisticByDomainId(),
       groupPermissions,
       guestPermissions);
 }
  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 void addDossierStepResources(
     DossierStep dossierStep,
     boolean addGroupPermission,
     boolean addGuestPermission,
     ServiceContext serviceContext)
     throws PortalException, SystemException {
   resourceLocalService.addResources(
       dossierStep.getCompanyId(),
       serviceContext.getScopeGroupId(),
       serviceContext.getUserId(),
       DossierStep.class.getName(),
       dossierStep.getDossierStepId(),
       false,
       addGroupPermission,
       addGuestPermission);
 }
  @Override
  public int getWorkflowTaskCountByUser(long companyId, long userId, Boolean completed)
      throws WorkflowException {

    try {
      ServiceContext serviceContext = new ServiceContext();

      serviceContext.setCompanyId(companyId);
      serviceContext.setUserId(userId);

      return KaleoTaskInstanceTokenLocalServiceUtil.getKaleoTaskInstanceTokensCount(
          User.class.getName(), serviceContext.getUserId(), completed, serviceContext);
    } catch (Exception e) {
      throw new WorkflowException(e);
    }
  }
 private void addStatisticByDomainResources(
     StatisticByDomain statisticByDomain,
     boolean addGroupPermission,
     boolean addGuestPermission,
     ServiceContext serviceContext)
     throws PortalException, SystemException {
   resourceLocalService.addResources(
       statisticByDomain.getCompanyId(),
       serviceContext.getScopeGroupId(),
       serviceContext.getUserId(),
       StatisticByDomain.class.getName(),
       statisticByDomain.getStatisticByDomainId(),
       false,
       addGroupPermission,
       addGuestPermission);
 }
  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());
  }
  private LayoutRevision _getLayoutRevision(Layout layout, LayoutRevision layoutRevision)
      throws PortalException, SystemException {

    if (layoutRevision != null) {
      return layoutRevision;
    }

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (!serviceContext.isSignedIn()) {
      LayoutRevision lastLayoutRevision = null;

      lastLayoutRevision =
          LayoutRevisionLocalServiceUtil.fetchLastLayoutRevision(layout.getPlid(), true);

      if (lastLayoutRevision == null) {
        lastLayoutRevision =
            LayoutRevisionLocalServiceUtil.fetchLastLayoutRevision(layout.getPlid(), false);
      }

      return lastLayoutRevision;
    }

    User user = UserLocalServiceUtil.getUser(serviceContext.getUserId());

    long layoutSetBranchId = ParamUtil.getLong(serviceContext, "layoutSetBranchId");

    LayoutSet layoutSet = layout.getLayoutSet();

    LayoutSetBranch layoutSetBranch =
        LayoutSetBranchLocalServiceUtil.getUserLayoutSetBranch(
            serviceContext.getUserId(),
            layout.getGroupId(),
            layout.isPrivateLayout(),
            layoutSet.getLayoutSetId(),
            layoutSetBranchId);

    layoutSetBranchId = layoutSetBranch.getLayoutSetBranchId();

    long layoutRevisionId = ParamUtil.getLong(serviceContext, "layoutRevisionId");

    if (layoutRevisionId <= 0) {
      layoutRevisionId =
          StagingUtil.getRecentLayoutRevisionId(user, layoutSetBranchId, layout.getPlid());
    }

    if (layoutRevisionId > 0) {
      layoutRevision = LayoutRevisionLocalServiceUtil.fetchLayoutRevision(layoutRevisionId);

      if (layoutRevision.getStatus() != WorkflowConstants.STATUS_INACTIVE) {

        return layoutRevision;
      }

      layoutRevision = null;
    }

    List<LayoutRevision> layoutRevisions =
        LayoutRevisionLocalServiceUtil.getLayoutRevisions(
            layoutSetBranchId,
            layout.getPlid(),
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS,
            new LayoutRevisionCreateDateComparator(true));

    if (!layoutRevisions.isEmpty()) {
      layoutRevision = layoutRevisions.get(0);

      for (LayoutRevision curLayoutRevision : layoutRevisions) {
        if (curLayoutRevision.isHead()) {
          layoutRevision = curLayoutRevision;

          break;
        }
      }
    }

    if (layoutRevision != null) {
      StagingUtil.setRecentLayoutRevisionId(
          user, layoutSetBranchId, layout.getPlid(), layoutRevision.getLayoutRevisionId());

      return layoutRevision;
    }

    LayoutBranch layoutBranch =
        LayoutBranchLocalServiceUtil.getMasterLayoutBranch(
            layoutSetBranchId, layout.getPlid(), serviceContext);

    if (!MergeLayoutPrototypesThreadLocal.isInProgress()) {
      serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);
    }

    return LayoutRevisionLocalServiceUtil.addLayoutRevision(
        serviceContext.getUserId(),
        layoutSetBranchId,
        layoutBranch.getLayoutBranchId(),
        LayoutRevisionConstants.DEFAULT_PARENT_LAYOUT_REVISION_ID,
        false,
        layout.getPlid(),
        LayoutConstants.DEFAULT_PLID,
        layout.isPrivateLayout(),
        layout.getName(),
        layout.getTitle(),
        layout.getDescription(),
        layout.getKeywords(),
        layout.getRobots(),
        layout.getTypeSettings(),
        layout.getIconImage(),
        layout.getIconImageId(),
        layout.getThemeId(),
        layout.getColorSchemeId(),
        layout.getWapThemeId(),
        layout.getWapColorSchemeId(),
        layout.getCss(),
        serviceContext);
  }
  @Override
  protected void handleActionRequestInternal(ActionRequest request, ActionResponse response)
      throws Exception {

    request.setCharacterEncoding("UTF-8");
    String msg = "";
    int articleId = 0;
    int isAdd = 0;
    int addSuccess = 0;

    UploadPortletRequest uploadPortlet = PortalUtil.getUploadPortletRequest(request);
    String currentURL = uploadPortlet.getParameter(News_Const.CURRENT_URL);
    String title = uploadPortlet.getParameter(News_Const.TITLE);
    String content = uploadPortlet.getParameter(News_Const.CONTENT);
    String keyword = uploadPortlet.getParameter(News_Const.KEY_WORD);
    String mark = uploadPortlet.getParameter(News_Const.MARK);
    String description = uploadPortlet.getParameter(News_Const.DESCRIPTION);
    String smallImagePath =
        Functions.getPathOfUploadImage(request, response, uploadPortlet, News_Const.SMALL_IMAGE);
    try {
      // Get current User
      com.liferay.portal.service.ServiceContext sc =
          ServiceContextFactory.getInstance(this.getClass().getName(), request);
      com.liferay.portal.model.User user = UserLocalServiceUtil.getUser(sc.getUserId());
      Long userIdTemp = user.getUserId();
      int userId = userIdTemp.intValue();
      String articleType = ProGateJournalArticleTypesLocalServiceUtil.getArticleTypeNews();
      ProGateJournalArticle article = null;
      if (mark != null) {
        article =
            ProGateJournalArticleLocalServiceUtil.createNews(
                Integer.toString(0),
                userId,
                title,
                articleType,
                description,
                content,
                smallImagePath,
                "",
                true,
                "");
      } else {
        article =
            ProGateJournalArticleLocalServiceUtil.createNews(
                Integer.toString(0),
                userId,
                title,
                articleType,
                description,
                content,
                smallImagePath,
                "",
                false,
                "");
      }

      if (article != null) {
        msg = "Bạn đã thêm tin tức thành công.";
        addSuccess = 1;
        articleId = article.getPrimaryKey();
      }
    } catch (Exception e) {
      // TODO: handle exception
      addSuccess = 2;
      msg = "Đã có lỗi xảy ra trong quá trình thêm tin tức.";
    }
    isAdd = 1;
    response.setRenderParameter(News_Const.CMD, Integer.toString(isAdd));
    response.setRenderParameter(News_Const.MSG_TEXT, msg);
    response.setRenderParameter(News_Const.ADD_SUCCESS, Integer.toString(addSuccess));
    response.setRenderParameter(News_Const.ARTICLE_ID, Integer.toString(articleId));
    response.setRenderParameter(News_Const.CURRENT_URL, currentURL);
    response.setRenderParameter("action", "updateNewsProGate");
  }
  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;
  }
  public TasksEntry updateTasksEntry(
      long tasksEntryId,
      String title,
      int priority,
      long assigneeUserId,
      long resolverUserId,
      int dueDateMonth,
      int dueDateDay,
      int dueDateYear,
      int dueDateHour,
      int dueDateMinute,
      boolean neverDue,
      int status,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Tasks entry

    Date now = new Date();

    TasksEntry tasksEntry = tasksEntryPersistence.findByPrimaryKey(tasksEntryId);

    User user = UserLocalServiceUtil.getUserById(tasksEntry.getUserId());

    Date dueDate = null;

    if (!neverDue) {
      dueDate =
          PortalUtil.getDate(
              dueDateMonth,
              dueDateDay,
              dueDateYear,
              dueDateHour,
              dueDateMinute,
              user.getTimeZone(),
              new TasksEntryDueDateException());
    }

    tasksEntry.setModifiedDate(now);
    tasksEntry.setTitle(title);
    tasksEntry.setPriority(priority);
    tasksEntry.setAssigneeUserId(assigneeUserId);
    tasksEntry.setDueDate(dueDate);

    if (status == TasksEntryConstants.STATUS_RESOLVED) {
      tasksEntry.setResolverUserId(resolverUserId);
      tasksEntry.setFinishDate(now);
    } else {
      tasksEntry.setResolverUserId(0);
      tasksEntry.setFinishDate(null);
    }

    tasksEntry.setStatus(status);

    tasksEntryPersistence.update(tasksEntry, false);

    // Asset

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

    // Social

    int activity = TasksActivityKeys.UPDATE_ENTRY;

    if (status == TasksEntryConstants.STATUS_RESOLVED) {
      activity = TasksActivityKeys.RESOLVE_ENTRY;
    } else if (status == TasksEntryConstants.STATUS_REOPENED) {
      activity = TasksActivityKeys.REOPEN_ENTRY;
    }

    SocialActivityLocalServiceUtil.addActivity(
        serviceContext.getUserId(),
        tasksEntry.getGroupId(),
        TasksEntry.class.getName(),
        tasksEntryId,
        activity,
        StringPool.BLANK,
        assigneeUserId);

    return tasksEntry;
  }
  @Test
  public void testChildLayoutFriendlyURL() throws Exception {
    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext();

    UserGroup userGroup =
        UserGroupLocalServiceUtil.addUserGroup(
            TestPropsValues.getUserId(),
            TestPropsValues.getCompanyId(),
            "Test " + RandomTestUtil.nextInt(),
            StringPool.BLANK,
            serviceContext);

    _group = userGroup.getGroup();

    Layout homeLayout =
        LayoutLocalServiceUtil.addLayout(
            serviceContext.getUserId(),
            _group.getGroupId(),
            true,
            LayoutConstants.DEFAULT_PARENT_LAYOUT_ID,
            "Home",
            StringPool.BLANK,
            StringPool.BLANK,
            LayoutConstants.TYPE_PORTLET,
            false,
            StringPool.BLANK,
            serviceContext);

    LayoutLocalServiceUtil.addLayout(
        serviceContext.getUserId(),
        _group.getGroupId(),
        true,
        homeLayout.getLayoutId(),
        "Child Layout",
        StringPool.BLANK,
        StringPool.BLANK,
        LayoutConstants.TYPE_PORTLET,
        false,
        StringPool.BLANK,
        serviceContext);

    String actualURL =
        PortalUtil.getActualURL(
            userGroup.getGroup().getGroupId(),
            true,
            Portal.PATH_MAIN,
            "/~/" + userGroup.getUserGroupId() + "/child-layout",
            new HashMap<String, String[]>(),
            getRequestContext());

    Assert.assertNotNull(actualURL);

    try {
      PortalUtil.getActualURL(
          userGroup.getGroup().getGroupId(),
          true,
          Portal.PATH_MAIN,
          "/~/" + userGroup.getUserGroupId() + "/non-existing-child-layout",
          new HashMap<String, String[]>(),
          getRequestContext());

      Assert.fail();
    } catch (NoSuchLayoutException nsle) {
    }
  }
  protected void searchMyEntries() throws Exception {
    User user1 = UserTestUtil.addUser(null, 0);

    long initialUser1SearchGroupEntriesCount =
        searchGroupEntriesCount(group.getGroupId(), user1.getUserId());

    User user2 = UserTestUtil.addUser(null, 0);

    long initialUser2SearchGroupEntriesCount =
        searchGroupEntriesCount(group.getGroupId(), user2.getUserId());

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(group.getGroupId());

    BaseModel<?> parentBaseModel1 = getParentBaseModel(group, serviceContext);
    BaseModel<?> parentBaseModel2 = getParentBaseModel(group, serviceContext);

    String name = PrincipalThreadLocal.getName();

    long userId = serviceContext.getUserId();

    try {
      PrincipalThreadLocal.setName(user1.getUserId());

      serviceContext.setUserId(user1.getUserId());

      baseModel =
          addBaseModel(parentBaseModel1, true, RandomTestUtil.randomString(), serviceContext);
      baseModel =
          addBaseModel(parentBaseModel1, true, RandomTestUtil.randomString(), serviceContext);
      baseModel =
          addBaseModel(parentBaseModel2, true, RandomTestUtil.randomString(), serviceContext);

      PrincipalThreadLocal.setName(user2.getUserId());

      serviceContext.setUserId(user2.getUserId());

      baseModel =
          addBaseModel(parentBaseModel1, true, RandomTestUtil.randomString(), serviceContext);
      baseModel =
          addBaseModel(parentBaseModel2, true, RandomTestUtil.randomString(), serviceContext);
    } finally {
      PrincipalThreadLocal.setName(name);

      serviceContext.setUserId(userId);
    }

    Assert.assertEquals(
        initialUser1SearchGroupEntriesCount + 3,
        searchGroupEntriesCount(group.getGroupId(), user1.getUserId()));
    Assert.assertEquals(
        initialUser2SearchGroupEntriesCount + 2,
        searchGroupEntriesCount(group.getGroupId(), user2.getUserId()));

    moveParentBaseModelToTrash((Long) parentBaseModel2.getPrimaryKeyObj());

    Assert.assertEquals(
        initialUser1SearchGroupEntriesCount + 2,
        searchGroupEntriesCount(group.getGroupId(), user1.getUserId()));
    Assert.assertEquals(
        initialUser2SearchGroupEntriesCount + 1,
        searchGroupEntriesCount(group.getGroupId(), user2.getUserId()));

    TrashHandler parentTrashHandler =
        TrashHandlerRegistryUtil.getTrashHandler(getParentBaseModelClassName());

    parentTrashHandler.restoreTrashEntry(
        user1.getUserId(), (Long) parentBaseModel2.getPrimaryKeyObj());

    Assert.assertEquals(
        initialUser1SearchGroupEntriesCount + 3,
        searchGroupEntriesCount(group.getGroupId(), user1.getUserId()));
    Assert.assertEquals(
        initialUser2SearchGroupEntriesCount + 2,
        searchGroupEntriesCount(group.getGroupId(), user2.getUserId()));
  }
  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());
    }
  }