From b73568fe17500765c33f6a062226e6b433412c49 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 24 Mar 2021 19:01:19 +0300 Subject: Cleanup HttpMediaTypeNotAcceptableException handler * move ExceptionHandler to ControllerAdvice * add test * reindent using VSCode --- .../java/com/juick/server/tests/ServerTests.java | 1053 +++++++++----------- 1 file changed, 454 insertions(+), 599 deletions(-) (limited to 'src/test/java/com') diff --git a/src/test/java/com/juick/server/tests/ServerTests.java b/src/test/java/com/juick/server/tests/ServerTests.java index cea3818e..30c7a3d6 100644 --- a/src/test/java/com/juick/server/tests/ServerTests.java +++ b/src/test/java/com/juick/server/tests/ServerTests.java @@ -159,9 +159,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. */ @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) -@TestPropertySource(properties = { - "ios_app_id=12345678.com.juick.ExampleApp" -}) +@TestPropertySource(properties = { "ios_app_id=12345678.com.juick.ExampleApp" }) @AutoConfigureMockMvc public class ServerTests { @@ -324,9 +322,11 @@ public class ServerTests { assertThat(messagesService.getMyFeed(freefd.getUid(), 0, false).get(0), equalTo(mid2)); assertThat(messagesService.getMyFeed(freefd.getUid(), 0, true).get(0), equalTo(mid3)); assertThat(messagesService.getMyFeed(freefd.getUid(), mid2, true).get(0), equalTo(mid0)); - assertThat(messagesService.recommendMessage(mid0, ugnich.getUid()), equalTo(MessagesService.RecommendStatus.Added)); + assertThat(messagesService.recommendMessage(mid0, ugnich.getUid()), + equalTo(MessagesService.RecommendStatus.Added)); assertThat(messagesService.getMessage(mid0).orElseThrow(IllegalStateException::new).getLikes(), equalTo(1)); - assertThat(messagesService.recommendMessage(mid0, ugnich.getUid()), equalTo(MessagesService.RecommendStatus.Deleted)); + assertThat(messagesService.recommendMessage(mid0, ugnich.getUid()), + equalTo(MessagesService.RecommendStatus.Deleted)); assertThat(messagesService.getMessage(mid0).get().getLikes(), equalTo(0)); assertThat(messagesService.getAll(ugnich.getUid(), 0).get(0), equalTo(mid3)); Tag yoTag = tagService.getTag("yoyo", true); @@ -336,8 +336,8 @@ public class ServerTests { List subscribers = subscriptionService.getSubscribedUsers(ugnich.getUid(), msg); telegramService.createTelegramUser(12345, "freefd"); - String loginhash = jdbcTemplate.queryForObject("SELECT loginhash FROM telegram where tg_id=?", - String.class, 12345); + String loginhash = jdbcTemplate.queryForObject("SELECT loginhash FROM telegram where tg_id=?", String.class, + 12345); crosspostService.setTelegramUser(loginhash, freefd.getUid()); List telegramSubscribers = telegramService.getTelegramIdentifiers(subscribers); @@ -415,10 +415,9 @@ public class ServerTests { subscriptionService.subscribeMessage(msg, user); subscriptionService.subscribeMessage(msg, ugnich); int reply_id = messagesService.createReply(msg.getMid(), 0, ugnich, "comment", null); - assertEquals(1, subscriptionService.getUsersSubscribedToComments(msg, - messagesService.getReply(msg.getMid(), reply_id)).size()); - assertThat(messagesService.getDiscussions(ugnich.getUid(), 0L).get(0), - equalTo(msg.getMid())); + assertEquals(1, subscriptionService + .getUsersSubscribedToComments(msg, messagesService.getReply(msg.getMid(), reply_id)).size()); + assertThat(messagesService.getDiscussions(ugnich.getUid(), 0L).get(0), equalTo(msg.getMid())); messagesService.deleteMessage(user.getUid(), mid); messagesService.deleteMessage(user.getUid(), mid2); String htmlTagName = ">_<"; @@ -426,7 +425,7 @@ public class ServerTests { TagStats htmlTagStats = new TagStats(); htmlTagStats.setTag(htmlTag); String dbTagName = jdbcTemplate.queryForObject("select name from tags where name=?", String.class, htmlTagName); - assertEquals( dbTagName, htmlTag.getName()); + assertEquals(dbTagName, htmlTag.getName()); int mid4 = messagesService.createMessage(user.getUid(), "yoyoyo", null, null); Message msg4 = messagesService.getMessage(mid4).get(); assertEquals(StringUtils.EMPTY, MessageUtils.getTagsString(msg4)); @@ -446,17 +445,19 @@ public class ServerTests { Message msg4 = messagesService.getMessage(mid).get(); assertThat(msg4.getLikes(), equalTo(1)); - assertEquals(2, msg4.getReactions().stream().filter(r -> r.getId() == 2) - .findFirst().orElseThrow(IllegalStateException::new).getCount()); - assertEquals(1, msg4.getReactions().stream().filter(r -> r.getId() == 3) - .findFirst().orElseThrow(IllegalStateException::new).getCount()); + assertEquals(2, msg4.getReactions().stream().filter(r -> r.getId() == 2).findFirst() + .orElseThrow(IllegalStateException::new).getCount()); + assertEquals(1, msg4.getReactions().stream().filter(r -> r.getId() == 3).findFirst() + .orElseThrow(IllegalStateException::new).getCount()); } @Test public void lastJidShouldNotBeDeleted() { 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); + 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)); } @@ -479,12 +480,12 @@ public class ServerTests { public void messageUpdatedTimeShouldMatchLastReplyTime() throws InterruptedException { 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(); + Instant ts = jdbcTemplate + .queryForObject("SELECT updated FROM messages WHERE message_id=?", Timestamp.class, mid).toInstant(); Thread.sleep(1000); int rid = messagesService.createReply(mid, 0, ugnich, "people", null); - Instant rts = jdbcTemplate.queryForObject("SELECT updated FROM messages WHERE message_id=?", - Timestamp.class, mid).toInstant(); + Instant rts = jdbcTemplate + .queryForObject("SELECT updated FROM messages WHERE message_id=?", Timestamp.class, mid).toInstant(); assertThat(rts, greaterThan(ts)); Message msg = messagesService.getReply(mid, rid); assertThat(rts, equalTo(msg.getCreated())); @@ -493,35 +494,28 @@ public class ServerTests { @Test public void testAllUnAuthorized() throws Exception { - mockMvc.perform(get("/api/")) - .andExpect(status().isMovedPermanently()); + mockMvc.perform(get("/api/")).andExpect(status().isMovedPermanently()); - mockMvc.perform(get("/api/auth")) - .andExpect(status().isUnauthorized()) + mockMvc.perform(get("/api/auth")).andExpect(status().isUnauthorized()) .andExpect(header().exists("WwW-Authenticate")); - mockMvc.perform(get("/api/home")) - .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/home")).andExpect(status().isUnauthorized()); - mockMvc.perform(get("/api/messages/recommended")) - .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/messages/recommended")).andExpect(status().isUnauthorized()); - mockMvc.perform(get("/api/messages/set_privacy")) - .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/messages/set_privacy")).andExpect(status().isUnauthorized()); } @Test public void homeTestWithMessages() throws Exception { String msgText = "Привет, я - Угнич"; - CommandResult result = commandsManager.processCommand(ugnich, msgText, URI.create("https://static.juick.com/settings/facebook.png")); + CommandResult result = commandsManager.processCommand(ugnich, msgText, + URI.create("https://static.juick.com/settings/facebook.png")); int mid = result.getNewMessage().get().getMid(); Message msg = messagesService.getMessage(mid).get(); tagService.createTag("тест"); String hash = DigestUtils.md5DigestAsHex(IOUtils.toByteArray(defaultAvatar.getInputStream())); - mockMvc.perform( - get("/api/home") - .with(httpBasic(ugnichName, ugnichPassword))) - .andExpect(status().isOk()) + mockMvc.perform(get("/api/home").with(httpBasic(ugnichName, ugnichPassword))).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$[0].mid", is(msg.getMid()))) .andExpect(jsonPath("$[0].timestamp", @@ -531,51 +525,34 @@ public class ServerTests { is(String.format("https://i.juick.com/p/%d.png", msg.getMid())))) .andExpect(jsonPath("$[0].attachment.small.url", is(String.format("https://i.juick.com/photos-512/%d.png", msg.getMid())))) - .andExpect(jsonPath("$[0].user.avatar", - is(String.format("http://localhost:8080/av-96-%s.png", hash)))); + .andExpect(jsonPath("$[0].user.avatar", is(String.format("http://localhost:8080/av-96-%s.png", hash)))); } @Test public void homeTestWithMessagesAndRememberMe() throws Exception { String ugnichHash = userService.getHashByUID(ugnich.getUid()); - mockMvc.perform( - get("/api/home") - .with(httpBasic(ugnichName, ugnichPassword))) - .andExpect(status().isOk()); + mockMvc.perform(get("/api/home").with(httpBasic(ugnichName, ugnichPassword))).andExpect(status().isOk()); - mockMvc.perform(get("/api/home") - .param("hash", ugnichHash)) - .andExpect(status().isOk()); + mockMvc.perform(get("/api/home").param("hash", ugnichHash)).andExpect(status().isOk()); - mockMvc.perform(get("/api/home") - .header("Authorization", String.format("Juick %s", ugnichHash))) + mockMvc.perform(get("/api/home").header("Authorization", String.format("Juick %s", ugnichHash))) .andExpect(status().isOk()); } @Test public void homeTestWithMessagesAndSimpleCors() throws Exception { mockMvc.perform( - get("/api/home") - .with(httpBasic(ugnichName, ugnichPassword)) - .header("Origin", "http://api.example.net")) - .andExpect(status().isOk()) - .andExpect(header().string("Access-Control-Allow-Origin", "*")); - mockMvc.perform( - get("/u/ugnich") - .header("Origin", "http://api.example.net")) - .andExpect(status().isOk()) + get("/api/home").with(httpBasic(ugnichName, ugnichPassword)).header("Origin", "http://api.example.net")) + .andExpect(status().isOk()).andExpect(header().string("Access-Control-Allow-Origin", "*")); + mockMvc.perform(get("/u/ugnich").header("Origin", "http://api.example.net")).andExpect(status().isOk()) .andExpect(header().string("Access-Control-Allow-Origin", "*")); } @Test public void homeTestWithPreflightCors() throws Exception { - mockMvc.perform( - options("/api/home") - .with(httpBasic(ugnichName, ugnichPassword)) - .header("Origin", "http://api.example.net") - .header("Access-Control-Request-Method", "POST") - .header("Access-Control-Request-Headers", "X-PINGOTHER, Content-Type")) - .andExpect(status().isOk()) + mockMvc.perform(options("/api/home").with(httpBasic(ugnichName, ugnichPassword)) + .header("Origin", "http://api.example.net").header("Access-Control-Request-Method", "POST") + .header("Access-Control-Request-Headers", "X-PINGOTHER, Content-Type")).andExpect(status().isOk()) .andExpect(header().string("Access-Control-Allow-Origin", "*")) .andExpect(header().string("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE")) .andExpect(header().string("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type")); @@ -584,16 +561,10 @@ public class ServerTests { @Test public void anonymousApis() throws Exception { + mockMvc.perform(get("/api/messages")).andExpect(status().isOk()); - mockMvc.perform(get("/api/messages")) - .andExpect(status().isOk()); - - mockMvc.perform(get("/api/users") - .param("uname", "ugnich") - .param("uname", "freefd")) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$", hasSize(2))); + mockMvc.perform(get("/api/users").param("uname", "ugnich").param("uname", "freefd")).andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$", hasSize(2))); } @Test @@ -608,19 +579,13 @@ public class ServerTests { messagesService.likeMessage(mid, freefdId, 2); messagesService.likeMessage(mid, freefdId, 3); - mockMvc.perform(get("/api/messages?" + "hash=" + userIdHash)) - .andDo(print()) - .andExpect(status().isOk()) + mockMvc.perform(get("/api/messages?" + "hash=" + userIdHash)).andDo(print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect((jsonPath("$[0].reactions[?(@.id == 3)].count", - is(Collections.singletonList(1))))) - .andExpect((jsonPath("$[0].reactions[?(@.id == 2)].count", - is(Collections.singletonList(2))))); + .andExpect((jsonPath("$[0].reactions[?(@.id == 3)].count", is(Collections.singletonList(1))))) + .andExpect((jsonPath("$[0].reactions[?(@.id == 2)].count", is(Collections.singletonList(2))))); - mockMvc.perform(get("/api/reactions?hash=" + userIdHash)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$.length()", is(7))); + mockMvc.perform(get("/api/reactions?hash=" + userIdHash)).andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$.length()", is(7))); } @Test @@ -629,50 +594,43 @@ public class ServerTests { Tag yo = tagService.getTag("yo", true); messagesService.createMessage(ugnich.getUid(), "text", null, Arrays.asList(yo, weather)); messagesService.createMessage(freefd.getUid(), "text2", null, Collections.singletonList(yo)); - MvcResult result = mockMvc.perform(get("/api/tags")) - .andExpect(status().isOk()) - .andReturn(); + MvcResult result = mockMvc.perform(get("/api/tags")).andExpect(status().isOk()).andReturn(); List tagsFromApi = jsonMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<>() { }); TagStats yoStats = tagsFromApi.stream().filter(t -> t.getTag().getName().equals("yo")).findFirst().get(); assertThat(yoStats.getUsageCount(), is(2)); - MvcResult result2 = mockMvc.perform(get("/api/tags") - .param("user_id", String.valueOf(ugnich.getUid()))) - .andExpect(status().isOk()) - .andReturn(); + MvcResult result2 = mockMvc.perform(get("/api/tags").param("user_id", String.valueOf(ugnich.getUid()))) + .andExpect(status().isOk()).andReturn(); List ugnichTagsFromApi = jsonMapper.readValue(result2.getResponse().getContentAsString(), new TypeReference<>() { }); - TagStats yoUgnichStats = ugnichTagsFromApi.stream().filter(t -> t.getTag().getName().equals("yo")).findFirst().get(); + TagStats yoUgnichStats = ugnichTagsFromApi.stream().filter(t -> t.getTag().getName().equals("yo")).findFirst() + .get(); assertThat(yoUgnichStats.getUsageCount(), is(1)); } @Test public void postWithReferer() throws Exception { - mockMvc.perform(post("/api/post") - .param("body", "yo") - .with(httpBasic(ugnichName, ugnichPassword))) + mockMvc.perform(post("/api/post").param("body", "yo").with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().isOk()); } @Test public void threadWithEphemeralNumberShouldReturn404() throws Exception { - mockMvc.perform(get("/api/thread").param("mid", "999999999") - .with(httpBasic(ugnichName, ugnichPassword))).andExpect(status().is4xxClientError()); + mockMvc.perform(get("/api/thread").param("mid", "999999999").with(httpBasic(ugnichName, ugnichPassword))) + .andExpect(status().is4xxClientError()); } @Test public void performRequestsWithIssuedToken() throws Exception { String ugnichHash = userService.getHashByUID(ugnich.getUid()); mockMvc.perform(get("/api/home")).andExpect(status().isUnauthorized()); - mockMvc.perform(get("/api/auth")) - .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/auth")).andExpect(status().isUnauthorized()); mockMvc.perform(get("/api/auth").with(httpBasic(ugnichName, "wrongpassword"))) .andExpect(status().isUnauthorized()); MvcResult result = mockMvc.perform(get("/api/auth").with(httpBasic(ugnichName, ugnichPassword))) - .andExpect(status().isOk()) - .andReturn(); + .andExpect(status().isOk()).andReturn(); String authHash = result.getResponse().getContentAsString(); assertThat(authHash, equalTo(ugnichHash)); mockMvc.perform(get("/api/home").param("hash", ugnichHash)).andExpect(status().isOk()); @@ -686,14 +644,10 @@ public class ServerTests { .contentType(MediaType.APPLICATION_JSON) .content(jsonMapper.writeValueAsBytes(Collections.singletonList(registration)))) .andExpect(status().isOk()); - MvcResult result = mockMvc.perform(get("/api/notifications") - .param("uid", String.valueOf(ugnich.getUid())) - .with(httpBasic(juickName, juickPassword))) - .andExpect(status().isOk()) - .andReturn(); - List users = jsonMapper.readValue(result.getResponse().getContentAsString(), - new TypeReference<>() { - }); + MvcResult result = mockMvc.perform(get("/api/notifications").param("uid", String.valueOf(ugnich.getUid())) + .with(httpBasic(juickName, juickPassword))).andExpect(status().isOk()).andReturn(); + List users = jsonMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<>() { + }); assertThat(users.size(), is(1)); assertThat(users.get(0).getTokens().size(), is(1)); assertThat(users.get(0).getTokens().get(0).getToken(), equalTo(token)); @@ -710,11 +664,11 @@ public class ServerTests { public void notificationsTokensTest() throws Exception { List tokens = Collections.singletonList(new ExternalToken(null, "gcm", "123456", null)); mockMvc.perform(delete("/api/notifications").with(httpBasic(ugnichName, ugnichPassword)) - .contentType(MediaType.APPLICATION_JSON) - .content(jsonMapper.writeValueAsBytes(tokens))).andExpect(status().isForbidden()); + .contentType(MediaType.APPLICATION_JSON).content(jsonMapper.writeValueAsBytes(tokens))) + .andExpect(status().isForbidden()); mockMvc.perform(delete("/api/notifications").with(httpBasic(juickName, juickPassword)) - .contentType(MediaType.APPLICATION_JSON) - .content(jsonMapper.writeValueAsBytes(tokens))).andExpect(status().isOk()); + .contentType(MediaType.APPLICATION_JSON).content(jsonMapper.writeValueAsBytes(tokens))) + .andExpect(status().isOk()); } @Test @@ -722,9 +676,11 @@ public class ServerTests { CommandResult result = commandsManager.processCommand(ugnich, "yo", emptyUri); String stringValueOfMid = String.valueOf(result.getNewMessage().get().getMid()); mockMvc.perform(get("/api/notifications").with(httpBasic(juickName, juickPassword)) - .param("mid", stringValueOfMid).param("uid", String.valueOf(ugnich.getUid()))).andExpect(status().isOk()); - mockMvc.perform(get("/api/notifications") - .param("mid", stringValueOfMid).param("uid", String.valueOf(ugnich.getUid()))).andExpect(status().isUnauthorized()); + .param("mid", stringValueOfMid).param("uid", String.valueOf(ugnich.getUid()))) + .andExpect(status().isOk()); + mockMvc.perform( + get("/api/notifications").param("mid", stringValueOfMid).param("uid", String.valueOf(ugnich.getUid()))) + .andExpect(status().isUnauthorized()); } @Test @@ -765,9 +721,7 @@ public class ServerTests { @Test public void lastMessagesTest() throws Exception { - mockMvc.perform( - get("/rss/")) - .andExpect(status().isOk()) + mockMvc.perform(get("/rss/")).andExpect(status().isOk()) .andExpect(content().contentType("application/rss+xml;charset=UTF-8")) .andExpect(xpath("/rss/channel/description").string("The latest messages at Juick")); } @@ -776,142 +730,130 @@ public class ServerTests { public void botCommandsTests() throws Exception { assertThat(commandsManager.processCommand(AnonymousUser.INSTANCE, "PING", emptyUri).getText(), is("PONG")); // subscription commands have two lines, others have 1 - assertThat(commandsManager.processCommand(AnonymousUser.INSTANCE, "help", emptyUri).getText().split("\n").length, is(32)); + assertThat( + commandsManager.processCommand(AnonymousUser.INSTANCE, "help", emptyUri).getText().split("\n").length, + is(32)); } @Test public void protocolTests() throws Exception { 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(); + Message msg = commandsManager + .processCommand(user, "*yo yoyo", URI.create("https://static.juick.com/settings/facebook.png")) + .getNewMessage().get(); assertThat(msg.getAttachmentType(), is("png")); - Message msgreply = commandsManager.processCommand(user, "#" + msg.getMid() + " yyy", HttpUtils.downloadImage(URI.create("https://static.juick.com/settings/xmpp.png").toURL(), tmpDir)).getNewMessage().get(); + Message msgreply = commandsManager + .processCommand(user, "#" + msg.getMid() + " yyy", HttpUtils + .downloadImage(URI.create("https://static.juick.com/settings/xmpp.png").toURL(), tmpDir)) + .getNewMessage().get(); assertThat(msgreply.getAttachmentType(), equalTo("png")); - assertEquals( "yoyo", - messagesService.getMessage(msg.getMid()).get().getText()); - assertEquals( "yo", - tagService.getMessageTags(msg.getMid()).get(0).getTag().getName()); - CommandResult yoyoMsg = commandsManager.processCommand(user, "*yo", URI.create("https://static.juick.com/settings/facebook.png")); + assertEquals("yoyo", messagesService.getMessage(msg.getMid()).get().getText()); + assertEquals("yo", tagService.getMessageTags(msg.getMid()).get(0).getTag().getName()); + CommandResult yoyoMsg = commandsManager.processCommand(user, "*yo", + URI.create("https://static.juick.com/settings/facebook.png")); assertThat(yoyoMsg.getNewMessage().isPresent(), is(true)); assertThat(yoyoMsg.getNewMessage().get().getTags().stream().findFirst().get(), is(yo)); Message msg2 = yoyoMsg.getNewMessage().get(); int mid = msg2.getMid(); - Timestamp last = jdbcTemplate.queryForObject("SELECT lastmessage FROM users WHERE id=?", Timestamp.class, user.getUid()); + Timestamp last = jdbcTemplate.queryForObject("SELECT lastmessage FROM users WHERE id=?", Timestamp.class, + user.getUid()); assertThat(last.toInstant(), equalTo(yoyoMsg.getNewMessage().get().getCreated())); assertEquals(true, commandsManager.processCommand(user, String.format("#%d", mid), emptyUri).getText().startsWith("@me")); 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("Subscribed", - commandsManager.processCommand(readerUser, "S #" + mid, emptyUri).getText()); - assertEquals( "Message is added to your recommendations", + 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("Subscribed", commandsManager.processCommand(readerUser, "S #" + mid, emptyUri).getText()); + assertEquals("Message is added to your recommendations", commandsManager.processCommand(readerUser, "! #" + mid, emptyUri).getText()); int rid = messagesService.createReply(mid, 0, user, "comment", null); - assertEquals(1, - subscriptionService.getUsersSubscribedToComments( - messagesService.getMessage(mid).get(), - messagesService.getReply(mid, rid)).size()); + assertEquals(1, subscriptionService + .getUsersSubscribedToComments(messagesService.getMessage(mid).get(), messagesService.getReply(mid, rid)) + .size()); privacyQueriesService.blacklistUser(user, readerUser); - assertEquals(0, - subscriptionService.getUsersSubscribedToComments( - messagesService.getMessage(mid).get(), - messagesService.getReply(mid, rid)).size()); - assertEquals(1, - subscriptionService.getUsersSubscribedToComments( - messagesService.getMessage(mid).get(), - messagesService.getReply(mid, rid), true).size()); + assertEquals(0, subscriptionService + .getUsersSubscribedToComments(messagesService.getMessage(mid).get(), messagesService.getReply(mid, rid)) + .size()); + assertEquals(1, subscriptionService.getUsersSubscribedToComments(messagesService.getMessage(mid).get(), + messagesService.getReply(mid, rid), true).size()); assertEquals("Subscribed to @" + user.getName(), - commandsManager.processCommand(readerUser, "S @" + user.getName(), emptyUri) - .getText()); + commandsManager.processCommand(readerUser, "S @" + user.getName(), emptyUri).getText()); List friends = userService.getUserFriends(readerUser.getUid()); - assertEquals(2, - friends.size()); - assertEquals(1, - 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 " - + "https://juick.com/m/" + mid + "#3"; - assertEquals(expectedSecondReply, - commandsManager.processCommand(user, "#" + mid + " yoyo", URI.create("https://static.juick.com/settings/facebook.png")).getText()); - assertEquals(expectedThirdReply, - commandsManager.processCommand(user, " \t\n #" + mid + "/2 ", - URI.create("https://static.juick.com/settings/facebook.png")).getText()); + assertEquals(2, friends.size()); + assertEquals(1, 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 " + "https://juick.com/m/" + mid + "#3"; + assertEquals(expectedSecondReply, commandsManager + .processCommand(user, "#" + mid + " yoyo", URI.create("https://static.juick.com/settings/facebook.png")) + .getText()); + assertEquals(expectedThirdReply, commandsManager.processCommand(user, " \t\n #" + mid + "/2 ", + URI.create("https://static.juick.com/settings/facebook.png")).getText()); Message reply = messagesService.getReplies(user, mid).stream().filter(m -> m.getRid() == 3).findFirst() .orElse(new Message()); - Timestamp lastreply = jdbcTemplate.queryForObject("SELECT lastmessage FROM users WHERE id=?", Timestamp.class, user.getUid()); + Timestamp lastreply = jdbcTemplate.queryForObject("SELECT lastmessage FROM users WHERE id=?", Timestamp.class, + user.getUid()); assertThat(lastreply.toInstant(), equalTo(reply.getCreated())); assertEquals(2, reply.getReplyto()); - assertThat(commandsManager.processCommand(readerUser, "#" + mid + " *yo *there", emptyUri) - .getText(), startsWith("Reply posted")); + assertThat(commandsManager.processCommand(readerUser, "#" + mid + " *yo *there", emptyUri).getText(), + startsWith("Reply posted")); assertEquals("Tags are updated", commandsManager.processCommand(user, "#" + mid + " *there", emptyUri).getText()); - assertEquals(2, - tagService.getMessageTags(mid).size()); + assertEquals(2, tagService.getMessageTags(mid).size()); assertThat(messagesService.getMessage(mid).get().getTags().size(), is(2)); assertEquals("Tag added to your blacklist", commandsManager.processCommand(readerUser, "BL *there", emptyUri).getText()); - assertEquals(0, - subscriptionService.getSubscribedUsers(user.getUid(), msg2).size()); + assertEquals(0, subscriptionService.getSubscribedUsers(user.getUid(), msg2).size()); assertEquals("Tags are updated", commandsManager.processCommand(user, "#" + mid + " *there", emptyUri).getText()); assertEquals(1, tagService.getMessageTags(mid).size()); User taggerUser = userService.createUser("dummyTagger", "dummySecret").orElseThrow(IllegalStateException::new); - assertEquals("Subscribed", - commandsManager.processCommand(taggerUser, "S *yo", emptyUri).getText()); - assertEquals(2, - subscriptionService.getSubscribedUsers(user.getUid(), msg2).size()); - assertEquals("Unsubscribed from yo", - commandsManager.processCommand(taggerUser, "U *yo", emptyUri).getText()); - assertEquals(1, - subscriptionService.getSubscribedUsers(user.getUid(), msg2).size()); - assertEquals(1, - userService.getUserReaders(user.getUid()).size()); + assertEquals("Subscribed", commandsManager.processCommand(taggerUser, "S *yo", emptyUri).getText()); + assertEquals(2, subscriptionService.getSubscribedUsers(user.getUid(), msg2).size()); + assertEquals("Unsubscribed from yo", commandsManager.processCommand(taggerUser, "U *yo", emptyUri).getText()); + assertEquals(1, subscriptionService.getSubscribedUsers(user.getUid(), msg2).size()); + assertEquals(1, userService.getUserReaders(user.getUid()).size()); String readerFeed = commandsManager.processCommand(readerUser, "#", emptyUri).getText(); assertThat(readerFeed.startsWith("Your feed"), is(true)); assertEquals("Unsubscribed from @" + user.getName(), - commandsManager.processCommand(readerUser, "U @" + user.getName(), emptyUri) - .getText()); - assertEquals(0, - userService.getUserReaders(user.getUid()).size()); - assertEquals(1, - userService.getUserFriends(user.getUid()).size()); + commandsManager.processCommand(readerUser, "U @" + user.getName(), emptyUri).getText()); + assertEquals(0, userService.getUserReaders(user.getUid()).size()); + assertEquals(1, userService.getUserFriends(user.getUid()).size()); assertEquals("Unsubscribed from #" + mid, commandsManager.processCommand(readerUser, "u #" + mid, emptyUri).getText()); - assertEquals(0, - subscriptionService.getUsersSubscribedToComments(messagesService.getMessage(mid).get(), - messagesService.getReply(mid, rid)).size()); + assertEquals(0, subscriptionService + .getUsersSubscribedToComments(messagesService.getMessage(mid).get(), messagesService.getReply(mid, rid)) + .size()); assertNotEquals("should NOT be deleted", String.format("Message %s deleted", mid), commandsManager.processCommand(readerUser, "D #" + mid, emptyUri).getText()); - assertEquals("Message deleted", - commandsManager.processCommand(user, "D #" + mid, emptyUri).getText()); - assertEquals("Message not found", - commandsManager.processCommand(user, "#" + mid, emptyUri).getText()); - - String expectedCodeMessage = "some smelly code goes here\n" + - "> void main(void** args) {\n" + - "> }"; + assertEquals("Message deleted", commandsManager.processCommand(user, "D #" + mid, emptyUri).getText()); + assertEquals("Message not found", commandsManager.processCommand(user, "#" + mid, emptyUri).getText()); + + String expectedCodeMessage = "some smelly code goes here\n" + "> void main(void** args) {\n" + "> }"; String codeAndTags = "*code\n" + expectedCodeMessage; Message codeAndTagsMessage = commandsManager.processCommand(user, codeAndTags, emptyUri).getNewMessage().get(); Set codeAndTagsTags = codeAndTagsMessage.getTags(); - assertEquals(1, - codeAndTagsTags.size()); - assertEquals("code", - codeAndTagsTags.stream().findFirst().get().getName()); - assertEquals(expectedCodeMessage, - codeAndTagsMessage.getText()); + assertEquals(1, codeAndTagsTags.size()); + assertEquals("code", codeAndTagsTags.stream().findFirst().get().getName()); + assertEquals(expectedCodeMessage, codeAndTagsMessage.getText()); CommandResult result = commandsManager.processCommand(user, "*one *two *three *four *five *six test", emptyUri); assertThat(result.getNewMessage(), is(Optional.empty())); assertThat(result.getText(), is("Sorry, 5 tags maximum.")); - result = commandsManager.processCommand(user, String.format("#%d *one *two *three *four *five *six", msg.getMid()), emptyUri); + result = commandsManager.processCommand(user, + String.format("#%d *one *two *three *four *five *six", msg.getMid()), emptyUri); assertThat(result.getNewMessage(), is(Optional.empty())); assertThat(result.getText(), is("Tags are NOT updated (5 tags maximum?)")); - result = commandsManager.processCommand(user, "I'm very smart to post my login url there" + - "", emptyUri); + result = commandsManager.processCommand(user, + "I'm very smart to post my login url there" + "", + emptyUri); assertThat(result.getNewMessage().isPresent(), is(true)); assertFalse(result.getNewMessage().get().getText().contains("VTYZkKV8FWkmu6g1")); - result = commandsManager.processCommand(user, "*корм *juick_ppl *рационализм *? *мюсли а сколько микроморт в дневной порции сверхмюслей?", emptyUri); + result = commandsManager.processCommand(user, + "*корм *juick_ppl *рационализм *? *мюсли а сколько микроморт в дневной порции сверхмюслей?", emptyUri); assertThat(result.getNewMessage().isPresent(), is(true)); String tags = "*Juick *Google *Google Play"; String data = "Вчера отправлял *NSFW постинг в топ :)"; @@ -933,50 +875,33 @@ public class ServerTests { public void mailParserTest() throws Exception { emailService.addEmail(ugnich.getUid(), "ugnich@example.com"); int mid = messagesService.createMessage(ugnich.getUid(), "text", StringUtils.EMPTY, Collections.emptyList()); - String mail = String.format("MIME-Version: 1.0\n" + - "Received: by 10.176.0.242 with HTTP; Fri, 16 Mar 2018 05:31:50 -0700 (PDT)\n" + - "In-Reply-To: <%d.0@juick.com>\n" + - "References: <%d.0@juick.com>\n" + - "Date: Fri, 16 Mar 2018 15:31:50 +0300\n" + - "Delivered-To: ugnich@example.com\n" + - "Message-ID: \n" + - "Subject: Re: New reply to TJ\n" + - "From: Ugnich \n" + - "To: Juick \n" + - "Content-Type: multipart/alternative; boundary=\"001a11454886e42be5056786ca70\"\n" + - "\n" + - "--001a11454886e42be5056786ca70\n" + - "Content-Type: text/plain; charset=\"UTF-8\"\n" + - "\n" + - "s2313334\n" + - "\n" + - "--001a11454886e42be5056786ca70\n" + - "Content-Type: text/html; charset=\"UTF-8\"\n" + - "\n" + - "
s2313334
\n" + - "\n" + - "--001a11454886e42be5056786ca70--", mid, mid); + String mail = String.format( + "MIME-Version: 1.0\n" + "Received: by 10.176.0.242 with HTTP; Fri, 16 Mar 2018 05:31:50 -0700 (PDT)\n" + + "In-Reply-To: <%d.0@juick.com>\n" + "References: <%d.0@juick.com>\n" + + "Date: Fri, 16 Mar 2018 15:31:50 +0300\n" + "Delivered-To: ugnich@example.com\n" + + "Message-ID: \n" + + "Subject: Re: New reply to TJ\n" + "From: Ugnich \n" + + "To: Juick \n" + + "Content-Type: multipart/alternative; boundary=\"001a11454886e42be5056786ca70\"\n" + "\n" + + "--001a11454886e42be5056786ca70\n" + "Content-Type: text/plain; charset=\"UTF-8\"\n" + "\n" + + "s2313334\n" + "\n" + "--001a11454886e42be5056786ca70\n" + + "Content-Type: text/html; charset=\"UTF-8\"\n" + "\n" + "
s2313334
\n" + + "\n" + "--001a11454886e42be5056786ca70--", + mid, mid); mockMvc.perform(post("/api/mail").with(httpBasic(juickName, juickPassword)).content(mail)) .andExpect(status().isOk()); - String reply = "Return-Path: \n" + - "Received: from [192.168.88.140] ([91.244.168.38])\n" + - " by smtp.gmail.com with ESMTPSA id r84sm3970197lja.54.2019.06.20.08.39.54\n" + - " for \n" + - " (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);\n" + - " Thu, 20 Jun 2019 08:39:54 -0700 (PDT)\n" + - "From: Ugnich \n" + - "Content-Type: text/plain; charset=utf-8\n" + - "Content-Transfer-Encoding: base64\n" + - "Mime-Version: 1.0 (1.0)\n" + - "Date: Thu, 20 Jun 2019 18:39:54 +0300\n" + - "Subject: Re: New reply to vt\n" + - "Message-Id: <40BC3538-0A0C-4BD0-8F11-5408A85CC6EF@gmail.com>\n" + - "References: <2945559.7@juick.com>\n" + - "In-Reply-To: \n" + - "To: juick@juick.com\n" + - "X-Mailer: iPhone Mail (16F203)\n" + - "\n" + - "0J3RgyDRjdGC0L4g0L/QvtC60LAhINCU0L7Qu9Cz0L4g0LvQuCwg0YPQvNC10Y7Rh9C4IQ=="; + String reply = "Return-Path: \n" + "Received: from [192.168.88.140] ([91.244.168.38])\n" + + " by smtp.gmail.com with ESMTPSA id r84sm3970197lja.54.2019.06.20.08.39.54\n" + + " for \n" + + " (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);\n" + + " Thu, 20 Jun 2019 08:39:54 -0700 (PDT)\n" + "From: Ugnich \n" + + "Content-Type: text/plain; charset=utf-8\n" + "Content-Transfer-Encoding: base64\n" + + "Mime-Version: 1.0 (1.0)\n" + "Date: Thu, 20 Jun 2019 18:39:54 +0300\n" + + "Subject: Re: New reply to vt\n" + "Message-Id: <40BC3538-0A0C-4BD0-8F11-5408A85CC6EF@gmail.com>\n" + + "References: <2945559.7@juick.com>\n" + + "In-Reply-To: \n" + + "To: juick@juick.com\n" + "X-Mailer: iPhone Mail (16F203)\n" + "\n" + + "0J3RgyDRjdGC0L4g0L/QvtC60LAhINCU0L7Qu9Cz0L4g0LvQuCwg0YPQvNC10Y7Rh9C4IQ=="; mockMvc.perform(post("/api/mail").with(httpBasic(juickName, juickPassword)).content(reply)) .andExpect(status().isOk()); } @@ -988,15 +913,12 @@ public class ServerTests { String freefdHash = userService.getHashByUID(freefd.getUid()); int freefdMid = messagesService.createMessage(freefd.getUid(), "to be not liked", null, null); - mockMvc.perform(post("/api/like?mid=" + mid + "&hash=" + freefdHash)) - .andExpect(status().isOk()) + mockMvc.perform(post("/api/like?mid=" + mid + "&hash=" + freefdHash)).andExpect(status().isOk()) .andExpect(jsonPath("$.status", is("Message is added to your recommendations"))); - mockMvc.perform(get("/api/thread?mid=" + mid + "&hash=" + freefdHash)) - .andExpect(status().isOk()) + mockMvc.perform(get("/api/thread?mid=" + mid + "&hash=" + freefdHash)).andExpect(status().isOk()) .andExpect(jsonPath("$[0].recommendations.length()", is(1))) .andExpect(jsonPath("$[0].recommendations[0].uname", is(freefdName))); - mockMvc.perform(post("/api/like?mid=" + freefdMid + "&hash=" + freefdHash)) - .andExpect(status().isForbidden()); + mockMvc.perform(post("/api/like?mid=" + freefdMid + "&hash=" + freefdHash)).andExpect(status().isForbidden()); } @Test @@ -1010,9 +932,11 @@ public class ServerTests { Message msg4 = messagesService.getMessage(mid1).get(); assertThat(msg4.getLikes(), is(0)); - assertThat(messagesService.getMessages(AnonymousUser.INSTANCE, Collections.singletonList(mid1)).get(0).getLikes(), is(0)); - assertEquals(1, msg4.getReactions().stream().filter(r -> r.getId() == 2) - .findFirst().orElseThrow(IllegalStateException::new).getCount()); + assertThat( + messagesService.getMessages(AnonymousUser.INSTANCE, Collections.singletonList(mid1)).get(0).getLikes(), + is(0)); + assertEquals(1, msg4.getReactions().stream().filter(r -> r.getId() == 2).findFirst() + .orElseThrow(IllegalStateException::new).getCount()); mockMvc.perform(post("/api/react?mid=" + mid1 + "&hash=" + freefdHash + "&reactionId=1")) .andExpect(status().isOk()); mockMvc.perform(post("/api/react?mid=" + mid1 + "&hash=" + freefdHash + "&reactionId=1")) @@ -1029,8 +953,8 @@ public class ServerTests { subscriptionService.subscribeMessage(messagesService.getMessage(mid).get(), ugnich); messagesService.createReply(mid, 0, freefd, "new reply", null); BiFunction lastRead = (user, m) -> jdbcTemplate.queryForObject( - "SELECT last_read_rid FROM subscr_messages WHERE suser_id=? AND message_id=?", - Integer.class, user.getUid(), m); + "SELECT last_read_rid FROM subscr_messages WHERE suser_id=? AND message_id=?", Integer.class, + user.getUid(), m); assertThat(lastRead.apply(ugnich, mid), is(0)); assertThat(messagesService.getUnread(ugnich).size(), is(1)); assertThat(messagesService.getUnread(ugnich).get(0), is(mid)); @@ -1048,8 +972,8 @@ public class ServerTests { assertThat(lastRead.apply(ugnich, mid), is(freefdrid)); privacyQueriesService.blacklistUser(ugnich, freefd); int newfreefdrid = messagesService.createReply(mid, 0, freefd, "from ban", null); - serverManager.processSystemEvent(new SystemEvent(this, SystemActivity.message(juick, messagesService.getReply(mid, newfreefdrid), - Collections.emptyList()))); + serverManager.processSystemEvent(new SystemEvent(this, + SystemActivity.message(juick, messagesService.getReply(mid, newfreefdrid), Collections.emptyList()))); assertThat(userService.isReplyToBL(ugnich, messagesService.getReply(mid, newfreefdrid)), is(true)); // TODO: test event listeners correctly Thread.sleep(2000L); @@ -1057,16 +981,14 @@ public class ServerTests { privacyQueriesService.blacklistUser(ugnich, freefd); newfreefdrid = messagesService.createReply(mid, 0, freefd, "after ban", null); assertThat(lastRead.apply(ugnich, mid), lessThan(newfreefdrid)); - mockMvc.perform(get(String.format("/api/thread?mid=%d&hash=%s", mid, ugnichHash))) - .andExpect(status().isOk()); + mockMvc.perform(get(String.format("/api/thread?mid=%d&hash=%s", mid, ugnichHash))).andExpect(status().isOk()); assertThat(lastRead.apply(ugnich, mid), is(newfreefdrid)); } @Test public void feedsShouldNotContainMessagesWithBannedTags() { Tag banned = tagService.getTag("banned", true); - int mid = messagesService.createMessage(ugnich.getUid(), "yo", "jpg", - Collections.singletonList(banned)); + int mid = messagesService.createMessage(ugnich.getUid(), "yo", "jpg", Collections.singletonList(banned)); privacyQueriesService.blacklistTag(freefd, banned); assertThat(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getAll(freefd.getUid(), 0)) .stream().noneMatch(m -> m.getTags().contains(banned)), is(true)); @@ -1081,25 +1003,28 @@ public class ServerTests { .stream().noneMatch(m -> m.getTags().contains(banned)), is(true)); assertFalse(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getPopular(ugnich.getUid(), 0)) .stream().noneMatch(m -> m.getTags().contains(banned))); - assertThat(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getMyFeed(freefd.getUid(), 0, true)) - .stream().noneMatch(m -> m.getTags().contains(banned)), is(true)); + assertThat( + messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getMyFeed(freefd.getUid(), 0, true)) + .stream().noneMatch(m -> m.getTags().contains(banned)), + is(true)); User newUser1 = userService.createUser("newUser1", "12345").orElseThrow(IllegalStateException::new); - int newMid = messagesService.createMessage(newUser1.getUid(), "people", null, Collections.singletonList(banned)); + int newMid = messagesService.createMessage(newUser1.getUid(), "people", null, + Collections.singletonList(banned)); messagesService.recommendMessage(newMid, ugnich.getUid()); - assertThat(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getMyFeed(freefd.getUid(), 0, true)) - .stream().noneMatch(m -> m.getTags().contains(banned)), is(true)); + assertThat( + messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getMyFeed(freefd.getUid(), 0, true)) + .stream().noneMatch(m -> m.getTags().contains(banned)), + is(true)); tagService.updateTags(newMid, Collections.singletonList(banned)); assertThat(messagesService.getMessage(newMid).get().getTags().size(), is(0)); privacyQueriesService.blacklistUser(freefd, newUser1); - assertThat(messagesService.getMyFeed(freefd.getUid(), 0, true) - .stream().noneMatch(m -> m == newMid), is(true)); + assertThat(messagesService.getMyFeed(freefd.getUid(), 0, true).stream().noneMatch(m -> m == newMid), is(true)); } @Test public void tagsShouldBeDeserializedFromXml() throws JAXBException { XmppSessionConfiguration configuration = XmppSessionConfiguration.builder() - .extensions(Extension.of(Message.class)) - .build(); + .extensions(Extension.of(Message.class)).build(); XmppSession xmpp = new XmppSession("juick.com", configuration) { @Override public void connect(Jid from) { @@ -1114,7 +1039,8 @@ public class ServerTests { String tag = "yo"; String xml = "yoyoyopeople"; Unmarshaller unmarshaller = xmpp.createUnmarshaller(); - rocks.xmpp.core.stanza.model.Message xmppMessage = (rocks.xmpp.core.stanza.model.Message) unmarshaller.unmarshal(new StringReader(xml)); + rocks.xmpp.core.stanza.model.Message xmppMessage = (rocks.xmpp.core.stanza.model.Message) unmarshaller + .unmarshal(new StringReader(xml)); Tag xmlTag = (Tag) unmarshaller.unmarshal(new StringReader(tag)); assertThat(xmlTag.getName(), equalTo("yo")); Message juickMessage = xmppMessage.getExtension(Message.class); @@ -1126,8 +1052,7 @@ public class ServerTests { public void messageParserSerializer() throws Exception { String tagsString = "test test" + (char) 0xA0 + "2 test 3"; Set tags = MessageUtils.parseTags(tagsString); - List tagList = tags.stream().map(t -> tagService.getTag(t.getName(), true)) - .collect(Collectors.toList()); + List tagList = tags.stream().map(t -> tagService.getTag(t.getName(), true)).collect(Collectors.toList()); assertEquals("test", tagList.get(0).getName()); assertEquals("test 3", tagList.get(2).getName()); assertEquals(3, tagList.size()); @@ -1138,9 +1063,7 @@ public class ServerTests { map.add("body", "*test *test 2 *test 3 YO"); map.add("hash", userService.getHashByUID(ugnich.getUid())); - ResponseEntity result = restTemplate.postForEntity( - "/api/post", - request, CommandResult.class); + ResponseEntity result = restTemplate.postForEntity("/api/post", request, CommandResult.class); assertThat(result.getStatusCode(), is(HttpStatus.OK)); Message msg = result.getBody().getNewMessage().orElseThrow(); Instant currentDate = msg.getCreated(); @@ -1148,8 +1071,7 @@ public class ServerTests { assertEquals(DateFormattersHolder.getMessageFormatterInstance().format(currentDate), JsonPath.read(jsonMessage, "$.timestamp")); - JAXBContext context = JAXBContext - .newInstance(Message.class); + JAXBContext context = JAXBContext.newInstance(Message.class); Marshaller m = context.createMarshaller(); StringWriter sw = new StringWriter(); @@ -1163,8 +1085,7 @@ public class ServerTests { assertEquals(DateFormattersHolder.getMessageFormatterInstance().format(currentDate), attrs.getNamedItem("ts").getNodeValue()); - MvcResult apiResult = mockMvc.perform(get("/api/thread?mid=" + msg.getMid())) - .andExpect(status().isOk()) + MvcResult apiResult = mockMvc.perform(get("/api/thread?mid=" + msg.getMid())).andExpect(status().isOk()) .andReturn(); List fromApi = jsonMapper.readValue(apiResult.getResponse().getContentAsString(StandardCharsets.UTF_8), new TypeReference<>() { @@ -1174,9 +1095,7 @@ public class ServerTests { @Test public void emptyAuthenticatedPostShouldThrowBadRequest() throws Exception { - mockMvc.perform(post("/api/post") - .with(httpBasic(juickName, juickPassword))) - .andExpect(status().isBadRequest()); + mockMvc.perform(post("/api/post").with(httpBasic(juickName, juickPassword))).andExpect(status().isBadRequest()); } @Test @@ -1196,10 +1115,8 @@ public class ServerTests { commandsManager.processCommand(ugnich, "S @freefd", emptyUri); assertThat(userService.getUserReaders(ugnich.getUid()).size(), is(1)); String hash = userService.getHashByUID(ugnich.getUid()); - mockMvc.perform(get("/api/me") - .with(httpBasic(ugnichName, ugnichPassword))) - .andExpect(jsonPath("$.hash", is(hash))) - .andExpect(jsonPath("$.readers.length()", is(1))) + mockMvc.perform(get("/api/me").with(httpBasic(ugnichName, ugnichPassword))) + .andExpect(jsonPath("$.hash", is(hash))).andExpect(jsonPath("$.readers.length()", is(1))) .andExpect(jsonPath("$.read.length()", is(1))); } @@ -1210,7 +1127,8 @@ public class ServerTests { int mid = result.getNewMessage().get().getMid(); commandsManager.processCommand(freefd, String.format("#%d ugnich - dick too", mid), emptyUri); commandsManager.processCommand(juick, String.format("#%d/1 ban for a hour!", mid), emptyUri); - commandsManager.processCommand(juick, String.format("#%d freefd is here but it is hidden from you", mid), emptyUri); + commandsManager.processCommand(juick, String.format("#%d freefd is here but it is hidden from you", mid), + emptyUri); assertThat(messagesService.getMessage(mid).get().getReplies(), is(3)); Message reply = messagesService.getReply(mid, 3); assertThat(userService.isReplyToBL(ugnich, reply), is(false)); @@ -1274,7 +1192,8 @@ public class ServerTests { @Test public void JpegFromJuickUriShouldBeProcessedCorrectly() throws Exception { Path tmpFile = Paths.get(tmpDir, "2915104.jpg"); - Files.copy(Paths.get(new ClassPathResource("2915104.jpg").getURI()), tmpFile, StandardCopyOption.REPLACE_EXISTING); + Files.copy(Paths.get(new ClassPathResource("2915104.jpg").getURI()), tmpFile, + StandardCopyOption.REPLACE_EXISTING); assertThat(tmpFile.toFile().exists(), is(true)); CommandResult postJpgiPhone = commandsManager.processCommand(ugnich, "YO", URI.create("juick://2915104.jpg")); assertThat(postJpgiPhone.getNewMessage().isPresent(), is(true)); @@ -1305,7 +1224,8 @@ public class ServerTests { CommandResult postJpgCmyk = commandsManager.processCommand(ugnich, "YO", pngOutput.toUri()); assertThat(postJpgCmyk.getNewMessage().isPresent(), is(true)); assertThat(postJpgCmyk.getNewMessage().get().getAttachmentType(), is("jpg")); - CommandResult replyJpgCmyk = commandsManager.processCommand(ugnich, String.format("#%d YO", postJpgCmyk.getNewMessage().get().getMid()), pngOutput.toUri()); + CommandResult replyJpgCmyk = commandsManager.processCommand(ugnich, + String.format("#%d YO", postJpgCmyk.getNewMessage().get().getMid()), pngOutput.toUri()); assertThat(replyJpgCmyk.getNewMessage().isPresent(), is(true)); assertThat(replyJpgCmyk.getNewMessage().get().getAttachmentType(), is("jpg")); } @@ -1317,41 +1237,43 @@ public class ServerTests { @Test public void messageEditingSpec() throws Exception { - MvcResult result = mockMvc.perform(post("/api/post").with(httpBasic(ugnichName, ugnichPassword)) - .param("body", "YO")).andExpect(status().is2xxSuccessful()).andReturn(); + MvcResult result = mockMvc + .perform(post("/api/post").with(httpBasic(ugnichName, ugnichPassword)).param("body", "YO")) + .andExpect(status().is2xxSuccessful()).andReturn(); Message original = jsonMapper.readValue(result.getResponse().getContentAsString(), CommandResult.class) .getNewMessage().get(); assertThat(original.getText(), equalTo("YO")); assertThat(original.getUpdatedAt(), equalTo(original.getCreated())); // to have updated_at greater than ts Thread.sleep(1000); - result = mockMvc.perform(post("/api/update").with(httpBasic(ugnichName, ugnichPassword)) - .param("mid", String.valueOf(original.getMid())) - .param("body", "PEOPLE")).andExpect(status().is2xxSuccessful()).andReturn(); + result = mockMvc + .perform(post("/api/update").with(httpBasic(ugnichName, ugnichPassword)) + .param("mid", String.valueOf(original.getMid())).param("body", "PEOPLE")) + .andExpect(status().is2xxSuccessful()).andReturn(); Message edited = jsonMapper.readValue(result.getResponse().getContentAsString(), CommandResult.class) .getNewMessage().get(); assertThat(edited.getText(), equalTo("PEOPLE")); assertThat(edited.getUpdatedAt(), greaterThan(edited.getCreated())); - Mockito.verify(activityListener, Mockito.times(1)) - .onApplicationEvent(updateEventCaptor.capture()); + Mockito.verify(activityListener, Mockito.times(1)).onApplicationEvent(updateEventCaptor.capture()); UpdateEvent updateEvent = updateEventCaptor.getValue(); assertThat(updateEvent.getUser(), is(ugnich)); assertThat(activityPubManager.messageUri(original.getMid(), 0), is(updateEvent.getMessageUri())); mockMvc.perform(post("/api/update").with(httpBasic(freefdName, freefdPassword)) - .param("mid", String.valueOf(original.getMid())) - .param("body", "PEOPLE")).andExpect(status().is(403)); - result = mockMvc.perform(post("/api/comment").with(httpBasic(freefdName, freefdPassword)) - .param("mid", String.valueOf(original.getMid())) - .param("body", "HEY")).andExpect(status().is2xxSuccessful()).andReturn(); + .param("mid", String.valueOf(original.getMid())).param("body", "PEOPLE")).andExpect(status().is(403)); + result = mockMvc + .perform(post("/api/comment").with(httpBasic(freefdName, freefdPassword)) + .param("mid", String.valueOf(original.getMid())).param("body", "HEY")) + .andExpect(status().is2xxSuccessful()).andReturn(); CommandResult comment = jsonMapper.readValue(result.getResponse().getContentAsString(), CommandResult.class); assertThat(comment.getNewMessage().get().getText(), is("HEY")); assertThat(comment.getNewMessage().get().getUpdatedAt(), is(comment.getNewMessage().get().getCreated())); // to have updated_at greater than ts Thread.sleep(1000); - result = mockMvc.perform(post("/api/update").with(httpBasic(freefdName, freefdPassword)) - .param("mid", String.valueOf(comment.getNewMessage().get().getMid())) - .param("rid", String.valueOf(comment.getNewMessage().get().getRid())) - .param("body", "HEY, JOE")).andExpect(status().is2xxSuccessful()).andReturn(); + result = mockMvc + .perform(post("/api/update").with(httpBasic(freefdName, freefdPassword)) + .param("mid", String.valueOf(comment.getNewMessage().get().getMid())) + .param("rid", String.valueOf(comment.getNewMessage().get().getRid())).param("body", "HEY, JOE")) + .andExpect(status().is2xxSuccessful()).andReturn(); Message editedComment = jsonMapper.readValue(result.getResponse().getContentAsString(), CommandResult.class) .getNewMessage().get(); assertThat(editedComment.getText(), is("HEY, JOE")); @@ -1363,16 +1285,19 @@ public class ServerTests { public void subscribersToRecommendations() { 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 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(poster.getUid(), "YO", null, Collections.singletonList(sampleTag)); + 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(recommender.getUid(), messagesService.getMessage(posterMid).get()); + BiFunction> subscribers = (recommId, msg) -> subscriptionService + .getUsersSubscribedToUserRecommendations(recommId, msg); + List recommendSubscribers = subscribers.apply(recommender.getUid(), + messagesService.getMessage(posterMid).get()); assertThat(recommendSubscribers.size(), is(1)); assertThat(recommendSubscribers.get(0).getUid(), is(reader.getUid())); privacyQueriesService.blacklistUser(reader, poster); @@ -1384,7 +1309,8 @@ public class ServerTests { tagService.blacklistTag(reader, sampleTag); 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()); + List lateRecommendSubscribers = subscribers.apply(recommender.getUid(), + messagesService.getMessage(posterMid).get()); assertThat(lateRecommendSubscribers.size(), is(0)); int readerMid = messagesService.createMessage(reader.getUid(), "PEOPLE", null, null); messagesService.recommendMessage(readerMid, recommender.getUid()); @@ -1398,8 +1324,7 @@ public class ServerTests { 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); + int rid = messagesService.createReply(mid, 0, commenter, "@mmm is dick", null); Message reply = messagesService.getReply(mid, rid); assertThat(subscriptionService.getUsersSubscribedToComments(msg, reply).size(), is(1)); subscriptionService.subscribeUser(mentioner, commenter); @@ -1407,6 +1332,7 @@ public class ServerTests { privacyQueriesService.blacklistUser(mentioner, commenter); assertThat(subscriptionService.getUsersSubscribedToComments(msg, reply).size(), is(0)); } + @Test public void mentionsInPosts() { jdbcTemplate.execute("DELETE FROM bl_users"); @@ -1432,8 +1358,7 @@ public class ServerTests { // only uid, name and uri assertThat(user.keySet().size(), is(3)); - JAXBContext context = JAXBContext - .newInstance(User.class); + JAXBContext context = JAXBContext.newInstance(User.class); Marshaller m = context.createMarshaller(); StringWriter sw = new StringWriter(); @@ -1465,8 +1390,7 @@ public class ServerTests { .andExpect(status().isNotFound()); mockMvc.perform(get("/api/info/isilmine").with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().isNotFound()); - mockMvc.perform(get("/api/info/ugnich").with(httpBasic(ugnichName, ugnichPassword))) - .andExpect(status().isOk()); + mockMvc.perform(get("/api/info/ugnich").with(httpBasic(ugnichName, ugnichPassword))).andExpect(status().isOk()); } @Test @@ -1477,10 +1401,8 @@ public class ServerTests { userService.createUser(userName, userPassword); mockMvc.perform(get("/api/auth").with(httpBasic(userName, userPassword))).andExpect(status().isUnauthorized()); - mockMvc.perform(post("/login") - .param("username", userName) - .param("password", userPassword)).andExpect(status().is3xxRedirection()) - .andExpect(redirectedUrl("/login?error=1")); + mockMvc.perform(post("/login").param("username", userName).param("password", userPassword)) + .andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("/login?error=1")); } @Test @@ -1494,19 +1416,18 @@ public class ServerTests { 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); + 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)); - assertThat(CollectionUtils.isEqualCollection(messagesService.getMessagesRecommendations( - Collections.singletonList(mid)) - .stream().map(p -> p.getRight()).map(User::getName).collect(Collectors.toList()), + assertThat(CollectionUtils.isEqualCollection( + messagesService.getMessagesRecommendations(Collections.singletonList(mid)).stream() + .map(p -> p.getRight()).map(User::getName).collect(Collectors.toList()), Arrays.asList("fmap", "ermine", "pogo", "Anonymous")), is(true)); - privacyQueriesService.blacklistUser(userService.getUserByName("monstreek"), - userService.getUserByName("pogo")); + privacyQueriesService.blacklistUser(userService.getUserByName("monstreek"), userService.getUserByName("pogo")); assertThat(messagesService.getMessage(mid).get().getLikes(), is(4)); - assertThat(CollectionUtils.isEqualCollection(messagesService.getMessagesRecommendations( - Collections.singletonList(mid)) - .stream().map(p -> p.getRight()).map(User::getName).collect(Collectors.toList()), + assertThat(CollectionUtils.isEqualCollection( + messagesService.getMessagesRecommendations(Collections.singletonList(mid)).stream() + .map(p -> p.getRight()).map(User::getName).collect(Collectors.toList()), Arrays.asList("fmap", "ermine", "Anonymous")), is(true)); } @@ -1526,40 +1447,39 @@ public class ServerTests { int bannedRid = messagesService.createReply(mid, 0, banned, "KURWA", null); int casualRid = messagesService.createReply(mid, 0, userService.getUserByName("user"), "DOOR", null); assertThat(messagesService.getReplies(AnonymousUser.INSTANCE, mid).size(), is(1)); - assertThat(messagesService.getMessages(AnonymousUser.INSTANCE, Collections.singletonList(mid)).get(0).getReplies(), is(1)); + assertThat( + messagesService.getMessages(AnonymousUser.INSTANCE, Collections.singletonList(mid)).get(0).getReplies(), + is(1)); assertThat(messagesService.getReplies(banned, mid).size(), is(2)); assertThat(messagesService.getMessages(banned, Collections.singletonList(mid)).get(0).getReplies(), is(2)); } @Test public void accountUrlShouldBeExposedOverWebfinger() throws Exception { - mockMvc.perform(get("/.well-known/webfinger?resource=acct:ugnich@localhost")) - .andExpect(status().isOk()) + mockMvc.perform(get("/.well-known/webfinger?resource=acct:ugnich@localhost")).andExpect(status().isOk()) .andExpect(jsonPath("$.subject", is("acct:ugnich@localhost"))) .andExpect(jsonPath("$.links", hasSize(1))) .andExpect(jsonPath("$.links[0].href", is("http://localhost:8080/u/ugnich"))); - mockMvc.perform(get("/.well-known/webfinger?resource=acct:durov@localhost")) - .andExpect(status().isNotFound()); + mockMvc.perform(get("/.well-known/webfinger?resource=acct:durov@localhost")).andExpect(status().isNotFound()); } @Test public void userProfileAndBlogShouldBeExposedAsActivityStream() throws Exception { ClassPathResource defaultAvatar = new ClassPathResource("static/av-96.png"); String hash = DigestUtils.md5DigestAsHex(IOUtils.toByteArray(defaultAvatar.getInputStream())); - mockMvc.perform(get("/u/ugnich").accept(Context.LD_JSON_MEDIA_TYPE)) - .andExpect(status().isOk()) + mockMvc.perform(get("/u/ugnich").accept(Context.LD_JSON_MEDIA_TYPE)).andExpect(status().isOk()) .andExpect(jsonPath("$.icon.url", is(String.format("http://localhost:8080/av-96-%s.png", hash)))) .andExpect(jsonPath("$.publicKey.publicKeyPem", is(keystoreManager.getPublicKeyPem()))); jdbcTemplate.execute("DELETE FROM messages"); List mids = IteratorUtils.toList(IntStream.rangeClosed(1, 30) - .mapToObj(i -> messagesService.createMessage(ugnich.getUid(), - String.format("message %d", i), null, null)) + .mapToObj( + i -> messagesService.createMessage(ugnich.getUid(), String.format("message %d", i), null, null)) .collect(Collectors.toCollection(ArrayDeque::new)).descendingIterator()); List midsPage = mids.stream().limit(20).collect(Collectors.toList()); mockMvc.perform(get("/u/ugnich/blog").accept(Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE)) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.orderedItems", hasSize(20))) - .andExpect(jsonPath("$.next", is("http://localhost:8080/u/ugnich/blog?before=" + midsPage.get(midsPage.size() - 1)))); + .andExpect(status().isOk()).andExpect(jsonPath("$.orderedItems", hasSize(20))) + .andExpect(jsonPath("$.next", + is("http://localhost:8080/u/ugnich/blog?before=" + midsPage.get(midsPage.size() - 1)))); } @Test @@ -1573,16 +1493,16 @@ public class ServerTests { @Test public void repliesList() throws IOException { int mid = messagesService.createMessage(ugnich.getUid(), "hello", null, null); - IntStream.range(1, 15).forEach(i -> - messagesService.createReply(mid, i - 1, freefd, String.valueOf(i - 1), null)); + IntStream.range(1, 15) + .forEach(i -> messagesService.createReply(mid, i - 1, freefd, String.valueOf(i - 1), null)); HtmlPage threadPage = webClient.getPage(String.format("http://localhost:8080/ugnich/%d", mid)); assertThat(threadPage.getWebResponse().getStatusCode(), equalTo(200)); - Long visibleItems = StreamSupport.stream(threadPage.getHtmlElementById("replies") - .getChildElements().spliterator(), false).filter(e -> { - StyleElement display = e.getStyleElement("display"); - return display == null || !display.getValue().equals("none"); - }).count(); + Long visibleItems = StreamSupport + .stream(threadPage.getHtmlElementById("replies").getChildElements().spliterator(), false).filter(e -> { + StyleElement display = e.getStyleElement("display"); + return display == null || !display.getValue().equals("none"); + }).count(); assertThat(visibleItems, equalTo(14L)); } @@ -1590,16 +1510,13 @@ public class ServerTests { public void userShouldNotSeeReplyButtonToBannedUser() throws Exception { int mid = messagesService.createMessage(ugnich.getUid(), "freefd bl me", null, null); messagesService.createReply(mid, 0, ugnich, "yo", null); - MvcResult loginResult = mockMvc.perform(post("/login") - .param("username", freefdName) - .param("password", freefdPassword)) + MvcResult loginResult = mockMvc + .perform(post("/login").param("username", freefdName).param("password", freefdPassword)) .andExpect(status().isFound()).andReturn(); Cookie loginCookie = loginResult.getResponse().getCookie("juick-remember-me"); webClient.setCookieManager(new CookieManager()); - webClient.getCookieManager().addCookie( - new com.gargoylesoftware.htmlunit.util.Cookie(loginCookie.getDomain(), - loginCookie.getName(), - loginCookie.getValue())); + webClient.getCookieManager().addCookie(new com.gargoylesoftware.htmlunit.util.Cookie(loginCookie.getDomain(), + loginCookie.getName(), loginCookie.getValue())); HtmlPage 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(false)); @@ -1619,8 +1536,7 @@ public class ServerTests { PebbleTemplate template = pebbleEngine.getTemplate("views/test"); Writer writer = new StringWriter(); template.evaluate(writer, - Collections.singletonMap("tagsList", - Collections.singletonList(new Tag(">_<").getName()))); + Collections.singletonMap("tagsList", Collections.singletonList(new Tag(">_<").getName()))); String output = writer.toString().trim(); assertThat(output, equalTo(">_<")); } @@ -1628,8 +1544,8 @@ public class ServerTests { public DomElement fetchMeta(String url, String name) throws IOException { HtmlPage page = webClient.getPage(url); DomElement emptyMeta = new DomElement("", "meta", null, null); - return page.getElementsByTagName("meta").stream() - .filter(t -> t.getAttribute("name").equals(name)).findFirst().orElse(emptyMeta); + return page.getElementsByTagName("meta").stream().filter(t -> t.getAttribute("name").equals(name)).findFirst() + .orElse(emptyMeta); } @Test @@ -1643,7 +1559,8 @@ public class ServerTests { Message message = messagesService.getMessage(mid2).get(); assertThat(fetchMeta(String.format("http://localhost:8080/ugnich/%d", mid2), "twitter:card") .getAttribute("content"), equalTo("summary_large_image")); - assertThat(fetchMeta(String.format("http://localhost:8080/ugnich/%d", mid2), "og:description") + assertThat( + fetchMeta(String.format("http://localhost:8080/ugnich/%d", mid2), "og:description") .getAttribute("content"), startsWith(StringEscapeUtils.escapeHtml4(MessageUtils.getMessageHashTags(message)))); } @@ -1651,15 +1568,12 @@ public class ServerTests { @Test public void hashLoginShouldNotUseSession() throws Exception { String hash = userService.getHashByUID(ugnich.getUid()); - MvcResult hashLoginResult = mockMvc.perform(get("/?show=my&hash=" + hash)) - .andExpect(status().isOk()) + MvcResult hashLoginResult = mockMvc.perform(get("/?show=my&hash=" + hash)).andExpect(status().isOk()) .andExpect(model().attribute("visitor", hasProperty("authHash", equalTo(hash)))) - .andExpect(content().string(containsString(hash))) - .andReturn(); + .andExpect(content().string(containsString(hash))).andReturn(); Cookie rememberMeFromHash = hashLoginResult.getResponse().getCookie("juick-remember-me"); - MvcResult formLoginResult = mockMvc.perform(post("/login") - .param("username", ugnichName) - .param("password", ugnichPassword)) + MvcResult formLoginResult = mockMvc + .perform(post("/login").param("username", ugnichName).param("password", ugnichPassword)) .andExpect(status().is3xxRedirection()).andReturn(); Cookie rememberMeFromForm = formLoginResult.getResponse().getCookie("juick-remember-me"); mockMvc.perform(get("/?show=my").cookie(rememberMeFromForm)).andExpect(status().isOk()) @@ -1680,16 +1594,13 @@ public class ServerTests { String msgText = "Привет, я снова Угнич"; int mid = messagesService.createMessage(ugnich.getUid(), msgText, null, null); int midNew = messagesService.createMessage(ugnich.getUid(), "Я более новый Угнич", null, null); - MvcResult loginResult = mockMvc.perform(post("/login") - .param("username", freefdName) - .param("password", freefdPassword)) + MvcResult loginResult = mockMvc + .perform(post("/login").param("username", freefdName).param("password", freefdPassword)) .andExpect(status().is3xxRedirection()).andReturn(); Cookie loginCookie = loginResult.getResponse().getCookie("juick-remember-me"); webClient.setCookieManager(new CookieManager()); - webClient.getCookieManager().addCookie( - new com.gargoylesoftware.htmlunit.util.Cookie(loginCookie.getDomain(), - loginCookie.getName(), - loginCookie.getValue())); + webClient.getCookieManager().addCookie(new com.gargoylesoftware.htmlunit.util.Cookie(loginCookie.getDomain(), + loginCookie.getName(), loginCookie.getValue())); String discussionsUrl = "http://localhost:8080/"; HtmlPage discussions = webClient.getPage(discussionsUrl); assertThat(discussions.querySelectorAll("article").size(), is(0)); @@ -1699,61 +1610,65 @@ public class ServerTests { subscriptionService.subscribeMessage(messagesService.getMessage(midNew).get(), freefd); discussions = (HtmlPage) discussions.refresh(); assertThat(discussions.querySelectorAll("article").size(), is(2)); - assertThat(discussions.querySelectorAll("article").get(0).getAttributes().getNamedItem("data-mid").getNodeValue(), is(String.valueOf(midNew))); + assertThat( + discussions.querySelectorAll("article").get(0).getAttributes().getNamedItem("data-mid").getNodeValue(), + is(String.valueOf(midNew))); messagesService.createReply(mid, 0, freefd, "I'm replied", null); discussions = (HtmlPage) discussions.refresh(); assertThat(discussions.querySelectorAll("article").size(), is(2)); - assertThat(discussions.querySelectorAll("article").get(0).getAttributes().getNamedItem("data-mid").getNodeValue(), is(String.valueOf(mid))); + assertThat( + discussions.querySelectorAll("article").get(0).getAttributes().getNamedItem("data-mid").getNodeValue(), + is(String.valueOf(mid))); Message msg = messagesService.getMessage(mid).get(); HtmlPage discussionsOld = webClient.getPage(discussionsUrl + "?to=" + msg.getUpdated().toEpochMilli()); assertThat(discussionsOld.querySelectorAll("article").size(), is(1)); - assertThat(discussionsOld.querySelectorAll("article").get(0).getAttributes().getNamedItem("data-mid").getNodeValue(), is(String.valueOf(midNew))); - List newMids = IntStream.rangeClosed(1, 19).map(i -> messagesService.createMessage(ugnich.getUid(), String.valueOf(i), null, null)).boxed().collect(Collectors.toList()); + assertThat(discussionsOld.querySelectorAll("article").get(0).getAttributes().getNamedItem("data-mid") + .getNodeValue(), is(String.valueOf(midNew))); + List newMids = IntStream.rangeClosed(1, 19) + .map(i -> messagesService.createMessage(ugnich.getUid(), String.valueOf(i), null, null)).boxed() + .collect(Collectors.toList()); for (Integer m : newMids) { subscriptionService.subscribeMessage(messagesService.getMessage(m).get(), freefd); } discussions = (HtmlPage) discussions.refresh(); assertThat(discussions.querySelectorAll("article").size(), is(20)); - assertThat(discussions.querySelectorAll("article") - .get(19).getAttributes().getNamedItem("data-mid").getNodeValue(), is(String.valueOf(mid))); + assertThat( + discussions.querySelectorAll("article").get(19).getAttributes().getNamedItem("data-mid").getNodeValue(), + is(String.valueOf(mid))); messagesService.createReply(midNew, 0, freefd, "I'm replied", null); discussions = (HtmlPage) discussions.refresh(); - assertThat(discussions.querySelectorAll("article") - .get(0).getAttributes().getNamedItem("data-mid").getNodeValue(), is(String.valueOf(midNew))); + assertThat( + discussions.querySelectorAll("article").get(0).getAttributes().getNamedItem("data-mid").getNodeValue(), + is(String.valueOf(midNew))); Message old = messagesService.getMessage(newMids.get(0)).get(); discussionsOld = webClient.getPage(discussionsUrl + "?to=" + old.getUpdated().toEpochMilli()); assertThat(discussionsOld.querySelectorAll("article").size(), is(1)); - assertThat(discussionsOld.querySelectorAll("article") - .get(0).getAttributes().getNamedItem("data-mid").getNodeValue(), is(String.valueOf(mid))); + assertThat(discussionsOld.querySelectorAll("article").get(0).getAttributes().getNamedItem("data-mid") + .getNodeValue(), is(String.valueOf(mid))); } @Test public void redirectParamShouldCorrectlyRedirectLoggedUser() throws Exception { - MvcResult formLoginResult = mockMvc.perform(post("/login") - .param("username", ugnichName) - .param("password", ugnichPassword)) + MvcResult formLoginResult = mockMvc + .perform(post("/login").param("username", ugnichName).param("password", ugnichPassword)) .andExpect(status().isFound()).andReturn(); Cookie rememberMeFromForm = formLoginResult.getResponse().getCookie("juick-remember-me"); - mockMvc.perform(get("/login").cookie(rememberMeFromForm)) - .andExpect(status().is3xxRedirection()) + mockMvc.perform(get("/login").cookie(rememberMeFromForm)).andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/")); - mockMvc.perform(get("/login?redirect=false").cookie(rememberMeFromForm)) - .andExpect(status().is3xxRedirection()) + mockMvc.perform(get("/login?redirect=false").cookie(rememberMeFromForm)).andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/login/success")); } @Test public void anythingRedirects() throws Exception { int mid = messagesService.createMessage(ugnich.getUid(), "yo", null, null); - mockMvc.perform(get(String.format("/%d", mid))) - .andExpect(status().isMovedPermanently()) + mockMvc.perform(get(String.format("/%d", mid))).andExpect(status().isMovedPermanently()) .andExpect(redirectedUrl(String.format("/%s/%d", ugnich.getName(), mid))); } @Test public void appAssociationsTest() throws Exception { - mockMvc.perform((get("/.well-known/apple-app-site-association"))) - .andExpect(status().isOk()) + mockMvc.perform((get("/.well-known/apple-app-site-association"))).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.webcredentials.apps[0]", is(appId))); } @@ -1764,16 +1679,13 @@ public class ServerTests { jdbcTemplate.execute("DELETE FROM replies"); jdbcTemplate.execute("DELETE FROM subscr_messages"); jdbcTemplate.execute("DELETE FROM bl_users"); - MvcResult loginResult = mockMvc.perform(post("/login") - .param("username", freefdName) - .param("password", freefdPassword)) + MvcResult loginResult = mockMvc + .perform(post("/login").param("username", freefdName).param("password", freefdPassword)) .andExpect(status().is3xxRedirection()).andReturn(); Cookie loginCookie = loginResult.getResponse().getCookie("juick-remember-me"); webClient.setCookieManager(new CookieManager()); - webClient.getCookieManager().addCookie( - new com.gargoylesoftware.htmlunit.util.Cookie(loginCookie.getDomain(), - loginCookie.getName(), - loginCookie.getValue())); + webClient.getCookieManager().addCookie(new com.gargoylesoftware.htmlunit.util.Cookie(loginCookie.getDomain(), + loginCookie.getName(), loginCookie.getValue())); int mid = messagesService.createMessage(ugnich.getUid(), "new test", null, null); subscriptionService.subscribeMessage(messagesService.getMessage(mid).get(), freefd); messagesService.createReply(mid, 0, ugnich, "new reply", null); @@ -1786,30 +1698,30 @@ public class ServerTests { assertThat(discussionsPage.querySelectorAll("#global a .badge").size(), is(1)); privacyQueriesService.blacklistUser(freefd, ugnich); assertThat(messagesService.getUnread(freefd).size(), is(0)); - /* TODO: fix - discussionsPage.refresh(); - var unreads = discussionsPage.querySelectorAll("#global a .badge"); - assertThat(unreads.size(), is(0)); + /* + * TODO: fix discussionsPage.refresh(); var unreads = + * discussionsPage.querySelectorAll("#global a .badge"); + * assertThat(unreads.size(), is(0)); */ privacyQueriesService.blacklistUser(freefd, ugnich); } @Test public void escapeSqlTests() { - String sql = String.format("SELECT * FROM table WHERE data='%s'", WebUtils.encodeSphinx("';-- DROP TABLE table")); + String sql = String.format("SELECT * FROM table WHERE data='%s'", + WebUtils.encodeSphinx("';-- DROP TABLE table")); assertThat(sql, is("SELECT * FROM table WHERE data='\\';-- DROP TABLE table\'")); } @Test public void swaggerOutput() throws Exception { - MvcResult result = mockMvc.perform(get("/v3/api-docs") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andReturn(); + MvcResult result = mockMvc.perform(get("/v3/api-docs").accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()).andReturn(); String outputDir = System.getProperty("io.springfox.staticdocs.outputDir"); if (StringUtils.isNotEmpty(outputDir)) { Files.createDirectories(Paths.get(outputDir)); - BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8); + BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), + StandardCharsets.UTF_8); writer.write(result.getResponse().getContentAsString()); writer.flush(); } @@ -1829,11 +1741,9 @@ public class ServerTests { @Test public void oneClickUnsubscribe() throws Exception { - mockMvc.perform(post("/settings/unsubscribe") - .param("hash", "123456") - .param("List-Unsubscribe", "One-Click")).andExpect(status().isBadRequest()); - mockMvc.perform(post("/settings/unsubscribe") - .param("hash", userService.getHashByUID(ugnich.getUid())) + mockMvc.perform(post("/settings/unsubscribe").param("hash", "123456").param("List-Unsubscribe", "One-Click")) + .andExpect(status().isBadRequest()); + mockMvc.perform(post("/settings/unsubscribe").param("hash", userService.getHashByUID(ugnich.getUid())) .param("List-Unsubscribe", "One-Click")).andExpect(status().isOk()); } @@ -1867,14 +1777,20 @@ public class ServerTests { assertThat(replyNote.getInReplyTo(), equalTo(extMessageUri)); String noteStr = IOUtils.toString(new ClassPathResource("mention.json").getURI(), StandardCharsets.UTF_8); Note create2 = jsonMapper.readValue(noteStr, Note.class); - jsonMapper.readValue(IOUtils.toString(new ClassPathResource("webfinger.json").getURI(), StandardCharsets.UTF_8), Account.class); - NodeInfo info = jsonMapper.readValue(IOUtils.toString(new ClassPathResource("xnodeinfo2.json").getURI(), StandardCharsets.UTF_8), NodeInfo.class); + jsonMapper.readValue(IOUtils.toString(new ClassPathResource("webfinger.json").getURI(), StandardCharsets.UTF_8), + Account.class); + NodeInfo info = jsonMapper.readValue( + IOUtils.toString(new ClassPathResource("xnodeinfo2.json").getURI(), StandardCharsets.UTF_8), + NodeInfo.class); assertThat(info.getUsage().getUsers().getActiveHalfyear(), is(42)); - Like like = jsonMapper.readValue(IOUtils.toString(new ClassPathResource("like.json").getURI(), StandardCharsets.UTF_8), Like.class); - String undoPleromaStr = IOUtils.toString(new ClassPathResource("undo_pleroma.json").getURI(), StandardCharsets.UTF_8); + Like like = jsonMapper.readValue( + IOUtils.toString(new ClassPathResource("like.json").getURI(), StandardCharsets.UTF_8), Like.class); + String undoPleromaStr = IOUtils.toString(new ClassPathResource("undo_pleroma.json").getURI(), + StandardCharsets.UTF_8); Undo undoPleroma = jsonMapper.readValue(undoPleromaStr, Undo.class); String undoPleromaFollower = (String) ((Map) undoPleroma.getObject()).get("object"); - String deletev3JsonStr = IOUtils.toString(new ClassPathResource("delete_v3.json").getURI(), StandardCharsets.UTF_8); + String deletev3JsonStr = IOUtils.toString(new ClassPathResource("delete_v3.json").getURI(), + StandardCharsets.UTF_8); Delete deleteObject = jsonMapper.readValue(deletev3JsonStr, Delete.class); } @@ -1897,8 +1813,11 @@ public class ServerTests { create.setObject(replyNote); signatureManager.post((Person) signatureManager.getContext(URI.create("http://localhost:8080/u/freefd")).get(), (Person) signatureManager.getContext(URI.create("http://localhost:8080/u/ugnich")).get(), create); - Message replyToExt = commandsManager.processCommand(ugnich, String.format("#%d/1 PSSH YOBA ETO TI", msg.getMid()), emptyUri).getNewMessage().get(); - json = jsonMapper.writeValueAsString(Context.build(activityPubManager.makeNote(messagesService.getReply(replyToExt.getMid(), replyToExt.getRid())))); + Message replyToExt = commandsManager + .processCommand(ugnich, String.format("#%d/1 PSSH YOBA ETO TI", msg.getMid()), emptyUri).getNewMessage() + .get(); + json = jsonMapper.writeValueAsString(Context.build( + activityPubManager.makeNote(messagesService.getReply(replyToExt.getMid(), replyToExt.getRid())))); } @Test @@ -1916,20 +1835,15 @@ public class ServerTests { String meUri = "/api/me"; Instant now = Instant.now(); String requestDate = DateFormattersHolder.getHttpDateFormatter().format(now); - mockMvc.perform(get("/api/me") - .header("Date", requestDate)) - .andExpect(status().isUnauthorized()); + mockMvc.perform(get("/api/me").header("Date", requestDate)).andExpect(status().isUnauthorized()); String testHost = "localhost"; Person ugnichPerson = profileController.getUser("ugnich"); now = Instant.now(); requestDate = DateFormattersHolder.getHttpDateFormatter().format(now); - String signatureString = signatureManager.addSignature(ugnichPerson, testHost, "GET", meUri, requestDate, StringUtils.EMPTY); - MvcResult me = mockMvc.perform(get("/api/me") - .header("Host", testHost) - .header("Date", requestDate) - .header("Signature", signatureString)) - .andExpect(status().isOk()) - .andReturn(); + String signatureString = signatureManager.addSignature(ugnichPerson, testHost, "GET", meUri, requestDate, + StringUtils.EMPTY); + MvcResult me = mockMvc.perform(get("/api/me").header("Host", testHost).header("Date", requestDate) + .header("Signature", signatureString)).andExpect(status().isOk()).andReturn(); User meUser = jsonMapper.readValue(me.getResponse().getContentAsString(), User.class); assertThat(meUser, is(ugnich)); String testuserResponseString = IOUtils.toString(testuserResponse.getInputStream(), StandardCharsets.UTF_8); @@ -1949,42 +1863,26 @@ public class ServerTests { var payload = IOUtils.toByteArray(testfollowRequest.getInputStream()); final byte[] digest = MessageDigest.getInstance("SHA-256").digest(payload); // (1) final String digestHeader = "SHA-256=" + new String(Base64.encodeBase64(digest)); - String testSignatureString = - signatureManager.addSignature(testuser, testHost, "POST", - inboxUri, testRequestDate, digestHeader, testKeystoreManager); - mockMvc.perform(post(inboxUri) - .header("Host", testHost) - .header("Date", testRequestDate) - .header("Digest", digestHeader) - .header("Signature", testSignatureString) - .contentType(Context.LD_JSON_MEDIA_TYPE) - .content(payload)) - .andExpect(status().isAccepted()); - mockMvc.perform(post(inboxUri) - .header("Host", "wronghost") - .header("Date", testRequestDate) - .header("Signature", testSignatureString) - .contentType(Context.LD_JSON_MEDIA_TYPE) - .content(IOUtils.toByteArray(testfollowRequest.getInputStream()))) - .andExpect(status().isUnauthorized()); + String testSignatureString = signatureManager.addSignature(testuser, testHost, "POST", inboxUri, + testRequestDate, digestHeader, testKeystoreManager); + mockMvc.perform(post(inboxUri).header("Host", testHost).header("Date", testRequestDate) + .header("Digest", digestHeader).header("Signature", testSignatureString) + .contentType(Context.LD_JSON_MEDIA_TYPE).content(payload)).andExpect(status().isAccepted()); + mockMvc.perform(post(inboxUri).header("Host", "wronghost").header("Date", testRequestDate) + .header("Signature", testSignatureString).contentType(Context.LD_JSON_MEDIA_TYPE) + .content(IOUtils.toByteArray(testfollowRequest.getInputStream()))).andExpect(status().isUnauthorized()); // digest required but not present - mockMvc.perform(post(inboxUri) - .header("Host", testHost) - .header("Date", testRequestDate) - .header("Signature", testSignatureString) - .contentType(Context.LD_JSON_MEDIA_TYPE) - .content(payload)) + mockMvc.perform(post(inboxUri).header("Host", testHost).header("Date", testRequestDate) + .header("Signature", testSignatureString).contentType(Context.LD_JSON_MEDIA_TYPE).content(payload)) .andExpect(status().isUnauthorized()); apClient.setRequestFactory(originalRequestFactory); } @Test public void hostmeta() throws Exception { - MvcResult result = mockMvc.perform(get("/.well-known/host-meta")) - .andExpect(status().isOk()).andReturn(); + MvcResult result = mockMvc.perform(get("/.well-known/host-meta")).andExpect(status().isOk()).andReturn(); String xrd = result.getResponse().getContentAsString(); - result = mockMvc.perform(get("/.well-known/x-nodeinfo2")) - .andExpect(status().isOk()).andReturn(); + result = mockMvc.perform(get("/.well-known/x-nodeinfo2")).andExpect(status().isOk()).andReturn(); } @Test @@ -1994,10 +1892,8 @@ public class ServerTests { CommandResult res = commandsManager.processCommand(ugnich, "@freefd DICK", emptyUri); assertThat(res.getNewMessage(), is(Optional.empty())); assertThat(res.getText(), is("Private message sent")); - MvcResult result = mockMvc.perform(get("/api/groups_pms") - .with(httpBasic(freefdName, freefdPassword))) - .andExpect(status().isOk()) - .andReturn(); + MvcResult result = mockMvc.perform(get("/api/groups_pms").with(httpBasic(freefdName, freefdPassword))) + .andExpect(status().isOk()).andReturn(); PrivateChats chats = jsonMapper.readValue(result.getResponse().getContentAsString(), PrivateChats.class); assertThat(chats.getUsers().size(), is(1)); } @@ -2015,39 +1911,38 @@ public class ServerTests { @Test public void signupTest() throws Exception { emailService.addVerificationCode(null, "demo@email.com", "123456"); - MvcResult result = mockMvc.perform(post("/api/signup") - .param("username", "testuser") - .param("password", "demopassword") - .param("verificationCode", "123456")).andExpect(status().isOk()).andReturn(); + MvcResult result = mockMvc.perform(post("/api/signup").param("username", "testuser") + .param("password", "demopassword").param("verificationCode", "123456")).andExpect(status().isOk()) + .andReturn(); User testuser = jsonMapper.readValue(result.getResponse().getContentAsString(), User.class); assertThat(testuser.getName(), is("testuser")); } @Test public void doNotAllowRepliesToNonExistingReplyAndNotAllowToEditTagsOfComment() throws Exception { - assertThat(commandsManager.processCommand(ugnich, "#23213213/2 BAD COMMENT", emptyUri).getText(), is("Message not found")); + assertThat(commandsManager.processCommand(ugnich, "#23213213/2 BAD COMMENT", emptyUri).getText(), + is("Message not found")); Message msg = commandsManager.processCommand(ugnich, "YO", emptyUri).getNewMessage().get(); - assertThat(commandsManager.processCommand(ugnich, String.format("#%d/1 BAD COMMENT", msg.getMid()), emptyUri).getText(), is("Reply not found")); - CommandResult result = commandsManager.processCommand(freefd, - String.format("#%d *GOOD *COMMENT", msg.getMid()), emptyUri); + assertThat(commandsManager.processCommand(ugnich, String.format("#%d/1 BAD COMMENT", msg.getMid()), emptyUri) + .getText(), is("Reply not found")); + CommandResult result = commandsManager.processCommand(freefd, String.format("#%d *GOOD *COMMENT", msg.getMid()), + emptyUri); Message reply = result.getNewMessage().get(); - assertThat(commandsManager.processCommand(ugnich, String.format("#%d/%d *GOOD *BAD", reply.getMid(), reply.getRid()), emptyUri).getText(), startsWith("Reply posted")); + assertThat( + commandsManager.processCommand(ugnich, + String.format("#%d/%d *GOOD *BAD", reply.getMid(), reply.getRid()), emptyUri).getText(), + startsWith("Reply posted")); } @Test public void XMPPSignupIsDisabled() throws Exception { jdbcTemplate.update("INSERT INTO jids(loginhash, jid) VALUES('1', 'test@jid.tld')"); - MvcResult formLoginResult = mockMvc.perform(post("/login") - .param("username", ugnichName) - .param("password", ugnichPassword)) + MvcResult formLoginResult = mockMvc + .perform(post("/login").param("username", ugnichName).param("password", ugnichPassword)) .andExpect(status().is3xxRedirection()).andReturn(); Cookie rememberMeFromForm = formLoginResult.getResponse().getCookie("juick-remember-me"); - mockMvc.perform(post("/signup") - .cookie(rememberMeFromForm) - .param("hash", "1") - .param("type", "xmpp") - .param("action", "link")) - .andExpect(status().isOk()) + mockMvc.perform(post("/signup").cookie(rememberMeFromForm).param("hash", "1").param("type", "xmpp") + .param("action", "link")).andExpect(status().isOk()) .andExpect(content().string(containsString("XMPP support is disabled"))); } @@ -2073,125 +1968,98 @@ public class ServerTests { public void changeProfileOverApi() throws Exception { ClassPathResource defaultAvatar = new ClassPathResource("static/av-96.png"); String hash = DigestUtils.md5DigestAsHex(IOUtils.toByteArray(defaultAvatar.getInputStream())); - assertThat(webApp.getAvatarUrl(userService.getUserByName(freefdName)), is(String.format("http://localhost:8080/av-96-%s.png", hash))); + assertThat(webApp.getAvatarUrl(userService.getUserByName(freefdName)), + is(String.format("http://localhost:8080/av-96-%s.png", hash))); ClassPathResource newAvatar = new ClassPathResource("static/durov.png"); byte[] newAvatarData = IOUtils.toByteArray(newAvatar.getInputStream()); mockMvc.perform(MockMvcRequestBuilders.multipart("/api/me/upload") .file(new MockMultipartFile("avatar", "durov.png", "image/png", newAvatarData)) - .with(httpBasic(freefdName, freefdPassword)) - ).andExpect(status().isOk()); + .with(httpBasic(freefdName, freefdPassword))).andExpect(status().isOk()); String newHash = DigestUtils.md5DigestAsHex(newAvatarData); URI newUri = Paths.get(imgDir, "ao", String.format("%d.png", freefd.getUid())).toUri(); assertThat(DigestUtils.md5DigestAsHex(IOUtils.toByteArray(newUri)), is(newHash)); - mockMvc.perform(post("/api/me") - .with(httpBasic(ugnichName, ugnichPassword)) - .param("password", "newPassword")) + mockMvc.perform(post("/api/me").with(httpBasic(ugnichName, ugnichPassword)).param("password", "newPassword")) .andExpect(status().isOk()); - mockMvc.perform(get("/api/me") - .with(httpBasic(ugnichName, ugnichPassword))) + mockMvc.perform(get("/api/me").with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().isUnauthorized()); - mockMvc.perform(post("/api/me") - .with(httpBasic(ugnichName, "newPassword")) - .param("password", ugnichPassword)) - .andExpect(status().isOk()); - mockMvc.perform(get("/api/me") - .with(httpBasic(ugnichName, ugnichPassword))) + mockMvc.perform(post("/api/me").with(httpBasic(ugnichName, "newPassword")).param("password", ugnichPassword)) .andExpect(status().isOk()); + mockMvc.perform(get("/api/me").with(httpBasic(ugnichName, ugnichPassword))).andExpect(status().isOk()); assertThat(usersController.getMe(ugnich).getJIDs().size(), is(0)); - jdbcTemplate.update("INSERT INTO jids(user_id, jid) VALUES(?, ?)", - ugnich.getUid(), "test@example.com"); - jdbcTemplate.update("INSERT INTO jids(user_id, jid) VALUES(?, ?)", - ugnich.getUid(), "test2@example.com"); + jdbcTemplate.update("INSERT INTO jids(user_id, jid) VALUES(?, ?)", ugnich.getUid(), "test@example.com"); + jdbcTemplate.update("INSERT INTO jids(user_id, jid) VALUES(?, ?)", ugnich.getUid(), "test2@example.com"); assertThat(usersController.getMe(ugnich).getJIDs().size(), is(2)); - mockMvc.perform(post("/api/me") - .with(httpBasic(ugnichName, ugnichPassword)) - .param("jid-del", "test@example.com")) + mockMvc.perform( + post("/api/me").with(httpBasic(ugnichName, ugnichPassword)).param("jid-del", "test@example.com")) .andExpect(status().isOk()); assertThat(usersController.getMe(ugnich).getJIDs().size(), is(1)); - mockMvc.perform(post("/api/me") - .with(httpBasic(ugnichName, ugnichPassword)) - .param("jid-del", "test2@example.com")) + mockMvc.perform( + post("/api/me").with(httpBasic(ugnichName, ugnichPassword)).param("jid-del", "test2@example.com")) .andExpect(status().isBadRequest()); jdbcTemplate.execute("DELETE FROM jids"); } @Test public void varyMvcResponse() throws Exception { - mockMvc.perform(get("/")) - .andExpect(status().isOk()) + mockMvc.perform(get("/")).andExpect(status().isOk()).andExpect(header().string("Vary", "Accept-Language")); + mockMvc.perform(get("/rss/ugnich/blog")).andExpect(status().isOk()) .andExpect(header().string("Vary", "Accept-Language")); - mockMvc.perform(get("/rss/ugnich/blog")) - .andExpect(status().isOk()) - .andExpect(header().string("Vary", "Accept-Language")); - mockMvc.perform(get("/api/messages")) - .andExpect(status().isOk()) + mockMvc.perform(get("/api/messages")).andExpect(status().isOk()) .andExpect(header().string("Vary", "Accept-Language")); } @Test public void apiInfo() throws Exception { userService.createUser("tst", "tst"); - MvcResult result = mockMvc.perform(get("/api/info/tst")) - .andExpect(status().isOk()) - .andReturn(); + MvcResult result = mockMvc.perform(get("/api/info/tst")).andExpect(status().isOk()).andReturn(); User tst = jsonMapper.readValue(result.getResponse().getContentAsString(), User.class); assertThat(tst.getReaders(), is(nullValue())); commandsManager.processCommand(ugnich, "S @tst", emptyUri); - result = mockMvc.perform(get("/api/info/tst")) - .andExpect(status().isOk()) - .andReturn(); + result = mockMvc.perform(get("/api/info/tst")).andExpect(status().isOk()).andReturn(); tst = jsonMapper.readValue(result.getResponse().getContentAsString(), User.class); assertThat(tst.getReaders().size(), is(1)); } @Test public void federatedUserDeletionFlow() throws Exception { - String deleteJsonStr = IOUtils.toString(new ClassPathResource("delete_user.json").getURI(), StandardCharsets.UTF_8); + String deleteJsonStr = IOUtils.toString(new ClassPathResource("delete_user.json").getURI(), + StandardCharsets.UTF_8); Delete delete = jsonMapper.readValue(deleteJsonStr, Delete.class); ClientHttpRequestFactory originalRequestFactory = apClient.getRequestFactory(); MockRestServiceServer restServiceServer = MockRestServiceServer.createServer(apClient); restServiceServer.expect(times(2), requestTo((String) delete.getObject())) .andRespond(withStatus(HttpStatus.GONE)); - restServiceServer.expect(requestTo((String) delete.getObject())) - .andRespond(response -> { - throw new ResourceAccessException("Connection reset"); - }); - mockMvc.perform(post("/api/inbox") - .contentType(ACTIVITY_MEDIA_TYPE) - .content(deleteJsonStr)) + restServiceServer.expect(requestTo((String) delete.getObject())).andRespond(response -> { + throw new ResourceAccessException("Connection reset"); + }); + mockMvc.perform(post("/api/inbox").contentType(ACTIVITY_MEDIA_TYPE).content(deleteJsonStr)) .andExpect(status().isAccepted()); - mockMvc.perform(post("/api/inbox") - .contentType(ACTIVITY_MEDIA_TYPE) - .content(deleteJsonStr) - .header("Signature", "keyId=\"https://example.com/users/deleted#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) host date digest content-type\",signature=\"wHoU91JJBsIYcR1W1/57B0oG98t5Aa/TvGPw1B8KQlAp5KhpePnOzD1MZRgivBx7YKO6eYwDx+AX9dn6tjlAvzRLygv21H6UoDZFihWzeE1HM8pY2Pe4EhUgYBN0YuiKUi7W4TS9bDRAJ5vGNPUWATe+2o5Jcbux5cZYXFKKYbLBLD+/IlqPdHA2IXLZ52HFVVfBkPH5sSklV6XJtD/PHLK9R/I9w/mUpj9moUPQu44rR7KvxiGNuHla3vfDtJbkBqLMdScX91EG8373AulXPUiCCF7R2lJB0fFQedm2nSbcwBoJ32GEyOyOPFgPKG5zd9Fd5TfB1pmA8ZIE0sChfA==\"")) + mockMvc.perform(post("/api/inbox").contentType(ACTIVITY_MEDIA_TYPE).content(deleteJsonStr).header("Signature", + "keyId=\"https://example.com/users/deleted#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) host date digest content-type\",signature=\"wHoU91JJBsIYcR1W1/57B0oG98t5Aa/TvGPw1B8KQlAp5KhpePnOzD1MZRgivBx7YKO6eYwDx+AX9dn6tjlAvzRLygv21H6UoDZFihWzeE1HM8pY2Pe4EhUgYBN0YuiKUi7W4TS9bDRAJ5vGNPUWATe+2o5Jcbux5cZYXFKKYbLBLD+/IlqPdHA2IXLZ52HFVVfBkPH5sSklV6XJtD/PHLK9R/I9w/mUpj9moUPQu44rR7KvxiGNuHla3vfDtJbkBqLMdScX91EG8373AulXPUiCCF7R2lJB0fFQedm2nSbcwBoJ32GEyOyOPFgPKG5zd9Fd5TfB1pmA8ZIE0sChfA==\"")) .andExpect(status().isAccepted()); apClient.setRequestFactory(originalRequestFactory); } @Test public void handleIncorrectCertificates() throws Exception { - String deleteJsonStr = IOUtils.toString(new ClassPathResource("delete_user.json").getURI(), StandardCharsets.UTF_8); + String deleteJsonStr = IOUtils.toString(new ClassPathResource("delete_user.json").getURI(), + StandardCharsets.UTF_8); Delete delete = jsonMapper.readValue(deleteJsonStr, Delete.class); ClientHttpRequestFactory originalRequestFactory = apClient.getRequestFactory(); MockRestServiceServer restServiceServer = MockRestServiceServer.createServer(apClient); - restServiceServer.expect(requestTo((String) delete.getObject())) - .andRespond(response -> { - throw new ResourceAccessException("Connection reset"); - }); - mockMvc.perform(post("/api/inbox") - .contentType(ACTIVITY_MEDIA_TYPE) - .content(deleteJsonStr) - .header("Signature", "keyId=\"https://example.com/users/deleted#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) host date digest content-type\",signature=\"wHoU91JJBsIYcR1W1/57B0oG98t5Aa/TvGPw1B8KQlAp5KhpePnOzD1MZRgivBx7YKO6eYwDx+AX9dn6tjlAvzRLygv21H6UoDZFihWzeE1HM8pY2Pe4EhUgYBN0YuiKUi7W4TS9bDRAJ5vGNPUWATe+2o5Jcbux5cZYXFKKYbLBLD+/IlqPdHA2IXLZ52HFVVfBkPH5sSklV6XJtD/PHLK9R/I9w/mUpj9moUPQu44rR7KvxiGNuHla3vfDtJbkBqLMdScX91EG8373AulXPUiCCF7R2lJB0fFQedm2nSbcwBoJ32GEyOyOPFgPKG5zd9Fd5TfB1pmA8ZIE0sChfA==\"")) + restServiceServer.expect(requestTo((String) delete.getObject())).andRespond(response -> { + throw new ResourceAccessException("Connection reset"); + }); + mockMvc.perform(post("/api/inbox").contentType(ACTIVITY_MEDIA_TYPE).content(deleteJsonStr).header("Signature", + "keyId=\"https://example.com/users/deleted#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) host date digest content-type\",signature=\"wHoU91JJBsIYcR1W1/57B0oG98t5Aa/TvGPw1B8KQlAp5KhpePnOzD1MZRgivBx7YKO6eYwDx+AX9dn6tjlAvzRLygv21H6UoDZFihWzeE1HM8pY2Pe4EhUgYBN0YuiKUi7W4TS9bDRAJ5vGNPUWATe+2o5Jcbux5cZYXFKKYbLBLD+/IlqPdHA2IXLZ52HFVVfBkPH5sSklV6XJtD/PHLK9R/I9w/mUpj9moUPQu44rR7KvxiGNuHla3vfDtJbkBqLMdScX91EG8373AulXPUiCCF7R2lJB0fFQedm2nSbcwBoJ32GEyOyOPFgPKG5zd9Fd5TfB1pmA8ZIE0sChfA==\"")) .andExpect(status().isAccepted()); apClient.setRequestFactory(originalRequestFactory); } @Test public void legacyAvatarEndpoint() throws Exception { - mockMvc.perform(get("/api/avatar") - .param("uname", "unknown")) - .andExpect(status().isOk()) + mockMvc.perform(get("/api/avatar").param("uname", "unknown")).andExpect(status().isOk()) .andExpect(content().bytes(IOUtils.toByteArray(defaultAvatar.getInputStream()))); } @@ -2205,8 +2073,8 @@ public class ServerTests { Create create = jsonMapper.readValue(noteString, Create.class); Map note = (Map) create.getObject(); String markdown = remarkConverter.convertFragment((String) note.get("content")); - String commandBody = note.get("attachment") == null ? markdown : - ((List) note.get("attachment")).stream().map(attachmentObj -> { + String commandBody = note.get("attachment") == null ? markdown + : ((List) note.get("attachment")).stream().map(attachmentObj -> { Map attachment = (Map) attachmentObj; String attachmentUrl = attachment.get("url"); String attachmentName = attachment.get("name"); @@ -2225,24 +2093,19 @@ public class ServerTests { @Test public void nodeinfo() throws Exception { - MvcResult nodeinfoXRD = mockMvc.perform(get("/.well-known/nodeinfo") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andReturn(); + MvcResult nodeinfoXRD = mockMvc.perform(get("/.well-known/nodeinfo").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()).andReturn(); JsonNode node = jsonMapper.readTree(nodeinfoXRD.getResponse().getContentAsString()); assertThat(node.get("links"), notNullValue()); String nodeinfoUrl = node.get("links").get(0).get("href").textValue(); - MvcResult nodeinfoData = mockMvc.perform(get(nodeinfoUrl) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andReturn(); + MvcResult nodeinfoData = mockMvc.perform(get(nodeinfoUrl).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()).andReturn(); JsonNode nodeinfo = jsonMapper.readTree(nodeinfoData.getResponse().getContentAsString()); assertThat(nodeinfo.get("software"), notNullValue()); assertThat(nodeinfo.get("server"), nullValue()); - MvcResult xnodeinfoData = mockMvc.perform(get("/.well-known/x-nodeinfo2") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andReturn(); + MvcResult xnodeinfoData = mockMvc + .perform(get("/.well-known/x-nodeinfo2").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()).andReturn(); JsonNode xnodeinfo = jsonMapper.readTree(xnodeinfoData.getResponse().getContentAsString()); assertThat(xnodeinfo.get("server"), notNullValue()); assertThat(xnodeinfo.get("software"), nullValue()); @@ -2283,29 +2146,20 @@ public class ServerTests { @Test public void rssFeeds() throws Exception { - mockMvc.perform(get("/rss/ugnich/blog") - .accept(MediaType.TEXT_XML)) - .andExpect(status().isOk()); + mockMvc.perform(get("/rss/ugnich/blog").accept(MediaType.TEXT_XML)).andExpect(status().isOk()); // fallback - mockMvc.perform(get("/rss/ugnich/blog") - .header("Accept", - "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;" + - "q=0.8,application/signed-exchange;v=b3")) - .andExpect(status().isOk()) - .andExpect(content().contentType("application/rss+xml;charset=UTF-8")); + mockMvc.perform(get("/rss/ugnich/blog").header("Accept", + "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;" + + "q=0.8,application/signed-exchange;v=b3")) + .andExpect(status().isOk()).andExpect(content().contentType("application/rss+xml;charset=UTF-8")); } @Test public void wsThreadsShouldRedirect() throws Exception { int mid = messagesService.createMessage(ugnich.getUid(), "tst", null, Collections.emptyList()); - mockMvc.perform(get("/ugnich/" + mid)) - .andExpect(status().isOk()); - mockMvc.perform(get("/s/" + mid)) - .andExpect(status().isFound()) - .andExpect(redirectedUrl("/ugnich/" + mid)); - mockMvc.perform(get("/ws/" + mid)) - .andExpect(status().isFound()) - .andExpect(redirectedUrl("/ugnich/" + mid)); + mockMvc.perform(get("/ugnich/" + mid)).andExpect(status().isOk()); + mockMvc.perform(get("/s/" + mid)).andExpect(status().isFound()).andExpect(redirectedUrl("/ugnich/" + mid)); + mockMvc.perform(get("/ws/" + mid)).andExpect(status().isFound()).andExpect(redirectedUrl("/ugnich/" + mid)); } @MockBean @@ -2328,8 +2182,7 @@ public class ServerTests { public void tagStatsSpec() throws Exception { String newUserName = "tagger"; String newUserSecret = "secret"; - User newUser = userService.createUser(newUserName, newUserSecret) - .orElseThrow(IllegalStateException::new); + User newUser = userService.createUser(newUserName, newUserSecret).orElseThrow(IllegalStateException::new); commandsManager.processCommand(newUser, "*test yo", emptyUri); commandsManager.processCommand(newUser, "*test yo2", emptyUri); commandsManager.processCommand(newUser, "*rare yo3", emptyUri); @@ -2353,17 +2206,13 @@ public class ServerTests { assertThat(plainText, is(getSnapshot(testSubscriptionTextEmail))); User demo = MockUtils.mockUser(45, ugnichName, ugnichPassword); Message html = MockUtils.mockMessage(56, demo, "yo"); - String htmlText = webApp.renderHtml( - MessageUtils.formatHtml(html), - PlainTextFormatter.formatUrl(html), - html, "12345") + String htmlText = webApp + .renderHtml(MessageUtils.formatHtml(html), PlainTextFormatter.formatUrl(html), html, "12345") .orElseThrow(); assertThat(htmlText, is(getSnapshot(testSubscriptionHtmlEmail))); html.setMid(0); - String htmlPM = webApp.renderHtml( - MessageUtils.formatHtml(html), - PlainTextFormatter.formatUrl(html), - html, "12345") + String htmlPM = webApp + .renderHtml(MessageUtils.formatHtml(html), PlainTextFormatter.formatUrl(html), html, "12345") .orElseThrow(); assertThat(htmlPM, is(getSnapshot(testPrivateHtmlEmail))); } @@ -2388,7 +2237,8 @@ public class ServerTests { } @Test - public void testAppleClientSecret() throws NoSuchAlgorithmException, IOException, InvalidKeySpecException, NoSuchProviderException { + public void testAppleClientSecret() + throws NoSuchAlgorithmException, IOException, InvalidKeySpecException, NoSuchProviderException { String secret = new String(clientSecretGenerator.getClientSecret().getBytes(), StandardCharsets.UTF_8); Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter(); @@ -2400,21 +2250,18 @@ public class ServerTests { privateKey = pemConverter.getPrivateKey((PrivateKeyInfo) pemObj); - -// Generate public key from private key + // Generate public key from private key KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC"); ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1"); - ECPoint Q = ecSpec.getG().multiply(((ECPrivateKey)privateKey).getD()); + ECPoint Q = ecSpec.getG().multiply(((ECPrivateKey) privateKey).getD()); byte[] publicDerBytes = Q.getEncoded(false); ECPoint point = ecSpec.getCurve().decodePoint(publicDerBytes); ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, ecSpec); ECPublicKey publicKeyGenerated = (ECPublicKey) keyFactory.generatePublic(pubSpec); - Jws jwt = Jwts.parserBuilder() - .setSigningKey(publicKeyGenerated).build() - .parseClaimsJws(secret); + Jws jwt = Jwts.parserBuilder().setSigningKey(publicKeyGenerated).build().parseClaimsJws(secret); assertThat(jwt.getHeader().get("kid"), is("keyid")); assertThat(jwt.getHeader().get("alg"), is("ES256")); Claims claims = jwt.getBody(); @@ -2422,6 +2269,7 @@ public class ServerTests { assertThat(claims.get("sub"), is("com.example.app")); assertThat(claims.get("aud"), is("https://appleid.apple.com")); } + @Test public void linksTest() throws IOException, ParserConfigurationException, SAXException { @@ -2432,8 +2280,15 @@ public class ServerTests { SapePageLinks botLinks = new SapePageLinks(site, "ugnich", URI.create("http://localhost/"), "ugnich"); assertThat(botLinks.render(), is("")); SapePageLinks visitorLinks = new SapePageLinks(site, "ugnich", URI.create("http://localhost/"), null); - assertThat(visitorLinks.render(), is(" Тест ссылки - passed. . Тест ссылки 2 - passed. ")); + assertThat(visitorLinks.render(), is( + " Тест ссылки - passed. . Тест ссылки 2 - passed. ")); SapePageLinks emptyLinks = new SapePageLinks(site, "ugnich", URI.create("http://localhost/yo"), null); assertThat(emptyLinks.render(), is(emptyString())); } + + @Test + public void invalidMediaTypeTest() throws Exception { + mockMvc.perform(get("/api/messages").header("Accept", "application/xml")).andExpect(status().isBadRequest()) + .andExpect(content().string("Invalid media type")); + } } -- cgit v1.2.3