protected void doExportStagedModel(
      PortletDataContext portletDataContext, CalendarResource calendarResource) throws Exception {

    Element calendarResourceElement = portletDataContext.getExportDataElement(calendarResource);

    for (Calendar calendar : calendarResource.getCalendars()) {
      StagedModelDataHandlerUtil.exportReferenceStagedModel(
          portletDataContext, calendarResource, calendar, PortletDataContext.REFERENCE_TYPE_STRONG);
    }

    if (calendarResource.getClassNameId() == PortalUtil.getClassNameId(User.class)) {

      User user = UserLocalServiceUtil.getUser(calendarResource.getClassPK());

      portletDataContext.addReferenceElement(
          calendarResource,
          calendarResourceElement,
          user,
          User.class,
          PortletDataContext.REFERENCE_TYPE_DEPENDENCY_DISPOSABLE,
          true);
    }

    portletDataContext.addClassedModel(
        calendarResourceElement,
        ExportImportPathUtil.getModelPath(calendarResource),
        calendarResource);
  }
  private static User _getUser(HttpServletRequest request) throws Exception {
    HttpSession session = request.getSession();

    if (PortalSessionThreadLocal.getHttpSession() == null) {
      PortalSessionThreadLocal.setHttpSession(session);
    }

    User user = PortalUtil.getUser(request);

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

    String userIdString = (String) session.getAttribute("j_username");
    String password = (String) session.getAttribute("j_password");

    if ((userIdString != null) && (password != null)) {
      long userId = GetterUtil.getLong(userIdString);

      user = UserLocalServiceUtil.getUser(userId);
    } else {
      long companyId = PortalUtil.getCompanyId(request);

      Company company = CompanyLocalServiceUtil.getCompany(companyId);

      user = company.getDefaultUser();
    }

    return user;
  }
 public com.liferay.portal.model.User getLiferayUser() {
   try {
     return UserLocalServiceUtil.getUser(liferayUserId);
   } catch (Exception ex) {
     return null;
   }
 }
  protected OAuthToken getOAuthToken(
      SecurityToken securityToken, String serviceName, String tokenName) throws GadgetException {

    long userId = GetterUtil.getLong(securityToken.getViewerId());

    User user = null;

    try {
      user = UserLocalServiceUtil.getUser(userId);
    } catch (Exception e) {
      throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e);
    }

    Gadget gadget = null;

    try {
      gadget = GadgetLocalServiceUtil.getGadget(user.getCompanyId(), securityToken.getAppUrl());
    } catch (Exception e) {
      throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e);
    }

    OAuthToken oAuthToken = null;

    try {
      oAuthToken =
          OAuthTokenLocalServiceUtil.getOAuthToken(
              userId, gadget.getGadgetId(), serviceName, securityToken.getModuleId(), tokenName);
    } catch (Exception e) {
    }

    return oAuthToken;
  }
  public MBMessage addPrivateMessageBranch(
      long userId,
      long parentMBMessageId,
      String body,
      List<ObjectValuePair<String, InputStream>> inputStreamOVPs,
      ThemeDisplay themeDisplay)
      throws PortalException {

    long mbThreadId = 0;

    MBMessage parentMessage = MBMessageLocalServiceUtil.getMBMessage(parentMBMessageId);

    List<User> recipients = new ArrayList<>();

    recipients.add(UserLocalServiceUtil.getUser(parentMessage.getUserId()));

    return addPrivateMessage(
        userId,
        mbThreadId,
        parentMBMessageId,
        recipients,
        parentMessage.getSubject(),
        body,
        inputStreamOVPs,
        themeDisplay);
  }
  protected List<User> parseRecipients(long userId, String to) throws PortalException {

    User user = UserLocalServiceUtil.getUser(userId);

    String[] recipients = StringUtil.split(to);

    List<User> users = new ArrayList<>();

    for (String recipient : recipients) {
      int x = recipient.indexOf(CharPool.LESS_THAN);
      int y = recipient.indexOf(CharPool.GREATER_THAN);

      try {
        String screenName = recipient;

        if ((x != -1) && (y != -1)) {
          screenName = recipient.substring(x + 1, y);
        }

        User recipientUser =
            UserLocalServiceUtil.getUserByScreenName(user.getCompanyId(), screenName);

        if (!users.contains(recipientUser)) {
          users.add(recipientUser);
        }
      } catch (NoSuchUserException nsue) {
      }
    }

    return users;
  }
  @Test
  public void testUnassignUserFromRequiredGroups() throws Exception {
    long[] userIds = addUsers();
    long[] standardGroupIds = addStandardGroups();
    long[] requiredGroupIds = addRequiredGroups();

    User user = UserLocalServiceUtil.getUser(userIds[0]);

    List<Group> groups = user.getGroups();

    Assert.assertEquals(1, groups.size());

    long[] userGroupIds =
        ArrayUtil.append(standardGroupIds, requiredGroupIds, new long[] {user.getGroupId()});

    MembershipPolicyTestUtil.updateUser(
        user, null, null, userGroupIds, null, Collections.<UserGroupRole>emptyList());

    groups = user.getGroups();

    Assert.assertEquals(userGroupIds.length, groups.size());

    MembershipPolicyTestUtil.updateUser(
        user, null, null, requiredGroupIds, null, Collections.<UserGroupRole>emptyList());

    groups = user.getGroups();

    Assert.assertEquals(requiredGroupIds.length, groups.size());
  }
  private void _buildParentGroupsBreadcrumb(
      LayoutSet layoutSet, PortletURL portletURL, ThemeDisplay themeDisplay, StringBundler sb)
      throws Exception {
    Group group = layoutSet.getGroup();

    if (group.isOrganization()) {
      Organization organization =
          OrganizationLocalServiceUtil.getOrganization(group.getOrganizationId());

      Organization parentOrganization = organization.getParentOrganization();

      if (parentOrganization != null) {
        Group parentGroup = parentOrganization.getGroup();

        LayoutSet parentLayoutSet =
            LayoutSetLocalServiceUtil.getLayoutSet(
                parentGroup.getGroupId(), layoutSet.isPrivateLayout());

        _buildParentGroupsBreadcrumb(parentLayoutSet, portletURL, themeDisplay, sb);
      }
    } else if (group.isUser()) {
      User groupUser = UserLocalServiceUtil.getUser(group.getClassPK());

      List<Organization> organizations =
          OrganizationLocalServiceUtil.getUserOrganizations(groupUser.getUserId(), true);

      if (!organizations.isEmpty()) {
        Organization organization = organizations.get(0);

        Group parentGroup = organization.getGroup();

        LayoutSet parentLayoutSet =
            LayoutSetLocalServiceUtil.getLayoutSet(
                parentGroup.getGroupId(), layoutSet.isPrivateLayout());

        _buildParentGroupsBreadcrumb(parentLayoutSet, portletURL, themeDisplay, sb);
      }
    }

    int layoutsPageCount = 0;

    if (layoutSet.isPrivateLayout()) {
      layoutsPageCount = group.getPrivateLayoutsPageCount();
    } else {
      layoutsPageCount = group.getPublicLayoutsPageCount();
    }

    if ((layoutsPageCount > 0) && !group.getName().equals(GroupConstants.GUEST)) {
      String layoutSetFriendlyURL = PortalUtil.getLayoutSetFriendlyURL(layoutSet, themeDisplay);

      sb.append("<li><span><a href=\"");
      sb.append(layoutSetFriendlyURL);
      sb.append("\">");
      sb.append(HtmlUtil.escape(group.getDescriptiveName()));
      sb.append("</a></span></li>");
    }
  }
  @Test(expected = MembershipPolicyException.class)
  public void testAssignUserToForbiddenGroups() throws Exception {
    long[] userIds = addUsers();

    User user = UserLocalServiceUtil.getUser(userIds[0]);

    MembershipPolicyTestUtil.updateUser(
        user, null, null, addForbiddenGroups(), null, Collections.<UserGroupRole>emptyList());
  }
  @Test
  public void testPropagateWhenAssigningUserToRequiredGroups() throws Exception {

    long[] userIds = addUsers();

    User user = UserLocalServiceUtil.getUser(userIds[0]);

    MembershipPolicyTestUtil.updateUser(
        user, null, null, addRequiredGroups(), null, Collections.<UserGroupRole>emptyList());

    Assert.assertTrue(isPropagateMembership());
  }
  protected GoogleDriveSession buildGoogleDriveSession() throws IOException, PortalException {

    long userId = PrincipalThreadLocal.getUserId();

    User user = UserLocalServiceUtil.getUser(userId);

    if (user.isDefaultUser()) {
      throw new PrincipalException("User is not authenticated");
    }

    GoogleCredential.Builder builder = new GoogleCredential.Builder();

    String googleClientId = PrefsPropsUtil.getString(user.getCompanyId(), "google-client-id");
    String googleClientSecret =
        PrefsPropsUtil.getString(user.getCompanyId(), "google-client-secret");

    builder.setClientSecrets(googleClientId, googleClientSecret);

    JacksonFactory jsonFactory = new JacksonFactory();

    builder.setJsonFactory(jsonFactory);

    HttpTransport httpTransport = new NetHttpTransport();

    builder.setTransport(httpTransport);

    GoogleCredential googleCredential = builder.build();

    ExpandoBridge expandoBridge = user.getExpandoBridge();

    String googleAccessToken =
        GetterUtil.getString(expandoBridge.getAttribute("googleAccessToken", false));

    googleCredential.setAccessToken(googleAccessToken);

    String googleRefreshToken =
        GetterUtil.getString(expandoBridge.getAttribute("googleRefreshToken", false));

    googleCredential.setRefreshToken(googleRefreshToken);

    Drive.Builder driveBuilder = new Drive.Builder(httpTransport, jsonFactory, googleCredential);

    Drive drive = driveBuilder.build();

    Drive.About driveAbout = drive.about();

    Drive.About.Get driveAboutGet = driveAbout.get();

    About about = driveAboutGet.execute();

    return new GoogleDriveSession(drive, about.getRootFolderId());
  }
 @Override
 public User findUser(String userId) {
   try {
     com.liferay.portal.model.User user = UserLocalServiceUtil.getUser(Long.parseLong(userId));
     if (user != null) {
       return new LiferayUserImpl(user);
     } else {
       return null;
     }
   } catch (PortalException e) {
     throw new RuntimeException(e);
   } catch (SystemException e) {
     throw new RuntimeException(e);
   }
 }
  protected HttpServletRequest setCredentials(
      HttpServletRequest request, HttpSession session, long userId, String authType)
      throws Exception {

    User user = UserLocalServiceUtil.getUser(userId);

    String userIdString = String.valueOf(userId);

    request = new ProtectedServletRequest(request, userIdString, authType);

    session.setAttribute(WebKeys.USER, user);
    session.setAttribute(_AUTHENTICATED_USER, userIdString);

    initThreadLocals(request);

    return request;
  }
  @Override
  public void initContextUser(long userId) throws AuthException {
    try {
      User user = UserLocalServiceUtil.getUser(userId);

      CompanyThreadLocal.setCompanyId(user.getCompanyId());

      PrincipalThreadLocal.setName(userId);

      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      AccessControlThreadLocal.setRemoteAccess(false);
    } catch (Exception e) {
      throw new AuthException(e.getMessage(), e);
    }
  }
  protected OAuthConsumer getOAuthConsumer(SecurityToken securityToken, String serviceName)
      throws GadgetException {

    long userId = GetterUtil.getLong(securityToken.getViewerId());

    User user = null;

    try {
      user = UserLocalServiceUtil.getUser(userId);
    } catch (Exception e) {
      throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e);
    }

    Gadget gadget = null;

    try {
      gadget = GadgetLocalServiceUtil.getGadget(user.getCompanyId(), securityToken.getAppUrl());
    } catch (Exception e) {
      throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e);
    }

    OAuthConsumer oAuthConsumer = null;

    try {
      oAuthConsumer =
          OAuthConsumerLocalServiceUtil.getOAuthConsumer(gadget.getGadgetId(), serviceName);
    } catch (Exception e) {
      return _oAuthConsumer;
    }

    if (oAuthConsumer.getKeyType().equals(OAuthConsumerConstants.KEY_TYPE_RSA_PRIVATE)) {

      if (_oAuthConsumer == null) {
        throw new GadgetException(
            GadgetException.Code.INTERNAL_SERVER_ERROR, "No OAuth key specified");
      }

      oAuthConsumer.setConsumerSecret(_oAuthConsumer.getConsumerSecret());
    }

    return oAuthConsumer;
  }
  public void setTokenInfo(
      SecurityToken securityToken,
      ConsumerInfo consumerInfo,
      String serviceName,
      String tokenName,
      TokenInfo tokenInfo)
      throws GadgetException {

    long userId = GetterUtil.getLong(securityToken.getViewerId());

    User user = null;

    try {
      user = UserLocalServiceUtil.getUser(userId);
    } catch (Exception e) {
      throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e);
    }

    Gadget gadget = null;

    try {
      gadget = GadgetLocalServiceUtil.getGadget(user.getCompanyId(), securityToken.getAppUrl());
    } catch (Exception e) {
      throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e);
    }

    try {
      OAuthTokenLocalServiceUtil.addOAuthToken(
          userId,
          gadget.getGadgetId(),
          serviceName,
          securityToken.getModuleId(),
          tokenInfo.getAccessToken(),
          tokenName,
          tokenInfo.getTokenSecret(),
          tokenInfo.getSessionHandle(),
          tokenInfo.getTokenExpireMillis());
    } catch (Exception e) {
      throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e);
    }
  }
  @Test
  public void testAssignUserToRequiredGroups() throws Exception {
    long[] userIds = addUsers();
    long[] requiredGroupIds = addRequiredGroups();

    int initialGroupUsersCount = UserLocalServiceUtil.getGroupUsersCount(requiredGroupIds[0]);

    User user = UserLocalServiceUtil.getUser(userIds[0]);

    MembershipPolicyTestUtil.updateUser(
        user,
        null,
        null,
        new long[] {requiredGroupIds[0]},
        null,
        Collections.<UserGroupRole>emptyList());

    Assert.assertEquals(
        initialGroupUsersCount + 1, UserLocalServiceUtil.getGroupUsersCount(requiredGroupIds[0]));
    Assert.assertTrue(isPropagateMembership());
  }
  public void addUserThread(
      long userId, long mbThreadId, long topMBMessageId, boolean read, boolean deleted)
      throws PortalException {

    long userThreadId = counterLocalService.increment();

    User user = UserLocalServiceUtil.getUser(userId);

    UserThread userThread = userThreadPersistence.create(userThreadId);

    userThread.setCompanyId(user.getCompanyId());
    userThread.setUserId(userId);
    userThread.setUserName(user.getFullName());
    userThread.setCreateDate(new Date());
    userThread.setModifiedDate(new Date());
    userThread.setMbThreadId(mbThreadId);
    userThread.setTopMBMessageId(topMBMessageId);
    userThread.setRead(read);
    userThread.setDeleted(deleted);

    userThreadPersistence.update(userThread);
  }
  protected HttpServletRequest setCredentials(
      HttpServletRequest request, HttpSession session, long userId) throws Exception {

    User user = UserLocalServiceUtil.getUser(userId);

    String userIdString = String.valueOf(userId);

    request = new ProtectedServletRequest(request, userIdString);

    session.setAttribute(WebKeys.USER, user);
    session.setAttribute(_AUTHENTICATED_USER, userIdString);

    if (_usePermissionChecker) {
      PrincipalThreadLocal.setName(userId);
      PrincipalThreadLocal.setPassword(PortalUtil.getUserPassword(request));

      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user, false);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);
    }

    return request;
  }
  protected void sendEmail(long mbMessageId, ThemeDisplay themeDisplay) throws Exception {

    MBMessage mbMessage = MBMessageLocalServiceUtil.getMBMessage(mbMessageId);

    User sender = UserLocalServiceUtil.getUser(mbMessage.getUserId());

    Company company = CompanyLocalServiceUtil.getCompany(sender.getCompanyId());

    InternetAddress from = new InternetAddress(company.getEmailAddress());

    String subject =
        StringUtil.read(
            PrivateMessagingPortlet.class.getResourceAsStream(
                "dependencies/notification_message_subject.tmpl"));

    subject =
        StringUtil.replace(
            subject,
            new String[] {"[$COMPANY_NAME$]", "[$FROM_NAME$]"},
            new String[] {company.getName(), sender.getFullName()});

    String body =
        StringUtil.read(
            PrivateMessagingPortlet.class.getResourceAsStream(
                "dependencies/notification_message_body.tmpl"));

    long portraitId = sender.getPortraitId();
    String tokenId = WebServerServletTokenUtil.getToken(sender.getPortraitId());
    String portraitURL =
        themeDisplay.getPortalURL()
            + themeDisplay.getPathImage()
            + "/user_"
            + (sender.isFemale() ? "female" : "male")
            + "_portrait?img_id="
            + portraitId
            + "&t="
            + tokenId;

    body =
        StringUtil.replace(
            body,
            new String[] {
              "[$BODY$]", "[$COMPANY_NAME$]", "[$FROM_AVATAR$]",
              "[$FROM_NAME$]", "[$FROM_PROFILE_URL$]", "[$SUBJECT$]"
            },
            new String[] {
              mbMessage.getBody(),
              company.getName(),
              portraitURL,
              sender.getFullName(),
              sender.getDisplayURL(themeDisplay),
              mbMessage.getSubject()
            });

    List<UserThread> userThreads =
        UserThreadLocalServiceUtil.getMBThreadUserThreads(mbMessage.getThreadId());

    for (UserThread userThread : userThreads) {
      if ((userThread.getUserId() == mbMessage.getUserId())
          && UserNotificationManagerUtil.isDeliver(
              userThread.getUserId(),
              PortletKeys.PRIVATE_MESSAGING,
              PrivateMessagingConstants.NEW_MESSAGE,
              0,
              UserNotificationDeliveryConstants.TYPE_EMAIL)) {

        continue;
      }

      User recipient = UserLocalServiceUtil.getUser(userThread.getUserId());

      String threadURL = getThreadURL(recipient, mbMessage.getThreadId(), themeDisplay);

      if (Validator.isNull(threadURL)) {
        continue;
      }

      InternetAddress to = new InternetAddress(recipient.getEmailAddress());

      Format dateFormatDateTime =
          FastDateFormatFactoryUtil.getDateTime(
              FastDateFormatConstants.LONG,
              FastDateFormatConstants.SHORT,
              recipient.getLocale(),
              recipient.getTimeZone());

      String userThreadBody =
          StringUtil.replace(
              body,
              new String[] {"[$SENT_DATE$]", "[$THREAD_URL$]"},
              new String[] {dateFormatDateTime.format(mbMessage.getCreateDate()), threadURL});

      MailMessage mailMessage = new MailMessage(from, to, subject, userThreadBody, true);

      MailServiceUtil.sendEmail(mailMessage);
    }
  }
  public List<BaseModel<?>> findByC_U_FN_EA(
      long companyId,
      long userId,
      String[] fullNames,
      String[] emailAddresses,
      boolean andOperator,
      int start,
      int end)
      throws SystemException {

    fullNames = CustomSQLUtil.keywords(fullNames, true);
    emailAddresses = CustomSQLUtil.keywords(emailAddresses, true);

    Session session = null;

    try {
      session = openSession();

      String sql = CustomSQLUtil.get(FIND_BY_C_U_FN_EA);

      sql =
          CustomSQLUtil.replaceKeywords(
              sql, "lower(User_.firstName)", StringPool.LIKE, false, fullNames);
      sql =
          CustomSQLUtil.replaceKeywords(
              sql, "lower(User_.middleName)", StringPool.LIKE, false, fullNames);
      sql =
          CustomSQLUtil.replaceKeywords(
              sql, "lower(User_.lastName)", StringPool.LIKE, false, fullNames);
      sql =
          CustomSQLUtil.replaceKeywords(
              sql, "lower(User_.screenName)", StringPool.LIKE, false, fullNames);
      sql =
          CustomSQLUtil.replaceKeywords(
              sql, "lower(User_.emailAddress)", StringPool.LIKE, true, emailAddresses);
      sql =
          CustomSQLUtil.replaceKeywords(
              sql, "lower(Contacts_Entry.fullName)", StringPool.LIKE, false, fullNames);
      sql =
          CustomSQLUtil.replaceKeywords(
              sql, "lower(Contacts_Entry.emailAddress)", StringPool.LIKE, true, emailAddresses);
      sql = CustomSQLUtil.replaceAndOperator(sql, andOperator);

      SQLQuery q = session.createSynchronizedSQLQuery(sql);

      q.addScalar("id", Type.LONG);
      q.addScalar("name", Type.STRING);
      q.addScalar("portalUser", Type.INTEGER);

      QueryPos qPos = QueryPos.getInstance(q);

      qPos.add(companyId);
      qPos.add(fullNames, 8);
      qPos.add(emailAddresses, 2);
      qPos.add(userId);
      qPos.add(fullNames, 2);
      qPos.add(emailAddresses, 2);

      List<BaseModel<?>> models = new ArrayList<BaseModel<?>>();

      Iterator<Object[]> itr = (Iterator<Object[]>) QueryUtil.iterate(q, getDialect(), start, end);

      while (itr.hasNext()) {
        Object[] array = itr.next();

        long id = (Long) array[0];
        // String name = (String)array[1];
        int portalUser = (Integer) array[2];

        BaseModel<?> model = null;

        if (portalUser == 1) {
          model = UserLocalServiceUtil.getUser(id);
        } else {
          model = EntryLocalServiceUtil.getEntry(id);
        }

        models.add(model);
      }

      return models;
    } catch (Exception e) {
      throw new SystemException(e);
    } finally {
      closeSession(session);
    }
  }
  protected MBMessage addPrivateMessage(
      long userId,
      long mbThreadId,
      long parentMBMessageId,
      List<User> recipients,
      String subject,
      String body,
      List<ObjectValuePair<String, InputStream>> inputStreamOVPs,
      ThemeDisplay themeDisplay)
      throws PortalException {

    User user = UserLocalServiceUtil.getUser(userId);
    Group group = GroupLocalServiceUtil.getCompanyGroup(user.getCompanyId());
    long categoryId = PrivateMessagingConstants.PRIVATE_MESSAGING_CATEGORY_ID;

    if (Validator.isNull(subject)) {
      subject = StringUtil.shorten(body, 50);
    }

    boolean anonymous = false;
    double priority = 0.0;
    boolean allowPingbacks = false;

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);

    MBMessage mbMessage =
        MBMessageLocalServiceUtil.addMessage(
            userId,
            user.getScreenName(),
            group.getGroupId(),
            categoryId,
            mbThreadId,
            parentMBMessageId,
            subject,
            body,
            MBMessageConstants.DEFAULT_FORMAT,
            inputStreamOVPs,
            anonymous,
            priority,
            allowPingbacks,
            serviceContext);

    if (mbThreadId == 0) {
      for (User recipient : recipients) {
        if (recipient.getUserId() != userId) {
          addUserThread(
              recipient.getUserId(),
              mbMessage.getThreadId(),
              mbMessage.getMessageId(),
              false,
              false);
        }
      }

      addUserThread(userId, mbMessage.getThreadId(), mbMessage.getMessageId(), true, false);
    } else {
      List<UserThread> userThreads =
          userThreadPersistence.findByMBThreadId(mbMessage.getThreadId());

      for (UserThread userThread : userThreads) {
        userThread.setModifiedDate(new Date());

        if (userThread.getUserId() == userId) {
          userThread.setRead(true);
        } else {
          userThread.setRead(false);
        }

        if (userThread.isDeleted()) {
          userThread.setTopMBMessageId(mbMessage.getMessageId());
          userThread.setDeleted(false);
        }

        userThreadPersistence.update(userThread);
      }
    }

    // Email

    try {
      sendEmail(mbMessage.getMessageId(), themeDisplay);
    } catch (Exception e) {
      throw new SystemException(e);
    }

    // Notifications

    sendNotificationEvent(mbMessage);

    return mbMessage;
  }
  private long _initCompany(ServletContext servletContext, String webId) {

    // Begin initializing company

    if (_log.isDebugEnabled()) {
      _log.debug("Begin initializing company with web id " + webId);
    }

    long companyId = 0;

    try {
      Company company = CompanyLocalServiceUtil.checkCompany(webId);

      companyId = company.getCompanyId();
    } catch (Exception e) {
      _log.error(e, e);
    }

    Long currentThreadCompanyId = CompanyThreadLocal.getCompanyId();

    String currentThreadPrincipalName = PrincipalThreadLocal.getName();

    try {
      CompanyThreadLocal.setCompanyId(companyId);

      String principalName = null;

      try {
        User user = UserLocalServiceUtil.getUser(PrincipalThreadLocal.getUserId());

        if (user.getCompanyId() == companyId) {
          principalName = currentThreadPrincipalName;
        }
      } catch (Exception e) {
      }

      PrincipalThreadLocal.setName(principalName);

      // Initialize display

      if (_log.isDebugEnabled()) {
        _log.debug("Initialize display");
      }

      try {
        String xml =
            HttpUtil.URLtoString(servletContext.getResource("/WEB-INF/liferay-display.xml"));

        PortletCategory portletCategory =
            (PortletCategory) WebAppPool.get(companyId, WebKeys.PORTLET_CATEGORY);

        if (portletCategory == null) {
          portletCategory = new PortletCategory();
        }

        PortletCategory newPortletCategory = PortletLocalServiceUtil.getEARDisplay(xml);

        portletCategory.merge(newPortletCategory);

        for (int i = 0; i < _companyIds.length; i++) {
          long currentCompanyId = _companyIds[i];

          PortletCategory currentPortletCategory =
              (PortletCategory) WebAppPool.get(currentCompanyId, WebKeys.PORTLET_CATEGORY);

          if (currentPortletCategory != null) {
            portletCategory.merge(currentPortletCategory);
          }
        }

        WebAppPool.put(companyId, WebKeys.PORTLET_CATEGORY, portletCategory);
      } catch (Exception e) {
        _log.error(e, e);
      }

      // LDAP import

      try {
        if (LDAPSettingsUtil.isImportOnStartup(companyId)) {
          UserImporterUtil.importUsers(companyId);
        }
      } catch (Exception e) {
        _log.error(e, e);
      }

      // Process application startup events

      if (_log.isDebugEnabled()) {
        _log.debug("Process application startup events");
      }

      try {
        EventsProcessorUtil.process(
            PropsKeys.APPLICATION_STARTUP_EVENTS,
            PropsValues.APPLICATION_STARTUP_EVENTS,
            new String[] {String.valueOf(companyId)});
      } catch (Exception e) {
        _log.error(e, e);
      }

      // End initializing company

      if (_log.isDebugEnabled()) {
        _log.debug(
            "End initializing company with web id " + webId + " and company id " + companyId);
      }

      addCompanyId(companyId);
    } finally {
      CompanyThreadLocal.setCompanyId(currentThreadCompanyId);

      PrincipalThreadLocal.setName(currentThreadPrincipalName);
    }

    return companyId;
  }
Exemple #24
0
  private String formatJournalArticleURL() {

    /* This checks if the object is viewable by the current user and, if so, works out
     * the original url for the search results. The "visible" flag variable is set for each one.
     */

    Long lGroupId;
    Long lArticleId;
    Long lUserId;
    String strJournalURL = Global.strNoURLReturned;

    JournalContentSearchLocalServiceUtil jcslu = new JournalContentSearchLocalServiceUtil();
    LayoutLocalServiceUtil llsu = new LayoutLocalServiceUtil();
    List<Long> listLayouts = new ArrayList<Long>();
    Layout layLayout;
    User user;
    int iCount = 0;
    this.isVisible = false;

    try {
      this.context = FacesContext.getCurrentInstance();
      this.portletRequest = (PortletRequest) context.getExternalContext().getRequest();
      this.themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);
    } catch (Exception e) {
      System.out.println(e);
    }

    try {
      lGroupId = Long.decode(this.getGroupId());
    } catch (NumberFormatException n) {
      lGroupId = 0l; // zero long, not letter O
    }

    try {
      lArticleId = Long.decode(this.getArticleId());
    } catch (NumberFormatException n) {
      lArticleId = 0l; // zero long, not letter O
    }

    try {
      lUserId = Long.decode(this.getUserId());
    } catch (NumberFormatException n) {
      lUserId = 0l; // zero long, not letter O
    }

    if ((lGroupId != 0) && (lArticleId != 0)) {
      try {
        try {
          permissionChecker = themeDisplay.getPermissionChecker();
          this.setIsVisible(
              permissionChecker.hasPermission(
                  lGroupId, this.entryClassName, this.rootEntryClassPK, ActionKeys.VIEW));
          if (this.isIsVisible()) {
            if (getEntryClassName().equalsIgnoreCase(JournalArticle.class.getName())) {
              iCount = jcslu.getLayoutIdsCount(lGroupId, false, articleId);
              listLayouts = jcslu.getLayoutIds(lGroupId, false, articleId);
              if (iCount > 0) {
                layLayout = llsu.getLayout(lGroupId, false, listLayouts.get(0));
                layoutFriendlyURL = PortalUtil.getLayoutFriendlyURL(layLayout, themeDisplay);
                layoutFullURL =
                    PortalUtil.getLayoutActualURL(layLayout, themeDisplay.getPathMain());
                strHost = portletRequest.getServerName();
                iServerPort = portletRequest.getServerPort();
                strScheme = portletRequest.getScheme();

                if (layoutFullURL.startsWith("http://")) {
                  strJournalURL = layoutFullURL;
                } else {
                  if (strHost.equalsIgnoreCase("localhost")) {
                    strJournalURL =
                        strScheme + "://" + strHost + ":" + iServerPort + layoutFriendlyURL;
                  } else {
                    strJournalURL = layoutFriendlyURL;
                  }
                }
              }
            } else if (getEntryClassName().equalsIgnoreCase(BlogsEntry.class.getName())) {
              BlogsEntry entry = BlogsEntryLocalServiceUtil.getEntry(lArticleId);

              Group trgtGroup = GroupLocalServiceUtil.getGroup(lGroupId);
              String strFrUrl = trgtGroup.getFriendlyURL();
              String strUrlPath;
              user = UserLocalServiceUtil.getUser(lUserId);

              if (strFrUrl.equalsIgnoreCase("/fishnet")) {
                strUrlPath = "/home/-/blogs/";
              } else if (strFrUrl.equalsIgnoreCase("/fishlink")) {
                strUrlPath = "/home/-/blogs/";
              } else if (strFrUrl.equalsIgnoreCase("/freshwater-biological-association")) {
                strUrlPath = "/home/-/blogs/";
              } else {
                strUrlPath = "/blog/-/blogs/";
              }
              layoutFriendlyURL = "/web" + strFrUrl + strUrlPath + entry.getUrlTitle();

              strHost = portletRequest.getServerName();
              iServerPort = portletRequest.getServerPort();
              strScheme = portletRequest.getScheme();

              strJournalURL = strScheme + "://" + strHost + ":" + iServerPort + layoutFriendlyURL;
            } else if (getEntryClassName().equalsIgnoreCase(WikiPage.class.getName())) {
              WikiPageResource pageResource =
                  WikiPageResourceLocalServiceUtil.getPageResource(lArticleId);

              WikiPage wikiPage =
                  WikiPageLocalServiceUtil.getPage(
                      pageResource.getNodeId(), pageResource.getTitle());
              WikiNode wikiNode = WikiNodeLocalServiceUtil.getNode(pageResource.getNodeId());
              String strWikiNodeName = wikiNode.getName();
              String strWikiTitle = wikiPage.getTitle();
              Long lPageGroupId = wikiPage.getGroupId();
              Group trgtGroup = GroupLocalServiceUtil.getGroup(lPageGroupId);
              String strFrUrl = trgtGroup.getFriendlyURL();

              strHost = portletRequest.getServerName();
              iServerPort = portletRequest.getServerPort();
              strScheme = portletRequest.getScheme();
              // Extremely nasty hack!
              if (strFrUrl.equalsIgnoreCase("/tera")) {
                String strReplacedTitle = strWikiTitle.replaceAll("\\s", "\\+");
                layoutFriendlyURL =
                    "/web"
                        + strFrUrl
                        + "/home?p_p_id=54_INSTANCE_rU18&p_p_lifecycle=0&p_p_state=normal&p_p_mode=view&p_p_col_id=column-1&p_p_col_count=1&_54_INSTANCE_rU18_struts_action=%2Fwiki_display%2Fview&_54_INSTANCE_rU18_nodeName="
                        + strWikiNodeName
                        + "&_54_INSTANCE_rU18_title="
                        + strReplacedTitle;
              } else if (strFrUrl.equalsIgnoreCase("/fwl")) {
                layoutFriendlyURL =
                    "/web" + strFrUrl + "/wiki/-/wiki/" + strWikiNodeName + "/" + strWikiTitle;
              } else if (strFrUrl.equalsIgnoreCase("/fishlink")) {
                layoutFriendlyURL =
                    "/web"
                        + strFrUrl
                        + strFrUrl
                        + "-wiki/-/wiki/"
                        + strWikiNodeName
                        + "/"
                        + strWikiTitle;
              } else {
                layoutFriendlyURL =
                    "/freshwater-wiki/-/wiki/" + strWikiNodeName + "/" + strWikiTitle;
              }
              // </hack>
              strJournalURL = strScheme + "://" + strHost + ":" + iServerPort + layoutFriendlyURL;

            } else if (getEntryClassName().equalsIgnoreCase(DLFileEntry.class.getName())) {
              DLFileEntry fileEntry = DLFileEntryLocalServiceUtil.getFileEntry(lArticleId);
              lGroupId = fileEntry.getGroupId();

              AssetEntry assetEntry =
                  AssetEntryLocalServiceUtil.getEntry(getEntryClassName(), lArticleId);
              Long lEntryId = assetEntry.getEntryId();

              strHost = portletRequest.getServerName();
              iServerPort = portletRequest.getServerPort();
              strScheme = portletRequest.getScheme();
              // Another hack
              layoutFriendlyURL = "/fwl/documents/-/asset_publisher/8Ztl/document/id/" + lEntryId;
              strJournalURL =
                  strScheme + "://" + strHost + ":" + iServerPort + "/web" + layoutFriendlyURL;
              if (fileEntry.getTitle().isEmpty()) {
                this.setTitle("From Document Library");
              } else {
                this.setTitle(fileEntry.getTitle());
              }
              //

            } else if (getEntryClassName().equalsIgnoreCase(IGImage.class.getName())) {
              IGImage image = IGImageLocalServiceUtil.getImage(lArticleId);

              strHost = portletRequest.getServerName();
              iServerPort = portletRequest.getServerPort();
              strScheme = portletRequest.getScheme();

              layoutFriendlyURL = "igimage.fba.org.uk";
              // if (layoutFullURL.startsWith("http://")) {
              // strJournalURL = layoutFullURL;
              // } else {
              strJournalURL = strScheme + "://" + strHost + ":" + iServerPort + layoutFriendlyURL;
              // }
              // PortletURL viewImageURL = new PortletURLImpl(request, PortletKeys.IMAGE_GALLERY,
              // plid, PortletRequest.RENDER_PHASE);

              // viewImageURL.setWindowState(WindowState.MAXIMIZED);

              // viewImageURL.setParameter("struts_action", "/image_gallery/view");
              // viewImageURL.setParameter("folderId", String.valueOf(image.getFolderId()));

            } else if (getEntryClassName().equalsIgnoreCase(MBMessage.class.getName())) {
              MBMessage message = MBMessageLocalServiceUtil.getMessage(lArticleId);
              String aHref =
                  "<a href="
                      + themeDisplay.getPathMain()
                      + "/message_boards/find_message?messageId="
                      + message.getMessageId()
                      + ">";
              strHost = portletRequest.getServerName();
              iServerPort = portletRequest.getServerPort();
              strScheme = portletRequest.getScheme();

              layoutFriendlyURL = "mbmessage.fba.org.uk";
              // if (layoutFullURL.startsWith("http://")) {
              // strJournalURL = layoutFullURL;
              // } else {
              strJournalURL = strScheme + "://" + strHost + ":" + iServerPort + layoutFriendlyURL;
              // }

            } else if (getEntryClassName().equalsIgnoreCase(BookmarksEntry.class.getName())) {
              BookmarksEntry entry = BookmarksEntryLocalServiceUtil.getEntry(lArticleId);

              String entryURL =
                  themeDisplay.getPathMain()
                      + "/bookmarks/open_entry?entryId="
                      + entry.getEntryId();

              strHost = portletRequest.getServerName();
              iServerPort = portletRequest.getServerPort();
              strScheme = portletRequest.getScheme();

              layoutFriendlyURL = "bookmarks.fba.org.uk";
              // if (layoutFullURL.startsWith("http://")) {
              // strJournalURL = layoutFullURL;
              // } else {
              strJournalURL = strScheme + "://" + strHost + ":" + iServerPort + layoutFriendlyURL;
              // }

            }
          }
        } catch (PortalException ex) {
          Logger.getLogger(Liferay.class.getName()).log(Level.SEVERE, null, ex);
        }
      } catch (SystemException ex) {
        Logger.getLogger(Liferay.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    return strJournalURL;
  }
Exemple #25
0
  @Test
  public void testProcessLoginEvents() throws Exception {
    final IntegerWrapper counter = new IntegerWrapper();

    JAASHelper jaasHelper = JAASHelper.getInstance();

    JAASHelper.setInstance(
        new JAASHelper() {

          @Override
          protected long doGetJaasUserId(long companyId, String name)
              throws PortalException, SystemException {

            try {
              return super.doGetJaasUserId(companyId, name);
            } finally {
              counter.increment();
            }
          }
        });

    if (mainServlet == null) {
      MockServletContext mockServletContext =
          new AutoDeployMockServletContext(getResourceBasePath(), new FileSystemResourceLoader());

      MockServletConfig mockServletConfig = new MockServletConfig(mockServletContext);

      MainServlet mainServlet = new MainServlet();

      try {
        mainServlet.init(mockServletConfig);
      } catch (ServletException se) {
        throw new RuntimeException("The main servlet could not be initialized");
      }
    }

    Date lastLoginDate = _user.getLastLoginDate();

    MockHttpServletRequest mockHttpServletRequest =
        new MockHttpServletRequest(
            mainServlet.getServletContext(), HttpMethods.GET, StringPool.SLASH);

    mockHttpServletRequest.setRemoteUser(String.valueOf(_user.getUserId()));

    JAASAction preJAASAction = new JAASAction();
    JAASAction postJAASAction = new JAASAction();

    try {
      EventsProcessorUtil.registerEvent(PropsKeys.LOGIN_EVENTS_PRE, preJAASAction);
      EventsProcessorUtil.registerEvent(PropsKeys.LOGIN_EVENTS_POST, postJAASAction);

      mainServlet.service(mockHttpServletRequest, new MockHttpServletResponse());

      Assert.assertEquals(2, counter.getValue());
      Assert.assertTrue(preJAASAction.isRan());
      Assert.assertTrue(postJAASAction.isRan());

      _user = UserLocalServiceUtil.getUser(_user.getUserId());

      Assert.assertFalse(lastLoginDate.after(_user.getLastLoginDate()));
    } finally {
      EventsProcessorUtil.unregisterEvent(PropsKeys.LOGIN_EVENTS_PRE, postJAASAction);
      EventsProcessorUtil.unregisterEvent(PropsKeys.LOGIN_EVENTS_POST, postJAASAction);

      JAASHelper.setInstance(jaasHelper);
    }
  }
  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);
  }
  public static List<Group> getGroups(long userId) throws Exception {
    User user = UserLocalServiceUtil.getUser(userId);

    return getGroups(user);
  }
Exemple #28
0
  protected void importEvent(
      PortletDataContext portletDataContext, Element eventElement, CalEvent event)
      throws Exception {

    long userId = portletDataContext.getUserId(event.getUserUuid());

    Date startDate = event.getStartDate();

    int startDateMonth = 0;
    int startDateDay = 0;
    int startDateYear = 0;
    int startDateHour = 0;
    int startDateMinute = 0;

    if (startDate != null) {
      Locale locale = null;
      TimeZone timeZone = null;

      if (event.getTimeZoneSensitive()) {
        User user = UserLocalServiceUtil.getUser(userId);

        locale = user.getLocale();
        timeZone = user.getTimeZone();
      } else {
        locale = LocaleUtil.getDefault();
        timeZone = TimeZoneUtil.getTimeZone(StringPool.UTC);
      }

      Calendar startCal = CalendarFactoryUtil.getCalendar(timeZone, locale);

      startCal.setTime(startDate);

      startDateMonth = startCal.get(Calendar.MONTH);
      startDateDay = startCal.get(Calendar.DATE);
      startDateYear = startCal.get(Calendar.YEAR);
      startDateHour = startCal.get(Calendar.HOUR);
      startDateMinute = startCal.get(Calendar.MINUTE);

      if (startCal.get(Calendar.AM_PM) == Calendar.PM) {
        startDateHour += 12;
      }
    }

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(eventElement, event, NAMESPACE);

    CalEvent importedEvent = null;

    if (portletDataContext.isDataStrategyMirror()) {
      CalEvent existingEvent =
          CalEventUtil.fetchByUUID_G(event.getUuid(), portletDataContext.getScopeGroupId());

      if (existingEvent == null) {
        serviceContext.setUuid(event.getUuid());

        importedEvent =
            CalEventLocalServiceUtil.addEvent(
                userId,
                event.getTitle(),
                event.getDescription(),
                event.getLocation(),
                startDateMonth,
                startDateDay,
                startDateYear,
                startDateHour,
                startDateMinute,
                event.getDurationHour(),
                event.getDurationMinute(),
                event.isAllDay(),
                event.isTimeZoneSensitive(),
                event.getType(),
                event.getRepeating(),
                event.getRecurrenceObj(),
                event.getRemindBy(),
                event.getFirstReminder(),
                event.getSecondReminder(),
                serviceContext);
      } else {
        importedEvent =
            CalEventLocalServiceUtil.updateEvent(
                userId,
                existingEvent.getEventId(),
                event.getTitle(),
                event.getDescription(),
                event.getLocation(),
                startDateMonth,
                startDateDay,
                startDateYear,
                startDateHour,
                startDateMinute,
                event.getDurationHour(),
                event.getDurationMinute(),
                event.isAllDay(),
                event.isTimeZoneSensitive(),
                event.getType(),
                event.getRepeating(),
                event.getRecurrenceObj(),
                event.getRemindBy(),
                event.getFirstReminder(),
                event.getSecondReminder(),
                serviceContext);
      }
    } else {
      importedEvent =
          CalEventLocalServiceUtil.addEvent(
              userId,
              event.getTitle(),
              event.getDescription(),
              event.getLocation(),
              startDateMonth,
              startDateDay,
              startDateYear,
              startDateHour,
              startDateMinute,
              event.getDurationHour(),
              event.getDurationMinute(),
              event.isAllDay(),
              event.isTimeZoneSensitive(),
              event.getType(),
              event.getRepeating(),
              event.getRecurrenceObj(),
              event.getRemindBy(),
              event.getFirstReminder(),
              event.getSecondReminder(),
              serviceContext);
    }

    portletDataContext.importClassedModel(event, importedEvent, NAMESPACE);
  }
  public static JSONObject getJSONRecipients(
      long userId, String type, String keywords, int start, int end)
      throws PortalException, SystemException {

    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

    User user = UserLocalServiceUtil.getUser(userId);

    LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();

    if (type.equals("site")) {
      params.put("inherit", Boolean.TRUE);

      LinkedHashMap<String, Object> groupParams = new LinkedHashMap<String, Object>();

      groupParams.put("inherit", Boolean.FALSE);
      groupParams.put("site", Boolean.TRUE);
      groupParams.put("usersGroups", userId);

      List<Group> groups =
          GroupLocalServiceUtil.search(
              user.getCompanyId(), groupParams, QueryUtil.ALL_POS, QueryUtil.ALL_POS);

      params.put(
          "usersGroups",
          SitesUtil.filterGroups(groups, PortletPropsValues.AUTOCOMPLETE_RECIPIENT_SITE_EXCLUDES));
    } else if (!type.equals("all")) {
      params.put(
          "socialRelationType",
          new Long[] {userId, new Long(SocialRelationConstants.TYPE_BI_CONNECTION)});
    }

    try {
      Role role =
          RoleLocalServiceUtil.getRole(user.getCompanyId(), RoleConstants.SOCIAL_OFFICE_USER);

      if (role != null) {
        params.put("inherit", Boolean.TRUE);
        params.put("usersRoles", new Long(role.getRoleId()));
      }
    } catch (NoSuchRoleException nsre) {
    }

    int total =
        UserLocalServiceUtil.searchCount(
            user.getCompanyId(), keywords, WorkflowConstants.STATUS_APPROVED, params);

    jsonObject.put("total", total);

    List<User> users =
        UserLocalServiceUtil.search(
            user.getCompanyId(),
            keywords,
            WorkflowConstants.STATUS_APPROVED,
            params,
            start,
            end,
            new UserFirstNameComparator(true));

    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

    for (User curUser : users) {
      JSONObject userJSONObject = JSONFactoryUtil.createJSONObject();

      StringBundler sb = new StringBundler(5);

      sb.append(curUser.getFullName());
      sb.append(CharPool.SPACE);
      sb.append(CharPool.LESS_THAN);
      sb.append(curUser.getScreenName());
      sb.append(CharPool.GREATER_THAN);

      userJSONObject.put("name", sb.toString());

      jsonArray.put(userJSONObject);
    }

    jsonObject.put("users", jsonArray);

    return jsonObject;
  }
  @Override
  public String getDescriptiveName(Locale locale) throws PortalException {
    Group curGroup = this;

    String name = getName(locale);

    if (Validator.isNull(name)) {
      Locale siteDefaultLocale = PortalUtil.getSiteDefaultLocale(getGroupId());

      name = getName(siteDefaultLocale);
    }

    if (isCompany() && !isCompanyStagingGroup()) {
      name = LanguageUtil.get(locale, "global");
    } else if (isControlPanel()) {
      name = LanguageUtil.get(locale, "control-panel");
    } else if (isGuest()) {
      Company company = CompanyLocalServiceUtil.getCompany(getCompanyId());

      Account account = company.getAccount();

      name = account.getName();
    } else if (isLayout()) {
      Layout layout = LayoutLocalServiceUtil.getLayout(getClassPK());

      name = layout.getName(locale);
    } else if (isLayoutPrototype()) {
      LayoutPrototype layoutPrototype =
          LayoutPrototypeLocalServiceUtil.getLayoutPrototype(getClassPK());

      name = layoutPrototype.getName(locale);
    } else if (isLayoutSetPrototype()) {
      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(getClassPK());

      name = layoutSetPrototype.getName(locale);
    } else if (isOrganization()) {
      long organizationId = getOrganizationId();

      Organization organization = OrganizationLocalServiceUtil.getOrganization(organizationId);

      name = organization.getName();

      curGroup = organization.getGroup();
    } else if (isUser()) {
      long userId = getClassPK();

      User user = UserLocalServiceUtil.getUser(userId);

      name = user.getFullName();
    } else if (isUserGroup()) {
      long userGroupId = getClassPK();

      UserGroup userGroup = UserGroupLocalServiceUtil.getUserGroup(userGroupId);

      name = userGroup.getName();
    } else if (isUserPersonalSite()) {
      name = LanguageUtil.get(locale, "user-personal-site");
    }

    if (curGroup.isStaged() && !curGroup.isStagedRemotely() && curGroup.isStagingGroup()) {

      Group liveGroup = getLiveGroup();

      name = liveGroup.getDescriptiveName(locale);
    }

    return name;
  }