示例#1
0
  @GET
  @Path("{userId}/friends")
  public Response getFriends(
      @PathParam("userId") String userId, @QueryParam(LOGGED_IN_USER_QPARAM) String currentUser) {
    List<User> friends = userDao.getFriends(userId, currentUser);
    List<com.campusconnect.neo4j.types.web.User> returnFriends = new ArrayList<>();
    for (User friend : friends) {
      returnFriends.add(Neo4jToWebMapper.mapUserNeo4jToWeb(friend));
    }
    FriendsPage friendsPage = new FriendsPage(0, returnFriends.size(), returnFriends);

    Friends allFriends = new Friends();
    allFriends.setFriends(friendsPage);

    if (currentUser != null && !currentUser.equals(userId)) {
      List<User> mutualFriends = userDao.getMutualFriends(currentUser, userId);
      List<com.campusconnect.neo4j.types.web.User> returnMutualFriends = new ArrayList<>();
      for (User friend : mutualFriends) {
        returnMutualFriends.add(Neo4jToWebMapper.mapUserNeo4jToWeb(friend));
      }
      FriendsPage mutualFriendsPage =
          new FriendsPage(0, returnMutualFriends.size(), returnMutualFriends);
      allFriends.setMutualFriends(mutualFriendsPage);
    }
    return Response.ok().entity(allFriends).build();
  }
示例#2
0
  @Test
  @ExpectedException(DataAccessException.class)
  public void testAddAndRemoveUser() throws Exception {
    User user = new User("testuser");
    user.setPassword("testpass");
    user.setFirstName("Test");
    user.setLastName("Last");
    Address address = new Address();
    address.setCity("Denver");
    address.setProvince("CO");
    address.setCountry("USA");
    address.setPostalCode("80210");
    user.setAddress(address);
    user.setEmail("*****@*****.**");
    user.setWebsite("http://raibledesigns.com");

    Role role = rdao.getRoleByName(Constants.USER_ROLE);
    assertNotNull(role.getId());
    user.addRole(role);

    user = dao.saveUser(user);
    flush();

    assertNotNull(user.getId());
    user = dao.get(user.getId());
    assertEquals("testpass", user.getPassword());

    dao.remove(user);
    flush();

    // should throw DataAccessException
    dao.get(user.getId());
  }
示例#3
0
  public void testUpdateUser() throws Exception {
    User user = dao.get(1L);

    Address address = user.getAddress();
    address.setAddress1("new address");
    user.setTimeZone("US/Central");

    dao.saveUser(user);

    user = dao.get(1L);
    assertEquals(address, user.getAddress());
    assertEquals("new address", user.getAddress().getAddress1());
    assertEquals("US/Central", user.getTimeZone());

    // verify that violation occurs when adding new user with same username
    user.setId(null);

    endTransaction();

    try {
      dao.saveUser(user);
      // flush();
      fail("saveUser didn't throw DataIntegrityViolationException");
    } catch (DataIntegrityViolationException e) {
      assertNotNull(e);
      log.debug("expected exception: " + e.getMessage());
    }
  }
  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView show(
      @ModelAttribute("form") EditRegisterRequest form,
      @PathVariable String nick,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    Template tmpl = Template.getTemplate(request);
    if (!tmpl.isSessionAuthorized()) {
      throw new AccessViolationException("Not authorized");
    }
    if (!tmpl.getNick().equals(nick)) {
      throw new AccessViolationException("Not authorized");
    }
    User user = tmpl.getCurrentUser();
    UserInfo userInfo = userDao.getUserInfoClass(user);

    ModelAndView mv = new ModelAndView("edit-reg");

    form.setEmail(user.getEmail());
    form.setUrl(userInfo.getUrl());
    form.setTown(userInfo.getTown());
    form.setName(user.getName());
    form.setInfo(StringEscapeUtils.unescapeHtml(userDao.getUserInfo(user)));

    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

    return mv;
  }
示例#5
0
 @Test
 public void testGetUserPassword() throws Exception {
   User user = dao.get(-1L);
   String password = dao.getUserPassword(user.getId());
   assertNotNull(password);
   log.debug("password: " + password);
 }
示例#6
0
  @Test
  @ExpectedException(DataIntegrityViolationException.class)
  public void testUpdateUser() throws Exception {
    User user = dao.get(-1L);

    Address address = user.getAddress();
    address.setAddress("new address");

    dao.saveUser(user);
    flush();

    user = dao.get(-1L);
    assertEquals(address, user.getAddress());
    assertEquals("new address", user.getAddress().getAddress());

    // verify that violation occurs when adding new user with same username
    User user2 = new User();
    user2.setAddress(user.getAddress());
    user2.setConfirmPassword(user.getConfirmPassword());
    user2.setEmail(user.getEmail());
    user2.setFirstName(user.getFirstName());
    user2.setLastName(user.getLastName());
    user2.setPassword(user.getPassword());
    user2.setPasswordHint(user.getPasswordHint());
    user2.setRoles(user.getRoles());
    user2.setUsername(user.getUsername());
    user2.setWebsite(user.getWebsite());

    // should throw DataIntegrityViolationException
    dao.saveUser(user2);
  }
示例#7
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // エンコーディング
    request.setCharacterEncoding("utf-8");

    String id = request.getParameter("id");
    String pass = request.getParameter("password");
    String url = request.getParameter("url");

    boolean isErr = false;
    // ハッシュ計算
    String hash = SHAGenerator.getStretchedPassword(id, pass);

    // ID(メールアドレス)かパスワードが空だった場合
    if (id == null || id.isEmpty() || pass == null || pass.isEmpty()) {
      request.setAttribute("authErr", "ユーザIDもしくはパスワードに誤りがあります");
      isErr = true;
    }
    // データベースにアクセス
    UserDao dao = new UserDao();
    User user = dao.auth(id, hash);
    // 存在チェック
    if (!isErr) {
      // 存在チェック
      if (user == null) {
        request.setAttribute("authErr", "認証エラーです");
      } else {
        // 認証情報を渡して遷移
        request.setAttribute("auth", user);
        request.getRequestDispatcher(url).forward(request, response);
      }
    } else {
      request.getRequestDispatcher("user_confilm.jsp").forward(request, response);
    }
  }
示例#8
0
 @POST
 @Path("{userId}/follow/{followUserId}")
 public Response follow(
     @PathParam("userId") final String userId,
     @PathParam("followUserId") final String followUserId) {
   userDao.createFollowingRelation(userDao.getUser(userId), userDao.getUser(followUserId));
   return Response.ok().build();
 }
示例#9
0
 @Test
 public void testAddScore() {
   userDao.addScore(10);
   List<User> list = userDao.queryAll(0, 100);
   for (User user : list) {
     System.out.println(user);
   }
 }
  @Test(expected = EmptyResultDataAccessException.class)
  public void TUnitGetUserFail() throws SQLException, ClassNotFoundException {

    dao.deleteAll();
    assertThat(dao.getCount(), is(0));

    dao.get("who");
  }
示例#11
0
 public void testGetExternalUser() throws Exception {
   User user = dao.get(1L);
   assertTrue("External field was not populated correctly.", !user.isExternal());
   assertTrue(!user.isHasProfile());
   user = dao.get(5L);
   assertTrue("External field was not populated.", user.isExternal());
   assertTrue(!user.isHasProfile());
 }
 /** Test of deleteUser method, of class UserDao. */
 @Ignore
 public void testDeleteUser() {
   System.out.println("deleteUser");
   String id = "";
   UserDao instance = new UserDaoImpl();
   instance.deleteUser(id);
   // TODO review the generated test code and remove the default call to fail.
   fail("The test case is a prototype.");
 }
示例#13
0
 @POST
 @Path("{userId}/friend/{friendUserId}")
 public Response addFriend(
     @PathParam("userId") final String userId,
     @PathParam("friendUserId") final String friendUserId) {
   userDao.createFriendRelationWithPending(userDao.getUser(userId), userDao.getUser(friendUserId));
   return Response.ok().build();
   //  return null;
 }
 @Test
 public void testDeleteUser() throws Exception {
   LOGGER.debug("test: DeleteUser");
   List<User> users = userDao.getAllUsers();
   Integer usersSize = users.size();
   assertTrue(users.size() > 0);
   userDao.deleteUser(users.get(0).getId_user());
   assertTrue(usersSize - 1 == userDao.getAllUsers().size());
 }
 /** Test of getUsersList method, of class UserDao. */
 @Ignore
 public void testGetUsersList() {
   System.out.println("getUsersList");
   UserDao instance = new UserDaoImpl();
   List<User> expResult = null;
   List<User> result = instance.getUsersList();
   assertEquals(expResult, result);
   // TODO review the generated test code and remove the default call to fail.
   fail("The test case is a prototype.");
 }
 @Test
 public void testAddUser() throws Exception {
   LOGGER.debug("test: addUser");
   Integer id_user = userDao.addUser(user);
   assertNotNull(id_user);
   User newUser = userDao.getUserById(id_user);
   assertEquals(user.getLogin(), newUser.getLogin());
   assertEquals(user.getPassword(), newUser.getPassword());
   assertEquals(user.getFirstname(), newUser.getFirstname());
   assertEquals(user.getLastname(), newUser.getLastname());
 }
 /** Test of createUser method, of class UserDao. */
 @Ignore
 public void testCreateUser() {
   System.out.println("createUser");
   User u = null;
   UserDao instance = new UserDaoImpl();
   String expResult = "";
   String result = instance.createUser(u);
   assertEquals(expResult, result);
   // TODO review the generated test code and remove the default call to fail.
   fail("The test case is a prototype.");
 }
示例#18
0
  public boolean enableUserByValidationKey(String emailValidationKey) {

    AppUser user = userDao.findByEmailValidationKey(emailValidationKey);
    boolean emailKeyExists = user != null;

    if (emailKeyExists) {
      user.setEnabled(true);
      user.setEmailValidationKey(null);
      userDao.merge(user);
    }

    return emailKeyExists;
  }
示例#19
0
 @PUT
 @Path("{userId}/fields")
 public Response updateUserFields(@PathParam("userId") final String userId, Fields fields)
     throws Exception {
   // todo: validate passed fields are valid or not
   User user = userDao.getUser(userId);
   setUpdatedFields(user, fields);
   user.setLastModifiedDate(System.currentTimeMillis());
   User updatedUser = userDao.updateUser(userId, user);
   checkWhetherSynchIsNeeded(updatedUser, fields);
   com.campusconnect.neo4j.types.web.User returnUser = mapUserNeo4jToWeb(updatedUser);
   return Response.ok().entity(returnUser).build();
 }
  @Test
  public void TUnitCreateAndSet() throws ClassNotFoundException, SQLException {

    dao.deleteAll();
    assertThat(dao.getCount(), is(0));

    dao.add(user1);
    assertThat(dao.getCount(), is(1));

    User user2 = dao.get(user1.getId());

    assertThat(user2.getName(), is(user1.getName()));
    assertThat(user2.getPW(), is(user1.getPW()));
  }
  @Test
  public void TUnitGetAll() {

    dao.deleteAll();

    List<User> users0 = dao.getAll();
    assertThat(users0.size(), is(0));

    dao.add(user1);
    List<User> users1 = dao.getAll();
    assertThat(users1.size(), is(1));
    checkSameUser(user1, users1.get(0));

    dao.add(user2);
    List<User> users2 = dao.getAll();
    assertThat(users2.size(), is(2));
    checkSameUser(user1, users1.get(0));
    checkSameUser(user2, users2.get(1));

    dao.add(user3);
    List<User> users3 = dao.getAll();
    assertThat(users3.size(), is(3));
    checkSameUser(user1, users1.get(0));
    checkSameUser(user2, users2.get(1));
    checkSameUser(user3, users3.get(2));
  }
示例#22
0
  public void testChangeUserRole() throws Exception {
    User user = dao.get(2L);
    assertEquals(6, user.getRoles().size());

    assertTrue(user.hasRole("ROLE_ADMIN"));

    user.getRoles().clear();
    user.addRole(rdao.getRoleByName("ROLE_EXTERNAL"));
    dao.saveUser(user);

    assertEquals(1, user.getRoles().size());

    assertTrue(user.getRoles().iterator().next().getName().equals("ROLE_EXTERNAL"));
  }
 /** To-one relationship, resolved on first access. */
 public User getUser() {
   Long __key = this.userId;
   if (user__resolvedKey == null || !user__resolvedKey.equals(__key)) {
     if (daoSession == null) {
       throw new DaoException("Entity is detached from DAO context");
     }
     UserDao targetDao = daoSession.getUserDao();
     User userNew = targetDao.load(__key);
     synchronized (this) {
       user = userNew;
       user__resolvedKey = __key;
     }
   }
   return user;
 }
示例#24
0
  @PUT
  @Path("{userId}/friend/{friendUserId}")
  public Response confirmFriend(
      @PathParam("userId") final String userId,
      @PathParam("friendUserId") final String friendUserId,
      @QueryParam(STATUS_QPARAM) final String status) {
    if (status.toLowerCase().equals("agreed")) {
      userDao.confirmFriendRelation(userDao.getUser(userId), userDao.getUser(friendUserId));
      // TODO:notification to user about acceptance

    } else if (status.toLowerCase().equals("cancel")) {
      userDao.deleteFriendRequest(userId, friendUserId, Constants.FRIEND_REQUEST_CANCEL_DELETE);
    }
    return Response.ok().build();
  }
示例#25
0
  public void testAddUserHistory() throws Exception {
    // Test that valid data works...
    dao.insertHistory(2L, 1L, 1L);

    // Now, invalid data
    Long messageId = 1234L; // Doesn't exist...
    Long userId = 4321L; // Also, doesn't exist...

    try {
      dao.insertHistory(userId, messageId, 1L);
      fail("insertHistory should have thrown an exception on foreign key validation");
    } catch (Exception e) {
      assertNotNull(e);
    }
  }
示例#26
0
  @POST
  @Path("{userId}/addresses")
  public Response addAddress(
      @PathParam("userId") String userId,
      com.campusconnect.neo4j.types.web.Address addressPayload) {
    Address address = mapAddressWebToNeo4j(addressPayload);
    User user = userDao.getUser(userId);
    // create new address
    Address createdAddress = addressDao.createAddress(address, userId);
    // Link to user
    userDao.addAddressToUser(createdAddress, user);

    com.campusconnect.neo4j.types.web.Address returnAddress = mapAddressNeo4jToWeb(createdAddress);
    return Response.ok().entity(returnAddress).build();
  }
  @RequestMapping(value = "/remove-userpic.jsp", method = RequestMethod.POST)
  public ModelAndView removeUserpic(ServletRequest request, @RequestParam("id") User user)
      throws Exception {
    Template tmpl = Template.getTemplate(request);

    if (!tmpl.isSessionAuthorized()) {
      throw new AccessViolationException("Not autorized");
    }

    User currentUser = tmpl.getCurrentUser();

    if (!currentUser.isModerator() && currentUser.getId() != user.getId()) {
      throw new AccessViolationException("Not permitted");
    }

    if (user.isModerator()) {
      throw new AccessViolationException(
          "Пользователю " + user.getNick() + " нельзя удалить картинку");
    }

    if (user.getPhoto() == null) {
      throw new AccessViolationException("Пользователь " + user.getNick() + " картинки не имеет");
    }

    if (userDao.removePhoto(user, currentUser)) {
      logger.info("Clearing " + user.getNick() + " userpic by " + currentUser.getNick());
    } else {
      logger.debug("SKIP Clearing " + user.getNick() + " userpic by " + currentUser.getNick());
    }

    return redirectToProfile(user);
  }
 @Test
 public void testGetUser() {
   expect(dao.load(1)).andReturn(fred);
   replay(dao);
   assertSame(fred, manager.getUser(1));
   verify(dao);
 }
示例#29
0
  @Override
  public void delete() {
    cancelListeners(getHibernateDao());

    Long pid = Long.valueOf(6L);
    Product product = dao.read(pid);
    Assert.assertNotNull(product);
    Set<User> authorizedUsers = product.getAuthorizedUsers();

    List<MetadataIndex> indexes = product.getIndexes();
    Assert.assertNotNull(indexes);
    Assert.assertFalse(indexes.isEmpty());
    Assert.assertFalse(authorizedUsers.isEmpty());

    dao.delete(product);
    getHibernateDao().getSessionFactory().getCurrentSession().flush();

    Assert.assertNull(dao.read(pid));
    Assert.assertEquals(countElements("METADATA_INDEXES", pid), 0);
    Assert.assertEquals(countElements("CHECKSUMS", pid), 0);

    for (User user : authorizedUsers) {
      Assert.assertNotNull(udao.read(user.getUUID()));
    }
  }
示例#30
0
  @Test
  public void findByLogin() throws Exception {
    UserDto dto = new UserDto().setLogin("david").setName("David").setEmail("*****@*****.**");
    when(dao.selectUserByLogin("david")).thenReturn(dto);

    assertThat(finder.findByLogin("david").name()).isEqualTo("David");
  }