/**
   * Adds a social relation between the two users to the database.
   *
   * @param userId1 the user that is the subject of the relation
   * @param userId2 the user at the other end of the relation
   * @param type the type of the relation
   * @return the social relation
   * @throws PortalException if the users could not be found, if the users were not from the same
   *     company, or if either of the users was the default user
   * @throws SystemException if a system exception occurred
   */
  public SocialRelation addRelation(long userId1, long userId2, int type)
      throws PortalException, SystemException {

    if (userId1 == userId2) {
      throw new RelationUserIdException();
    }

    User user1 = userPersistence.findByPrimaryKey(userId1);
    User user2 = userPersistence.findByPrimaryKey(userId2);

    if (user1.getCompanyId() != user2.getCompanyId()) {
      throw new RelationUserIdException();
    }

    SocialRelation relation = socialRelationPersistence.fetchByU1_U2_T(userId1, userId2, type);

    if (relation == null) {
      long relationId = counterLocalService.increment();

      relation = socialRelationPersistence.create(relationId);

      relation.setCompanyId(user1.getCompanyId());
      relation.setCreateDate(System.currentTimeMillis());
      relation.setUserId1(userId1);
      relation.setUserId2(userId2);
      relation.setType(type);

      socialRelationPersistence.update(relation);
    }

    if (SocialRelationConstants.isTypeBi(type)) {
      SocialRelation biRelation = socialRelationPersistence.fetchByU1_U2_T(userId2, userId1, type);

      if (biRelation == null) {
        long biRelationId = counterLocalService.increment();

        biRelation = socialRelationPersistence.create(biRelationId);

        biRelation.setCompanyId(user1.getCompanyId());
        biRelation.setCreateDate(System.currentTimeMillis());
        biRelation.setUserId1(userId2);
        biRelation.setUserId2(userId1);
        biRelation.setType(type);

        socialRelationPersistence.update(biRelation);
      }
    }

    return relation;
  }