Exemplo n.º 1
0
  private List<org.apache.rave.model.Person> getGroupMembersFromRepository(
      CollectionOptions collectionOptions, String groupId, String appId) {

    String filter = collectionOptions == null ? null : collectionOptions.getFilter();
    List<org.apache.rave.model.Person> current;

    if (filter == null
        || filter.equals(PersonService.ALL_FILTER)
        || filter.equals(PersonService.TOP_FRIENDS_FILTER)) {
      current = repository.findByGroup(groupId);

    } else if (filter.equals(PersonService.HAS_APP_FILTER)) {
      current = repository.findByGroup(groupId, appId);

    } else if (filter.equals(PersonService.IS_WITH_FRIENDS_FILTER)) {
      current = repository.findByGroupWithFriend(groupId, collectionOptions.getFilterValue());

      // Represents the default case (filter by field)
    } else {
      current =
          repository.findByGroup(
              groupId,
              filter,
              collectionOptions.getFilterOperation(),
              collectionOptions.getFilterValue());
    }
    return current;
  }
  @Test
  public void getJohnDoeFriendsOrderedByName() throws Exception {
    // Set collection options
    CollectionOptions collectionOptions = new CollectionOptions();
    collectionOptions.setSortBy("name");
    collectionOptions.setSortOrder(SortOrder.ascending);
    collectionOptions.setMax(20);

    // Get all friends of john.doe
    Future<RestfulCollection<Person>> result =
        this.personServiceDb.getPeople(
            SpiTestUtil.buildUserIds("john.doe"),
            new GroupId(GroupId.Type.friends, "@friends"),
            collectionOptions,
            Person.Field.ALL_FIELDS,
            SpiTestUtil.DEFAULT_TEST_SECURITY_TOKEN);

    RestfulCollection<Person> peopleCollection = result.get();
    assertEquals(3, peopleCollection.getTotalResults());
    assertEquals(0, peopleCollection.getStartIndex());
    List<Person> people = peopleCollection.getEntry();
    // The users should be in alphabetical order
    SpiTestUtil.assertPersonEquals(people.get(0), "george.doe", "George Doe");
    SpiTestUtil.assertPersonEquals(people.get(1), "jane.doe", "Jane Doe");
  }
Exemplo n.º 3
0
  private List<org.apache.rave.model.Person> getConnectedPeopleFromRepository(
      CollectionOptions collectionOptions, String appId, String userId) {

    String filter = collectionOptions == null ? null : collectionOptions.getFilter();
    List<org.apache.rave.model.Person> current;
    // Currently ignoring TOP FRIENDS as it hasn't been defined what a top friend is

    if (filter == null
        || filter.equals(PersonService.ALL_FILTER)
        || filter.equals(PersonService.TOP_FRIENDS_FILTER)) {
      current = repository.findAllConnectedPeople(userId);

    } else if (filter.equals(PersonService.HAS_APP_FILTER)) {
      current = repository.findAllConnectedPeople(userId, appId);

    } else if (filter.equals(PersonService.IS_WITH_FRIENDS_FILTER)) {
      current =
          repository.findAllConnectedPeopleWithFriend(userId, collectionOptions.getFilterValue());

      // Represents the default case (filter by field)
    } else {
      current =
          repository.findAllConnectedPeople(
              userId,
              filter,
              collectionOptions.getFilterOperation(),
              collectionOptions.getFilterValue());
    }
    return current;
  }
Exemplo n.º 4
0
 private CollectionOptions manipulateCollectionOptions(
     CollectionOptions options, SecurityToken token) {
   if (options != null && options.getFilterValue() != null) {
     if (options.getFilterValue().equalsIgnoreCase(AbstractSecurityToken.Keys.OWNER.name()))
       options.setFilterValue(token.getOwnerId());
     else if (options.getFilterValue().equalsIgnoreCase(AbstractSecurityToken.Keys.VIEWER.name()))
       options.setFilterValue(token.getViewerId());
   }
   return options;
 }
  /**
   * Tests getPeople with a couple of UserIds
   *
   * @throws Exception
   */
  @Test
  public void testGetExpectedPeople() throws Exception {
    CollectionOptions options = new CollectionOptions();
    options.setSortBy(PersonService.ALL_FILTER);
    options.setSortOrder(SortOrder.ascending);
    options.setFilter(null);
    options.setFilterOperation(FilterOperation.contains);
    options.setFilterValue("");
    options.setFirst(0);
    options.setMax(5);

    Set<UserId> userIds = new java.util.HashSet<UserId>();
    userIds.add(JOHN_DOE);
    userIds.add(JANE_DOE);
    userIds.add(MAIJA_M);

    RestfulCollection<Person> peopleCollection =
        personService
            .getPeople(
                userIds, null, options, Collections.<String>emptySet(), new FakeGadgetToken())
            .get();
    List<Person> personList = peopleCollection.getEntry();
    assertEquals(true, containsPerson(personList, JOHN_DOE.getUserId()));
    assertEquals(true, containsPerson(personList, MAIJA_M.getUserId()));
    assertEquals(false, containsPerson(personList, GEORGE_DOE.getUserId()));
  }
  public RestfulCollection<Activity> doGetActivities(
      UserId userId,
      GroupId groupId,
      String appId,
      Set<String> fields,
      CollectionOptions collectionOptions,
      Set<String> activityIds,
      SecurityToken securityToken)
      throws Exception {

    ThemeDisplay themeDisplay = getThemeDisplay(securityToken);

    long userIdLong = GetterUtil.getLong(userId.getUserId(securityToken));

    List<Activity> activities = getActivities(themeDisplay, userIdLong);

    return new RestfulCollection<Activity>(
        activities, collectionOptions.getFirst(), activities.size(), collectionOptions.getMax());
  }
  public RestfulCollection<Activity> doGetActivities(
      Set<UserId> userIds,
      GroupId groupId,
      String appId,
      Set<String> fields,
      CollectionOptions collectionOptions,
      SecurityToken securityToken)
      throws Exception {

    ThemeDisplay themeDisplay = getThemeDisplay(securityToken);

    List<Activity> activities = new ArrayList<Activity>();

    for (UserId userId : userIds) {
      long userIdLong = GetterUtil.getLong(userId.getUserId(securityToken));

      List<Activity> personActivities = getActivities(themeDisplay, userIdLong);

      activities.addAll(personActivities);
    }

    return new RestfulCollection<Activity>(
        activities, collectionOptions.getFirst(), activities.size(), collectionOptions.getMax());
  }
  @Test
  public void testGetExpectedFriends() throws Exception {
    CollectionOptions options = new CollectionOptions();
    options.setSortBy(PersonService.TOP_FRIENDS_SORT);
    options.setSortOrder(SortOrder.ascending);
    options.setFilter(null);
    options.setFilterOperation(FilterOperation.contains);
    options.setFilterValue("");
    options.setFirst(0);
    options.setMax(20);

    RestfulCollection<Person> friendsCollection =
        personService
            .getPeople(
                Sets.newHashSet(JOHN_DOE),
                new GroupId(GroupId.Type.friends, null),
                options,
                Collections.<String>emptySet(),
                new FakeGadgetToken())
            .get();
    assertEquals(4, friendsCollection.getEntry().size());
  }
  public void testGetExpectedUsersForPlural() throws Exception {
    CollectionOptions options = new CollectionOptions();
    options.setSortBy(PersonService.TOP_FRIENDS_SORT);
    options.setSortOrder(SortOrder.ascending);
    options.setFilter(null);
    options.setFilterOperation(FilterOperation.contains);
    options.setFilterValue("");
    options.setFirst(0);
    options.setMax(20);

    RestfulCollection<Person> responseItem =
        db.getPeople(
                ImmutableSet.of(JOHN_DOE, JANE_DOE),
                new GroupId(GroupId.Type.friends, null),
                options,
                Collections.<String>emptySet(),
                token)
            .get();
    assertNotNull(responseItem);
    assertEquals(4, responseItem.getTotalResults());
    // Test a couple of users
    assertEquals("john.doe", responseItem.getEntry().get(0).getId());
    assertEquals("jane.doe", responseItem.getEntry().get(1).getId());
  }
Exemplo n.º 10
0
  /** Get the set of user id's from a user and group */
  @SuppressWarnings("unchecked")
  private Set<String> getIdSet(
      UserId userId, GroupId groupId, CollectionOptions options, SecurityToken token)
      throws HibernateException {

    String user = userId.getUserId(token);

    if (groupId == null) {
      return ImmutableSortedSet.of(user);
    }

    Set<String> idSet = new HashSet<String>();

    //		Session hs = HibernateUtil.getSessionFactory().getCurrentSession();
    //		Transaction tran = null;

    switch (groupId.getType()) {
      case all:
        // idSet.add(user);
        List<String> allUserIds = null;
        try {
          // List<String> allUserIds = sqlMap.queryForList(
          // "getAllUserIds" );
          Session hs = HibernateUtil.getSessionFactory().getCurrentSession();
          Transaction tran = hs.beginTransaction();

          // Criteria crit = hs.createCriteria(User.class);
          Query q = hs.createQuery("select id from User");
          allUserIds = (List<String>) q.list();

        } catch (HibernateException e) {

          HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
          e.printStackTrace();
        }

        for (String id : allUserIds) {
          idSet.add(id);
        }
        break;
      case groupId:
      case friends:
        try {
          /**
           * This filter can be any field of the object being filtered or the special js filters,
           * hasApp or topFriends. Other special Filters defined in the OpenSocial v.9 specification
           * are
           *
           * <dl>
           *   <dt>all
           *   <dd>Retrieves all friends
           *   <dt>hasApp
           *   <dd>Retrieves all friends with any data for this application.
           *   <dt>'topFriends
           *   <dd>Retrieves only the user's top friends.
           *   <dt>isFriendsWith
           *   <dd>Only "hasApp filter" is implemented here
           * </dl>
           */
          Session hs = HibernateUtil.getSessionFactory().getCurrentSession();
          Transaction tran = hs.beginTransaction();

          // List<String> friendsIds = sqlMap.queryForList("getFriendsIds",user);

          List<String> friendsIds = new ArrayList<String>();

          User userObject = (User) hs.get(User.class, user);

          Set<User> friends = userObject.getFriendsByMe();
          Set<User> friendsByOthers = userObject.getFriendsByOther();

          friends.addAll(friendsByOthers);

          if (options.getFilter() != null && options.getFilter().equals("hasApp")) {

            Set<User> tempFriends = new HashSet<User>();
            tempFriends.addAll(friends);

            for (User friend : tempFriends) {
              if (!friend.getPerson().getHasapp()) friends.remove(friend);
            }
          }

          for (User friend : friends) {
            friendsIds.add(friend.getId());
          }
          idSet.addAll(friendsIds);

        } catch (HibernateException e) {

          HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
          e.printStackTrace();
        }

        break;
      case self:
        idSet.add(user);
        break;
    }
    return idSet;
  }
Exemplo n.º 11
0
  /* (non-Javadoc)
   * @see org.apache.shindig.social.opensocial.spi.ActivityService#getActivities(java.util.Set, org.apache.shindig.social.opensocial.spi.GroupId, java.lang.String, java.util.Set, org.apache.shindig.social.opensocial.spi.CollectionOptions, org.apache.shindig.auth.SecurityToken)
   */
  public Future<RestfulCollection<Activity>> getActivities(
      Set<UserId> userIds,
      GroupId groupId,
      String appId,
      Set<String> fields,
      CollectionOptions options,
      SecurityToken token)
      throws ProtocolException {

    List<Activity> plist = null;
    int lastPos = 1;

    StringBuilder sb = new StringBuilder();
    // sanitize the list to get the uid's and remove duplicates
    List<String> paramList = SPIUtils.getUserList(userIds, token);
    // select the group Id as this will drive the query
    switch (groupId.getType()) {
      case all:
        // select all contacts activity
        sb.append(ActivityDb.JPQL_FINDACTIVITY);
        JPQLUtils.addInClause(sb, "a", "userId", lastPos, paramList.size());
        sb.append(" or a.userId in (select m.person.id from GroupDb g join g.members m where ");
        lastPos = JPQLUtils.addInClause(sb, "g.owner", "id", lastPos, paramList.size());
        sb.append(")");
        break;
      case friends:
        // select all friends (subset of contacts)
        sb.append(ActivityDb.JPQL_FINDACTIVITY_BY_FRIENDS);
        lastPos = JPQLUtils.addInClause(sb, "p", "id", lastPos, paramList.size());
        sb.append(")) ");
        // TODO Group by doesn't work in HSQLDB or Derby - causes a "Not in aggregate function or
        // group by clause" jdbc exception
        // sb.append(" group by p ");
        break;
      case groupId:
        sb.append(ActivityDb.JPQL_FINDACTIVITY_BY_GROUP);
        paramList.add(groupId.getGroupId());
        lastPos += 2;
        break;
      case deleted:
        // ???
        break;
      case self:
        // select self
        sb.append(ActivityDb.JPQL_FINDACTIVITY);
        lastPos = JPQLUtils.addInClause(sb, "a", "userId", lastPos, paramList.size());
        break;
      default:
        throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST, "Group ID not recognized");
    }

    JPQLUtils.addFilterClause(sb, ActivityDb.FILTER_CAPABILITY, options, paramList);

    EntityManager entityManager = getEntityManager();

    // Get total results, that is count the total number of rows for this query
    Long totalResults = JPQLUtils.getTotalResults(entityManager, sb.toString(), paramList);
    if (options == null) options = new CollectionOptions();

    // Execute paginated query
    if (totalResults > 0) {
      JPQLUtils.addOrderClause(sb, options, "a");
      plist = JPQLUtils.getListQuery(entityManager, sb.toString(), paramList, options);
    }
    entityManager.close();
    if (plist == null) {
      plist = new ArrayList<Activity>();
    }

    // all of the above could equally have been placed into a thread to overlay the
    // db wait times.
    RestfulCollection<Activity> restCollection =
        new RestfulCollection<Activity>(
            plist, options.getFirst(), totalResults.intValue(), options.getMax());
    return ImmediateFuture.newInstance(restCollection);
  }