From f148f16ac82815f65f0b4ff44e1b2184ec0da0b0 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Mon, 29 Apr 2019 16:25:38 +0300 Subject: Refactoring --- .../java/com/juick/server/api/ApiSocialLogin.java | 9 +- .../com/juick/server/www/controllers/SignUp.java | 48 +++-- src/main/java/com/juick/service/UserService.java | 4 +- .../java/com/juick/service/UserServiceImpl.java | 12 +- .../java/com/juick/server/tests/ServerTests.java | 213 ++++++++++----------- 5 files changed, 131 insertions(+), 155 deletions(-) diff --git a/src/main/java/com/juick/server/api/ApiSocialLogin.java b/src/main/java/com/juick/server/api/ApiSocialLogin.java index fe5f2069..2d0a5c7e 100644 --- a/src/main/java/com/juick/server/api/ApiSocialLogin.java +++ b/src/main/java/com/juick/server/api/ApiSocialLogin.java @@ -302,13 +302,10 @@ public class ApiSocialLogin { String verifiedEmail = emailService.getEmailByAuthCode(verificationCode); if (StringUtils.isNotEmpty(verifiedEmail)) { - int uid = userService.createUser(username, password); - if (uid <= 0) { - throw new HttpBadRequestException(); - } - emailService.addEmail(uid, verifiedEmail); + com.juick.User newUser = userService.createUser(username, password).orElseThrow(HttpBadRequestException::new); + emailService.addEmail(newUser.getUid(), verifiedEmail); emailService.deleteAuthCode(verificationCode); - return ResponseEntity.ok(userService.getUserByUID(uid).orElseThrow(IllegalStateException::new)); + return ResponseEntity.ok(newUser); } else { return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null); } diff --git a/src/main/java/com/juick/server/www/controllers/SignUp.java b/src/main/java/com/juick/server/www/controllers/SignUp.java index 8793478a..5fce2d35 100644 --- a/src/main/java/com/juick/server/www/controllers/SignUp.java +++ b/src/main/java/com/juick/server/www/controllers/SignUp.java @@ -17,6 +17,7 @@ package com.juick.server.www.controllers; import com.juick.User; +import com.juick.model.AnonymousUser; import com.juick.server.util.HttpBadRequestException; import com.juick.server.util.HttpForbiddenException; import com.juick.server.www.WebApp; @@ -24,6 +25,9 @@ import com.juick.service.CrosspostService; import com.juick.service.EmailService; import com.juick.service.UserService; import com.juick.service.security.annotation.Visitor; +import com.juick.service.security.entities.JuickUser; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; @@ -31,8 +35,6 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.inject.Inject; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletResponse; /** * @@ -93,14 +95,13 @@ public class SignUp { @PostMapping("/signup") protected String doPost( @Visitor User visitor, - HttpServletResponse response, @RequestParam String type, @RequestParam String hash, @RequestParam String action, @RequestParam(required = false) String username, @RequestParam(required = false) String password, ModelMap modelMap) { - int uid = 0; + User current; if (hash.length() > 36 || !type.matches("^[a-zA-Z0-9\\-]+$") || !hash.matches("^[a-zA-Z0-9\\-]+$")) { throw new HttpBadRequestException(); @@ -112,22 +113,23 @@ public class SignUp { if (username.length() > 32) { throw new HttpBadRequestException(); } - uid = userService.checkPassword(username, password); + current = userService.checkPassword(username, password).orElseThrow(HttpForbiddenException::new); } else { - uid = visitor.getUid(); + current = visitor; } - if (uid <= 0) { + if (current.getUid() <= 0) { throw new HttpForbiddenException(); } - if (!(type.charAt(0) == 'f' && crosspostService.setFacebookUser(hash, uid)) - && !(type.charAt(0) == 'v' && crosspostService.setVKUser(hash, uid)) - && !(type.charAt(0) == 'd' && crosspostService.setTelegramUser(hash, uid)) - && !(type.charAt(0) == 'x' && userService.getAllJIDs(visitor).size() > 0 && crosspostService.setJIDUser(hash, uid))) { + if (!(type.charAt(0) == 'f' && crosspostService.setFacebookUser(hash, current.getUid())) + && !(type.charAt(0) == 'v' && crosspostService.setVKUser(hash, current.getUid())) + && !(type.charAt(0) == 'd' && crosspostService.setTelegramUser(hash, current.getUid())) + && !(type.charAt(0) == 'x' && userService.getAllJIDs(visitor).size() > 0 + && crosspostService.setJIDUser(hash, current.getUid()))) { if (type.equals("email")) { String email = emailService.getEmailByAuthCode(hash); - emailService.addEmail(uid, email); + emailService.addEmail(current.getUid(), email); emailService.deleteAuthCode(hash); } else { if (type.equals("xmpp")) { @@ -144,19 +146,14 @@ public class SignUp { throw new HttpBadRequestException(); } - // CHECK USERNAME + current = userService.createUser(username, password).orElseThrow(HttpBadRequestException::new); - uid = userService.createUser(username, password); - if (uid <= 0) { - throw new HttpBadRequestException(); - } - - if (!(type.charAt(0) == 'f' && crosspostService.setFacebookUser(hash, uid)) - && !(type.charAt(0) == 'v' && crosspostService.setVKUser(hash, uid)) - && !(type.charAt(0) == 'd' && crosspostService.setTelegramUser(hash, uid))) { + if (!(type.charAt(0) == 'f' && crosspostService.setFacebookUser(hash, current.getUid())) + && !(type.charAt(0) == 'v' && crosspostService.setVKUser(hash, current.getUid())) + && !(type.charAt(0) == 'd' && crosspostService.setTelegramUser(hash, current.getUid()))) { if (type.equals("email")) { String email = emailService.getEmailByAuthCode(hash); - emailService.addEmail(uid, email); + emailService.addEmail(current.getUid(), email); emailService.deleteAuthCode(hash); } else { if (type.equals("xmpp")) { @@ -170,10 +167,9 @@ public class SignUp { } if (visitor.isAnonymous()) { - hash = userService.getHashByUID(uid); - Cookie c = new Cookie("hash", hash); - c.setMaxAge(365 * 24 * 60 * 60); - response.addCookie(c); + UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = + new UsernamePasswordAuthenticationToken(new JuickUser(current), password, JuickUser.USER_AUTHORITY); + SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); } return "redirect:/"; } diff --git a/src/main/java/com/juick/service/UserService.java b/src/main/java/com/juick/service/UserService.java index 3a51dffb..0d4efcfc 100644 --- a/src/main/java/com/juick/service/UserService.java +++ b/src/main/java/com/juick/service/UserService.java @@ -40,7 +40,7 @@ public interface UserService { String getSignUpHashByTelegramID(Long telegramId, String username); - int createUser(String username, String password); + Optional createUser(String username, String password); Optional getUserByUID(int uid); @@ -66,7 +66,7 @@ public interface UserService { String getHashByUID(int uid); - int checkPassword(String username, String password); + Optional checkPassword(String username, String password); boolean updatePassword(User user, String newPassword); diff --git a/src/main/java/com/juick/service/UserServiceImpl.java b/src/main/java/com/juick/service/UserServiceImpl.java index bcfb8dac..8d2947f8 100644 --- a/src/main/java/com/juick/service/UserServiceImpl.java +++ b/src/main/java/com/juick/service/UserServiceImpl.java @@ -103,7 +103,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { @Transactional @Override - public int createUser(final String username, final String password) { + public Optional createUser(final String username, final String password) { KeyHolder holder = new GeneratedKeyHolder(); try { getJdbcTemplate().update( @@ -117,7 +117,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { }, holder); } catch (DuplicateKeyException e) { - return -1; + return Optional.empty(); } int uid = holder.getKeys().size() > 1 ? (int)holder.getKeys().get("id") : holder.getKey().intValue(); @@ -125,7 +125,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { getJdbcTemplate().update("INSERT INTO useroptions(user_id) VALUES (?)", uid); getJdbcTemplate().update("INSERT INTO subscr_users(user_id, suser_id) VALUES (2, ?)", uid); - return uid; + return getUserByUID(uid); } @Transactional(readOnly = true) @@ -322,7 +322,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { @Transactional(readOnly = true) @Override - public int checkPassword(final String username, final String password) { + public Optional checkPassword(final String username, final String password) { if (StringUtils.isNotBlank(username)) { List list = getJdbcTemplate().query( "SELECT DISTINCT u.id, u.nick, u.passw, u.banned, u.last_seen," + @@ -337,10 +337,10 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { if (!list.isEmpty()) { User user = list.get(0); if (Objects.equals(password, user.getCredentials())) - return user.getUid(); + return Optional.of(user); } } - return -1; + return Optional.empty(); } @Transactional diff --git a/src/test/java/com/juick/server/tests/ServerTests.java b/src/test/java/com/juick/server/tests/ServerTests.java index be077e00..c554f20e 100644 --- a/src/test/java/com/juick/server/tests/ServerTests.java +++ b/src/test/java/com/juick/server/tests/ServerTests.java @@ -252,12 +252,9 @@ public class ServerTests { freefdPassword = "MyPassw0rd!"; juickName = "juick"; juickPassword = "demo"; - int ugnichId = userService.createUser(ugnichName, ugnichPassword); - ugnich = userService.getUserByUID(ugnichId).orElseThrow(IllegalStateException::new); - int freefdId = userService.createUser(freefdName, freefdPassword); - freefd = userService.getUserByUID(freefdId).orElseThrow(IllegalStateException::new); - int juickId = userService.createUser(juickName, juickPassword); - juick = userService.getUserByUID(juickId).orElseThrow(IllegalStateException::new); + ugnich = userService.createUser(ugnichName, ugnichPassword).orElseThrow(IllegalStateException::new); + freefd = userService.createUser(freefdName, freefdPassword).orElseThrow(IllegalStateException::new); + juick = userService.createUser(juickName, juickPassword).orElseThrow(IllegalStateException::new); webClient.getOptions().setJavaScriptEnabled(false); isSetUp = true; } @@ -278,8 +275,8 @@ public class ServerTests { int mid2 = messagesService.createMessage(ugnich.getUid(), "test2", null, null); List freefdFeed = messagesService.getMyFeed(freefd.getUid(), 0, false); assertThat(freefdFeed.get(0), equalTo(mid2)); - int tonyaid = userService.createUser("Tonya", "secret"); - int mid3 = messagesService.createMessage(tonyaid, "test3", null, null); + User tonya = userService.createUser("Tonya", "secret").orElseThrow(IllegalStateException::new);; + int mid3 = messagesService.createMessage(tonya.getUid(), "test3", null, null); messagesService.recommendMessage(mid3, ugnich.getUid()); assertThat(messagesService.getMyFeed(freefd.getUid(), 0, false).get(0), equalTo(mid2)); assertThat(messagesService.getMyFeed(freefd.getUid(), 0, true).get(0), equalTo(mid3)); @@ -328,10 +325,9 @@ public class ServerTests { @Test public void messageTests() { - int user_id = userService.createUser("mmmme", "secret"); - User user = userService.getUserByUID(user_id).orElse(AnonymousUser.INSTANCE); + User user = userService.createUser("mmmme", "secret").orElseThrow(IllegalStateException::new);; assertEquals("it should be me", "mmmme", user.getName()); - int mid = messagesService.createMessage(user_id, "yo", null, new ArrayList<>()); + int mid = messagesService.createMessage(user.getUid(), "yo", null, new ArrayList<>()); Message msg = messagesService.getMessage(mid).get(); assertEquals("yo", msg.getText()); User me = msg.getUser(); @@ -341,13 +337,12 @@ public class ServerTests { Tag tag = tagService.getTag(tagID); List tagList = new ArrayList<>(); tagList.add(tag); - int mid2 = messagesService.createMessage(user_id, "yo2", null, tagList); + int mid2 = messagesService.createMessage(user.getUid(), "yo2", null, tagList); Message msg2 = messagesService.getMessage(mid2).get(); assertEquals(1, msg2.getTags().size()); - assertEquals("we already have ugnich", -1, userService.createUser("ugnich", "x")); - int ugnich_id = userService.createUser("hugnich", "x"); - User ugnich = userService.getUserByUID(ugnich_id).orElse(AnonymousUser.INSTANCE); - int rid = messagesService.createReply(msg2.getMid(), 0, ugnich, "bla-bla", null); + assertEquals("we already have ugnich", Optional.empty(), userService.createUser("ugnich", "x")); + User hugnich = userService.createUser("hugnich", "x").orElseThrow(IllegalStateException::new);; + int rid = messagesService.createReply(msg2.getMid(), 0, hugnich, "bla-bla", null); assertEquals(1, rid); assertThat(msg2.getTo(), equalTo(AnonymousUser.INSTANCE)); Message reply = messagesService.getReply(msg2.getMid(), rid); @@ -355,7 +350,7 @@ public class ServerTests { List replies = messagesService.getReplies(user, msg2.getMid()); assertThat(replies.size(), equalTo(1)); assertThat(replies.get(0), equalTo(reply)); - int ridToReply = messagesService.createReply(msg2.getMid(), 1, ugnich, "blax2", null); + int ridToReply = messagesService.createReply(msg2.getMid(), 1, hugnich, "blax2", null); Message reply2 = messagesService.getReply(msg2.getMid(), ridToReply); assertThat(reply.getTo().getName(), equalTo(user.getName())); List replies2 = messagesService.getReplies(user, msg2.getMid()); @@ -366,8 +361,8 @@ public class ServerTests { assertEquals(2, msg3.getReplies()); assertEquals("weather", msg3.getTags().stream().findFirst().get().getName()); - assertEquals(ugnich.getUid(), userService.checkPassword(ugnich.getName(), "x")); - assertEquals(-1, userService.checkPassword(ugnich.getName(), "xy")); + assertThat(hugnich, is(userService.checkPassword(hugnich.getName(), "x").get())); + assertThat(userService.checkPassword(hugnich.getName(), "xy"), is(Optional.empty())); subscriptionService.subscribeMessage(msg, user); subscriptionService.subscribeMessage(msg, ugnich); @@ -376,26 +371,26 @@ public class ServerTests { messagesService.getReply(msg.getMid(), reply_id)).size()); assertThat(messagesService.getDiscussions(ugnich.getUid(), 0L).get(0), equalTo(msg.getMid())); - messagesService.deleteMessage(user_id, mid); - messagesService.deleteMessage(user_id, mid2); + messagesService.deleteMessage(user.getUid(), mid); + messagesService.deleteMessage(user.getUid(), mid2); String htmlTagName = ">_<"; Tag htmlTag = tagService.getTag(htmlTagName, true); TagStats htmlTagStats = new TagStats(); htmlTagStats.setTag(htmlTag); String dbTagName = jdbcTemplate.queryForObject("select name from tags where name=?", String.class, htmlTagName); assertEquals("db tags should not be escaped", dbTagName, htmlTag.getName()); - int mid4 = messagesService.createMessage(user_id, "yoyoyo", null, null); + int mid4 = messagesService.createMessage(user.getUid(), "yoyoyo", null, null); Message msg4 = messagesService.getMessage(mid4).get(); assertEquals("tags string should be empty", StringUtils.EMPTY, MessageUtils.getTagsString(msg4)); - messagesService.deleteMessage(user_id, mid4); + messagesService.deleteMessage(user.getUid(), mid4); } public ExpectedException exception = ExpectedException.none(); @Test public void likeTypeStatsTests(){ - int user_id = userService.createUser("dsdss", "secret"); + User dsdss = userService.createUser("dsdss", "secret").orElseThrow(IllegalStateException::new);; final int freefdId = freefd.getUid(); - int mid = messagesService.createMessage(user_id, "yo", null, new ArrayList<>()); + int mid = messagesService.createMessage(dsdss.getUid(), "yo", null, new ArrayList<>()); messagesService.likeMessage(mid, freefdId , 2); messagesService.likeMessage(mid, freefdId,2); messagesService.likeMessage(mid, freefdId,3); @@ -411,24 +406,24 @@ public class ServerTests { } @Test public void lastJidShouldNotBeDeleted() { - int ugnich_id = userService.createUser("hugnich2", "x"); - jdbcTemplate.update("INSERT INTO jids(user_id,jid,active) VALUES(?,?,?)", ugnich_id, "firstjid@localhost", 1); - jdbcTemplate.update("INSERT INTO jids(user_id,jid,active) VALUES(?,?,?)", ugnich_id, "secondjid@localhost", 1); - assertThat(userService.deleteJID(ugnich_id, "secondjid@localhost"), equalTo(true)); - assertThat(userService.deleteJID(ugnich_id, "firstjid@localhost"), equalTo(false)); + User hugnich2 = userService.createUser("hugnich2", "x").orElseThrow(IllegalStateException::new);; + jdbcTemplate.update("INSERT INTO jids(user_id,jid,active) VALUES(?,?,?)", hugnich2.getUid(), "firstjid@localhost", 1); + jdbcTemplate.update("INSERT INTO jids(user_id,jid,active) VALUES(?,?,?)", hugnich2.getUid(), "secondjid@localhost", 1); + assertThat(userService.deleteJID(hugnich2.getUid(), "secondjid@localhost"), equalTo(true)); + assertThat(userService.deleteJID(hugnich2.getUid(), "firstjid@localhost"), equalTo(false)); } @Test public void lastEmailShouldNotBeDeleted() { - int ugnich_id = userService.createUser("hugnich3", "x"); - jdbcTemplate.update("INSERT INTO emails(user_id,email) VALUES(?,?)", ugnich_id, "first@localhost"); - jdbcTemplate.update("INSERT INTO emails(user_id,email) VALUES(?,?)", ugnich_id, "second@localhost"); - assertThat(emailService.deleteEmail(ugnich_id, "second@localhost"), equalTo(true)); - assertThat(emailService.deleteEmail(ugnich_id, "first@localhost"), equalTo(false)); + User hugnich3 = userService.createUser("hugnich3", "x").orElseThrow(IllegalStateException::new);; + jdbcTemplate.update("INSERT INTO emails(user_id,email) VALUES(?,?)", hugnich3.getUid(), "first@localhost"); + jdbcTemplate.update("INSERT INTO emails(user_id,email) VALUES(?,?)", hugnich3.getUid(), "second@localhost"); + assertThat(emailService.deleteEmail(hugnich3.getUid(), "second@localhost"), equalTo(true)); + assertThat(emailService.deleteEmail(hugnich3.getUid(), "first@localhost"), equalTo(false)); } @Test public void messageUpdatedTimeShouldMatchLastReplyTime() throws InterruptedException { - int ugnich_id = userService.createUser("hugnich4", "x"); - int mid = messagesService.createMessage(ugnich_id, "yo", null, null); + User hugnich4 = userService.createUser("hugnich4", "x").orElseThrow(IllegalStateException::new);; + int mid = messagesService.createMessage(hugnich4.getUid(), "yo", null, null); Instant ts = jdbcTemplate.queryForObject("SELECT updated FROM messages WHERE message_id=?", Timestamp.class, mid).toInstant(); Thread.sleep(1000); @@ -438,7 +433,7 @@ public class ServerTests { assertThat(rts, greaterThan(ts)); Message msg = messagesService.getReply(mid, rid); assertThat(rts, equalTo(msg.getCreated())); - messagesService.deleteMessage(ugnich_id, mid); + messagesService.deleteMessage(hugnich4.getUid(), mid); } @Test @@ -544,13 +539,12 @@ public class ServerTests { @Test public void messagesUrlTest() throws Exception { - int user_id = userService.createUser("dsds4345", "secret"); + User dsds4345 = userService.createUser("dsds4345", "secret").orElseThrow(IllegalStateException::new);; String freefdHash = userService.getHashByUID(freefd.getUid()); - System.out.println("user_id"+ user_id); - String userIdHash = userService.getHashByUID(user_id); + String userIdHash = userService.getHashByUID(dsds4345.getUid()); final int freefdId = freefd.getUid(); - int mid = messagesService.createMessage(user_id, "yo", null, new ArrayList<>()); + int mid = messagesService.createMessage(dsds4345.getUid(), "yo", null, new ArrayList<>()); messagesService.likeMessage(mid, freefdId, 2 ); messagesService.likeMessage(mid, freefdId, 2 ); messagesService.likeMessage(mid, freefdId, 3 ); @@ -715,8 +709,7 @@ public class ServerTests { @Test public void protocolTests() throws Exception { - int uid = userService.createUser("me", "secret"); - User user = userService.getUserByUID(uid).orElse(AnonymousUser.INSTANCE); + User user = userService.createUser("me", "secret").orElseThrow(IllegalStateException::new);; Tag yo = tagService.getTag("yo", true); Message msg = commandsManager.processCommand(user, "*yo yoyo", URI.create("https://static.juick.com/settings/facebook.png")).getNewMessage().get(); assertThat(msg.getAttachmentType(), is("png")); @@ -735,8 +728,7 @@ public class ServerTests { assertThat(last.toInstant(), equalTo(yoyoMsg.getNewMessage().get().getCreated())); assertEquals("should be message", true, commandsManager.processCommand(user, String.format("#%d", mid), emptyUri).getText().startsWith("@me")); - int readerUid = userService.createUser("dummyReader", "dummySecret"); - User readerUser = userService.getUserByUID(readerUid).orElse(AnonymousUser.INSTANCE); + User readerUser = userService.createUser("dummyReader", "dummySecret").orElseThrow(IllegalStateException::new);; assertThat(commandsManager.processCommand(readerUser, "s", emptyUri).getText().startsWith("You are subscribed to"), is(true)); assertThat(commandsManager.processCommand(readerUser, "S", emptyUri).getText().startsWith("You are subscribed to"), is(true)); assertEquals("should be subscribed", "Subscribed", @@ -760,11 +752,11 @@ public class ServerTests { assertEquals("should be subscribed", "Subscribed to @" + user.getName(), commandsManager.processCommand(readerUser, "S @" + user.getName(), emptyUri) .getText()); - List friends = userService.getUserFriends(readerUid); + List friends = userService.getUserFriends(readerUser.getUid()); assertEquals("number of friend users should match", 2, friends.size()); assertEquals("number of reader users should match", 1, - userService.getUserReaders(uid).size()); + userService.getUserReaders(user.getUid()).size()); String expectedSecondReply = "Reply posted.\n#" + mid + "/2 " + "https://juick.com/m/" + mid + "#2"; String expectedThirdReply = "Reply posted.\n#" + mid + "/3 " @@ -789,32 +781,31 @@ public class ServerTests { assertEquals("should be blacklisted", "Tag added to your blacklist", commandsManager.processCommand(readerUser, "BL *there", emptyUri).getText()); assertEquals("number of subscribed users should match", 0, - subscriptionService.getSubscribedUsers(uid, msg2).size()); + subscriptionService.getSubscribedUsers(user.getUid(), msg2).size()); assertEquals("tags should be updated", "Tags are updated", commandsManager.processCommand(user, "#" + mid + " *there", emptyUri).getText()); assertEquals("number of tags should match", 1, tagService.getMessageTags(mid).size()); - int taggerUid = userService.createUser("dummyTagger", "dummySecret"); - User taggerUser = userService.getUserByUID(taggerUid).orElse(AnonymousUser.INSTANCE); + User taggerUser = userService.createUser("dummyTagger", "dummySecret").orElseThrow(IllegalStateException::new);; assertEquals("should be subscribed", "Subscribed", commandsManager.processCommand(taggerUser, "S *yo", emptyUri).getText()); assertEquals("number of subscribed users should match", 2, - subscriptionService.getSubscribedUsers(uid, msg2).size()); + subscriptionService.getSubscribedUsers(user.getUid(), msg2).size()); assertEquals("should be unsubscribed", "Unsubscribed from yo", commandsManager.processCommand(taggerUser, "U *yo", emptyUri).getText()); assertEquals("number of subscribed users should match", 1, - subscriptionService.getSubscribedUsers(uid, msg2).size()); + subscriptionService.getSubscribedUsers(user.getUid(), msg2).size()); assertEquals("number of readers should match", 1, - userService.getUserReaders(uid).size()); + userService.getUserReaders(user.getUid()).size()); String readerFeed = commandsManager.processCommand(readerUser, "#", emptyUri).getText(); assertTrue("description should match", readerFeed.startsWith("Your feed")); assertEquals("should be unsubscribed", "Unsubscribed from @" + user.getName(), commandsManager.processCommand(readerUser, "U @" + user.getName(), emptyUri) .getText()); assertEquals("number of readers should match", 0, - userService.getUserReaders(uid).size()); + userService.getUserReaders(user.getUid()).size()); assertEquals("number of friends should match", 1, - userService.getUserFriends(uid).size()); + userService.getUserFriends(user.getUid()).size()); assertEquals("should be unsubscribed", "Unsubscribed from #" + mid, commandsManager.processCommand(readerUser, "u #" + mid, emptyUri).getText()); assertEquals("number of subscribed users should match", 0, @@ -915,9 +906,9 @@ public class ServerTests { @Test public void likesTests() throws Exception{ - int user_id = userService.createUser("dsds", "secret"); + User dsds = userService.createUser("dsds", "secret").orElseThrow(IllegalStateException::new);; String freefdHash = userService.getHashByUID(freefd.getUid()); - int mid1 = messagesService.createMessage(user_id, "yo", null, new ArrayList<>()); + int mid1 = messagesService.createMessage(dsds.getUid(), "yo", null, new ArrayList<>()); mockMvc.perform(post("/api/react?mid=" + mid1 + "&hash=" + freefdHash+ "&reactionId=2")) .andExpect(status().isOk()); @@ -995,14 +986,14 @@ public class ServerTests { .stream().noneMatch(m -> m.getTags().contains(banned))); assertTrue(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getMyFeed(freefd.getUid(), 0, true)) .stream().noneMatch(m -> m.getTags().contains(banned))); - int newUid = userService.createUser("newUser1", "12345"); - int newMid = messagesService.createMessage(newUid, "people", null, Collections.singletonList(banned)); + User newUser1 = userService.createUser("newUser1", "12345").orElseThrow(IllegalStateException::new);; + int newMid = messagesService.createMessage(newUser1.getUid(), "people", null, Collections.singletonList(banned)); messagesService.recommendMessage(newMid, ugnich.getUid()); assertTrue(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getMyFeed(freefd.getUid(), 0, true)) .stream().noneMatch(m -> m.getTags().contains(banned))); tagService.updateTags(newMid, Collections.singletonList(banned)); assertThat(messagesService.getMessage(newMid).get().getTags().size(), is(0)); - privacyQueriesService.blacklistUser(freefd, userService.getUserByUID(newUid).orElse(AnonymousUser.INSTANCE)); + privacyQueriesService.blacklistUser(freefd, newUser1); assertTrue(messagesService.getMyFeed(freefd.getUid(), 0, true) .stream().noneMatch(m -> m == newMid)); } @@ -1252,47 +1243,41 @@ public class ServerTests { } @Test public void subscribersToRecommendations() { - int readerId = userService.createUser("reader", "123456"); - int recommenderId = userService.createUser("recommender", "123456"); - int lateRecommenderId = userService.createUser("lateRecommender", "123456"); - int posterId = userService.createUser("poster", "123456"); - User reader = userService.getUserByName("reader"); - User recommender = userService.getUserByName("recommender"); - User lateRecommender = userService.getUserByName("lateRecommender"); - User poster = userService.getUserByName("poster"); + User reader = userService.createUser("reader", "123456").orElseThrow(IllegalStateException::new);; + User recommender = userService.createUser("recommender", "123456").orElseThrow(IllegalStateException::new);; + User lateRecommender = userService.createUser("lateRecommender", "123456").orElseThrow(IllegalStateException::new);; + User poster = userService.createUser("poster", "123456").orElseThrow(IllegalStateException::new);; subscriptionService.subscribeUser(reader, recommender); subscriptionService.subscribeUser(reader, lateRecommender); Tag sampleTag = tagService.getTag("banned", true); - int posterMid = messagesService.createMessage(posterId, "YO", null, Collections.singletonList(sampleTag)); - messagesService.recommendMessage(posterMid, recommenderId); + int posterMid = messagesService.createMessage(poster.getUid(), "YO", null, Collections.singletonList(sampleTag)); + messagesService.recommendMessage(posterMid, recommender.getUid()); BiFunction> subscribers = (recommId, msg) -> subscriptionService.getUsersSubscribedToUserRecommendations(recommId, msg); - List recommendSubscribers = subscribers.apply(recommenderId, messagesService.getMessage(posterMid).get()); + List recommendSubscribers = subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()); assertThat(recommendSubscribers.size(), is(1)); - assertThat(recommendSubscribers.get(0).getUid(), is(readerId)); + assertThat(recommendSubscribers.get(0).getUid(), is(reader.getUid())); privacyQueriesService.blacklistUser(reader, poster); - assertThat(subscribers.apply(recommenderId, messagesService.getMessage(posterMid).get()).size(), is(0)); + assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()).size(), is(0)); privacyQueriesService.blacklistUser(reader, poster); - assertThat(subscribers.apply(recommenderId, messagesService.getMessage(posterMid).get()).size(), is(1)); + assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()).size(), is(1)); tagService.blacklistTag(reader, sampleTag); - assertThat(subscribers.apply(recommenderId, messagesService.getMessage(posterMid).get()).size(), is(0)); + assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()).size(), is(0)); tagService.blacklistTag(reader, sampleTag); - assertThat(subscribers.apply(recommenderId, messagesService.getMessage(posterMid).get()).size(), is(1)); - messagesService.recommendMessage(posterMid, lateRecommenderId); - List lateRecommendSubscribers = subscribers.apply(recommenderId, messagesService.getMessage(posterMid).get()); + assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()).size(), is(1)); + messagesService.recommendMessage(posterMid, lateRecommender.getUid()); + List lateRecommendSubscribers = subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()); assertThat(lateRecommendSubscribers.size(), is(0)); - int readerMid = messagesService.createMessage(readerId, "PEOPLE", null, null); - messagesService.recommendMessage(readerMid, recommenderId); - assertThat(subscribers.apply(recommenderId, messagesService.getMessage(readerMid).get()).size(), is(0)); + int readerMid = messagesService.createMessage(reader.getUid(), "PEOPLE", null, null); + messagesService.recommendMessage(readerMid, recommender.getUid()); + assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(readerMid).get()).size(), is(0)); } @Test public void mentionsInComments() { - int posterId = userService.createUser("p", "secret"); - int commenterId = userService.createUser("cc", "secret"); - User commenter = userService.getUserByUID(commenterId).get(); - int mentionerId = userService.createUser("mmm", "secret"); - User mentioner = userService.getUserByUID(mentionerId).get(); - int mid = messagesService.createMessage(posterId, "who is dick?", null, null); + User poster = userService.createUser("p", "secret").orElseThrow(IllegalStateException::new);; + User commenter = userService.createUser("cc", "secret").orElseThrow(IllegalStateException::new);; + User mentioner = userService.createUser("mmm", "secret").orElseThrow(IllegalStateException::new);; + int mid = messagesService.createMessage(poster.getUid(), "who is dick?", null, null); Message msg = messagesService.getMessage(mid).get(); int rid = messagesService.createReply(mid, 0, commenter, "@mmm is dick", null); @@ -1305,8 +1290,7 @@ public class ServerTests { } @Test public void credentialsShouldNeverBeSerialized() throws Exception { - int uid = userService.createUser("yyy", "xxxx"); - User yyy = userService.getUserByUID(uid).get(); + User yyy = userService.createUser("yyy", "xxxx").orElseThrow(IllegalStateException::new);; assertThat(yyy.getCredentials(), is("xxxx")); ObjectMapper jsonMapper = new ObjectMapper(); jsonMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); @@ -1336,7 +1320,7 @@ public class ServerTests { String userPassword = "secret"; String msgText = "автор этого поста был забанен"; - User isilmine = userService.getUserByUID(userService.createUser(userName, userPassword)).orElseThrow(IllegalStateException::new); + User isilmine = userService.createUser(userName, userPassword).orElseThrow(IllegalStateException::new); int mid = messagesService.createMessage(isilmine.getUid(), msgText, null, null); mockMvc.perform(get(String.format("/api/thread?mid=%d", mid)).with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().isOk()); @@ -1367,14 +1351,14 @@ public class ServerTests { @Test public void bannedUserShouldBeShadowedFromRecommendationsList() throws IOException { jdbcTemplate.execute("DELETE FROM bl_users"); - int ermineId = userService.createUser("ermine", "secret"); - int monstreekId = userService.createUser("monstreek", "secret"); - int pogoId = userService.createUser("pogo", "secret"); - int fmapId = userService.createUser("fmap", "secret"); - int mid = messagesService.createMessage(monstreekId, "KURWA", null, null); - assertThat(messagesService.recommendMessage(mid, ermineId), is(MessagesService.RecommendStatus.Added)); - assertThat(messagesService.recommendMessage(mid, fmapId), is(MessagesService.RecommendStatus.Added)); - assertThat(messagesService.recommendMessage(mid, pogoId), is(MessagesService.RecommendStatus.Added)); + User ermine = userService.createUser("ermine", "secret").orElseThrow(IllegalStateException::new);; + User monstreek = userService.createUser("monstreek", "secret").orElseThrow(IllegalStateException::new);; + User pogo = userService.createUser("pogo", "secret").orElseThrow(IllegalStateException::new);; + User fmap = userService.createUser("fmap", "secret").orElseThrow(IllegalStateException::new);; + int mid = messagesService.createMessage(monstreek.getUid(), "KURWA", null, null); + assertThat(messagesService.recommendMessage(mid, ermine.getUid()), is(MessagesService.RecommendStatus.Added)); + assertThat(messagesService.recommendMessage(mid, fmap.getUid()), is(MessagesService.RecommendStatus.Added)); + assertThat(messagesService.recommendMessage(mid, pogo.getUid()), is(MessagesService.RecommendStatus.Added)); jdbcTemplate.update("INSERT INTO favorites(user_id, user_uri, message_id, like_id, ts) " + "values (0, 'http://example.com/u/test', ?, 1, now())", mid); assertThat(messagesService.getMessage(mid).get().getLikes(), is(4)); @@ -1393,15 +1377,15 @@ public class ServerTests { @Test public void bannedUserShouldNotBeVisibleToOthers() { jdbcTemplate.execute("DELETE FROM messages"); - int casualUserId = userService.createUser("user", "secret"); - int bannedUserId = userService.createUser("banned", "banned"); - jdbcTemplate.update("UPDATE users SET banned=1 WHERE id=?", bannedUserId); - messagesService.createMessage(bannedUserId, "KURWA", null, Collections.emptyList()); - assertThat(messagesService.getAll(casualUserId, 0).size(), is(0)); - assertThat(messagesService.getDiscussions(casualUserId, 0L).size(), is(0)); + User casualUser = userService.createUser("user", "secret").orElseThrow(IllegalStateException::new);; + User bannedUser = userService.createUser("banned", "banned").orElseThrow(IllegalStateException::new);; + jdbcTemplate.update("UPDATE users SET banned=1 WHERE id=?", bannedUser.getUid()); + messagesService.createMessage(bannedUser.getUid(), "KURWA", null, Collections.emptyList()); + assertThat(messagesService.getAll(casualUser.getUid(), 0).size(), is(0)); + assertThat(messagesService.getDiscussions(casualUser.getUid(), 0L).size(), is(0)); assertThat(messagesService.getDiscussions(0, 0L).size(), is(0)); - assertThat(messagesService.getAll(bannedUserId, 0).size(), is(1)); - int mid = messagesService.createMessage(casualUserId, "PEACE", null, Collections.emptyList()); + assertThat(messagesService.getAll(bannedUser.getUid(), 0).size(), is(1)); + int mid = messagesService.createMessage(casualUser.getUid(), "PEACE", null, Collections.emptyList()); User banned = userService.getUserByName("banned"); int bannedRid = messagesService.createReply(mid, 0, banned, "KURWA", null); int casualRid = messagesService.createReply(mid, 0, userService.getUserByName("user"), "DOOR", null); @@ -1482,9 +1466,8 @@ public class ServerTests { assertThat(threadPage.querySelectorAll(".a-thread-comment").isEmpty(), equalTo(false)); privacyQueriesService.blacklistUser(freefd, ugnich); assertThat(userService.isInBLAny(freefd.getUid(), ugnich.getUid()), equalTo(true)); - int renhaId = userService.createUser("renha", "secret"); - messagesService.createReply(mid, 0, userService.getUserByUID(renhaId).orElseThrow(IllegalStateException::new), - "people", null); + User renha = userService.createUser("renha", "secret").orElseThrow(IllegalStateException::new); + messagesService.createReply(mid, 0, renha,"people", null); threadPage = webClient.getPage(String.format("http://localhost:8080/ugnich/%d", mid)); assertThat(threadPage.getWebResponse().getStatusCode(), equalTo(200)); assertThat(threadPage.querySelectorAll(".msg-comment-target").isEmpty(), equalTo(true)); @@ -1833,11 +1816,11 @@ public class ServerTests { @Test public void seenTests() { Instant now = Instant.now(); - int newUserUid = userService.createUser("newuser", "assword"); - assertThat(newUserUid, greaterThanOrEqualTo(0)); - assertThat(userService.getUserByUID(newUserUid).get().getSeen(), is(nullValue())); - messagesService.createMessage(newUserUid, "YO", "", null); - assertThat(userService.getUserByUID(newUserUid).get().getSeen(), greaterThanOrEqualTo(now)); + User newUser = userService.createUser("newuser", "assword").orElseThrow(IllegalStateException::new);; + assertThat(newUser.getUid(), greaterThanOrEqualTo(0)); + assertThat(newUser.getSeen(), is(nullValue())); + messagesService.createMessage(newUser.getUid(), "YO", "", null); + assertThat(userService.getUserByUID(newUser.getUid()).get().getSeen(), greaterThanOrEqualTo(now)); } @Test public void signupTest() throws Exception { -- cgit v1.2.3