diff options
author | Vitaly Takmazov | 2022-10-24 01:09:32 +0300 |
---|---|---|
committer | Vitaly Takmazov | 2022-11-25 14:16:03 +0300 |
commit | 9faf43a6c4b933b5f97be4348d461bf91f5bf2e2 (patch) | |
tree | 238968b200c73d905b9367154fddb7ac3eff6274 /src/test/java/com/juick/server | |
parent | e0a98e8bd925bc5aebe49d011bb4ec17978f8bd9 (diff) |
Spring Boot 3
Diffstat (limited to 'src/test/java/com/juick/server')
-rw-r--r-- | src/test/java/com/juick/server/tests/ServerTests.java | 668 |
1 files changed, 430 insertions, 238 deletions
diff --git a/src/test/java/com/juick/server/tests/ServerTests.java b/src/test/java/com/juick/server/tests/ServerTests.java index da777a92..69622387 100644 --- a/src/test/java/com/juick/server/tests/ServerTests.java +++ b/src/test/java/com/juick/server/tests/ServerTests.java @@ -36,6 +36,7 @@ import static org.hamcrest.collection.IsEmptyCollection.empty; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.util.AssertionErrors.assertNotEquals; import static org.springframework.test.web.client.ExpectedCount.times; @@ -91,11 +92,6 @@ import java.util.stream.IntStream; import java.util.stream.StreamSupport; import javax.inject.Inject; -import javax.servlet.http.Cookie; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; @@ -168,9 +164,9 @@ import com.juick.www.api.activity.model.objects.Note; import com.juick.www.api.activity.model.objects.Person; import com.juick.www.api.webfinger.model.Account; import com.juick.www.api.xnodeinfo2.model.NodeInfo; -import com.mitchellbosecke.pebble.PebbleEngine; -import com.mitchellbosecke.pebble.error.PebbleException; -import com.mitchellbosecke.pebble.template.PebbleTemplate; +import io.pebbletemplates.pebble.PebbleEngine; +import io.pebbletemplates.pebble.error.PebbleException; +import io.pebbletemplates.pebble.template.PebbleTemplate; import com.overzealous.remark.Remark; import org.apache.commons.collections4.CollectionUtils; @@ -232,6 +228,11 @@ import org.xml.sax.SAXException; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; +import jakarta.servlet.http.Cookie; +import jakarta.xml.bind.JAXBContext; +import jakarta.xml.bind.JAXBException; +import jakarta.xml.bind.Marshaller; +import jakarta.xml.bind.Unmarshaller; import rocks.xmpp.addr.Jid; import rocks.xmpp.core.session.Extension; import rocks.xmpp.core.session.XmppSession; @@ -376,8 +377,10 @@ public class ServerTests { ugnichPassword = "secret"; freefdName = "freefd"; freefdPassword = "MyPassw0rd!"; - ugnich = userService.createUser(ugnichName, ugnichPassword).orElseThrow(IllegalStateException::new); - freefd = userService.createUser(freefdName, freefdPassword).orElseThrow(IllegalStateException::new); + ugnich = userService.createUser(ugnichName, ugnichPassword) + .orElseThrow(IllegalStateException::new); + freefd = userService.createUser(freefdName, freefdPassword) + .orElseThrow(IllegalStateException::new); webClient.getOptions().setJavaScriptEnabled(false); webClient.getOptions().setCssEnabled(false); isSetUp = true; @@ -412,7 +415,8 @@ public class ServerTests { assertThat(messagesService.getMyFeed(freefd.getUid(), mid2, true).get(0), equalTo(mid0)); assertThat(messagesService.recommendMessage(mid0, ugnich.getUid()), equalTo(MessagesService.RecommendStatus.Added)); - assertThat(messagesService.getMessage(mid0).orElseThrow(IllegalStateException::new).getRecommendations().size(), equalTo(1)); + assertThat(messagesService.getMessage(mid0).orElseThrow(IllegalStateException::new).getRecommendations() + .size(), equalTo(1)); assertThat(messagesService.recommendMessage(mid0, ugnich.getUid()), equalTo(MessagesService.RecommendStatus.Deleted)); assertThat(messagesService.getMessage(mid0).get().getRecommendations().size(), equalTo(0)); @@ -424,7 +428,8 @@ public class ServerTests { List<User> subscribers = subscriptionService.getSubscribedUsers(ugnich.getUid(), msg); telegramService.createTelegramUser(12345, "freefd"); - String loginhash = jdbcTemplate.queryForObject("SELECT loginhash FROM telegram where tg_id=?", String.class, + String loginhash = jdbcTemplate.queryForObject("SELECT loginhash FROM telegram where tg_id=?", + String.class, 12345); userService.setTelegramUser(loginhash, freefd.getUid()); @@ -503,7 +508,8 @@ public class ServerTests { 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()); + .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); @@ -511,7 +517,8 @@ public class ServerTests { Tag htmlTag = tagService.getTag(htmlTagName, true); TagStats htmlTagStats = new TagStats(); htmlTagStats.setTag(htmlTag); - String dbTagName = jdbcTemplate.queryForObject("select name from tags where name=?", String.class, htmlTagName); + String dbTagName = jdbcTemplate.queryForObject("select name from tags where name=?", String.class, + htmlTagName); assertEquals(dbTagName, htmlTag.getName()); int mid4 = messagesService.createMessage(user.getUid(), "yoyoyo", null, Set.of()); Message msg4 = messagesService.getMessage(mid4).get(); @@ -564,8 +571,10 @@ public class ServerTests { @Test public void lastEmailShouldNotBeDeleted() { User hugnich3 = userService.createUser("hugnich3", "x").orElseThrow(IllegalStateException::new); - jdbcTemplate.update("INSERT INTO emails(user_id,email) VALUES(?,?)", hugnich3.getUid(), "first@localhost"); - jdbcTemplate.update("INSERT INTO emails(user_id,email) VALUES(?,?)", hugnich3.getUid(), "second@localhost"); + jdbcTemplate.update("INSERT INTO emails(user_id,email) VALUES(?,?)", hugnich3.getUid(), + "first@localhost"); + jdbcTemplate.update("INSERT INTO emails(user_id,email) VALUES(?,?)", hugnich3.getUid(), + "second@localhost"); emailService.addEmail(hugnich3.getUid(), "test@email.example.com"); assertThat(emailService.getNotificationsEmail(hugnich3.getUid()), is("test@email.example.com")); emailService.disableEmail(hugnich3, "test@email.example.com"); @@ -580,11 +589,13 @@ public class ServerTests { User hugnich4 = userService.createUser("hugnich4", "x").orElseThrow(IllegalStateException::new); int mid = messagesService.createMessage(hugnich4.getUid(), "yo", null, Set.of()); Instant ts = jdbcTemplate - .queryForObject("SELECT updated FROM messages WHERE message_id=?", Timestamp.class, mid).toInstant(); + .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(); + .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())); @@ -618,19 +629,23 @@ public class ServerTests { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$[0].mid", is(msg.getMid()))) .andExpect(jsonPath("$[0].timestamp", - is(DateFormattersHolder.getMessageFormatterInstance().format(msg.getCreated())))) + is(DateFormattersHolder.getMessageFormatterInstance() + .format(msg.getCreated())))) .andExpect(jsonPath("$[0].body", is(msg.getText()))) .andExpect(jsonPath("$[0].attachment.url", 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)))); + 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)))); } @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()); @@ -641,8 +656,10 @@ public class ServerTests { @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", "*")); + 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", "*")); } @@ -650,11 +667,15 @@ public class ServerTests { @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()) + .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")); + .andExpect(header().string("Access-Control-Allow-Methods", + "POST,GET,PUT,OPTIONS,DELETE")) + .andExpect(header().string("Access-Control-Allow-Headers", + "X-PINGOTHER, Content-Type")); } @Test @@ -662,8 +683,10 @@ public class ServerTests { 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 @@ -680,11 +703,14 @@ public class ServerTests { 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))); + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.length()", is(7))); } @Test @@ -697,14 +723,16 @@ public class ServerTests { List<TagStats> tagsFromApi = jsonMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<>() { }); - TagStats yoStats = tagsFromApi.stream().filter(t -> t.getTag().getName().equals("yo")).findFirst().get(); + 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(); List<TagStats> ugnichTagsFromApi = jsonMapper.readValue(result2.getResponse().getContentAsString(), new TypeReference<>() { }); - TagStats yoUgnichStats = ugnichTagsFromApi.stream().filter(t -> t.getTag().getName().equals("yo")).findFirst() + TagStats yoUgnichStats = ugnichTagsFromApi.stream().filter(t -> t.getTag().getName().equals("yo")) + .findFirst() .get(); assertThat(yoUgnichStats.getUsageCount(), is(1)); } @@ -717,7 +745,8 @@ public class ServerTests { @Test public void threadWithEphemeralNumberShouldReturn404() throws Exception { - mockMvc.perform(get("/api/thread").param("mid", "999999999").with(httpBasic(ugnichName, ugnichPassword))) + mockMvc.perform(get("/api/thread").param("mid", "999999999") + .with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().is4xxClientError()); } @@ -743,10 +772,13 @@ 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(serviceUser.getName(), "password"))).andExpect(status().isOk()).andReturn(); - List<User> users = jsonMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<>() { - }); + MvcResult result = mockMvc + .perform(get("/api/notifications").param("uid", String.valueOf(ugnich.getUid())) + .with(httpBasic(serviceUser.getName(), "password"))) + .andExpect(status().isOk()).andReturn(); + List<User> 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)); @@ -754,7 +786,8 @@ public class ServerTests { @Test public void tg2juickLinks() { - UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://juick.com/m/123456#23").build(); + UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://juick.com/m/123456#23") + .build(); assertThat(uriComponents.getPath().substring(3), is("123456")); assertThat(uriComponents.getFragment(), is("23")); } @@ -778,7 +811,8 @@ public class ServerTests { .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()))) + get("/api/notifications").param("mid", stringValueOfMid).param("uid", + String.valueOf(ugnich.getUid()))) .andExpect(status().isUnauthorized()); } @@ -846,10 +880,12 @@ public class ServerTests { @Test public void botCommandsTests() throws Exception { - assertThat(commandsManager.processCommand(AnonymousUser.INSTANCE, "PING", emptyUri).getText(), is("PONG")); + 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, + commandsManager.processCommand(AnonymousUser.INSTANCE, "help", emptyUri).getText() + .split("\n").length, is(32)); } @@ -859,12 +895,14 @@ public class ServerTests { 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")) + .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)) + .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()); @@ -875,28 +913,35 @@ public class ServerTests { 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, + 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); + 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"), + 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"), + 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)) + .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)) + .getUsersSubscribedToComments(messagesService.getMessage(mid).get(), + messagesService.getReply(mid, rid)) .size()); assertEquals(1, subscriptionService.getUsersSubscribedToComments(messagesService.getMessage(mid).get(), messagesService.getReply(mid, rid), true).size()); @@ -908,13 +953,15 @@ public class ServerTests { 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")) + .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, + Timestamp lastreply = jdbcTemplate.queryForObject("SELECT lastmessage FROM users WHERE id=?", + Timestamp.class, user.getUid()); assertThat(lastreply.toInstant(), equalTo(reply.getCreated())); assertEquals(2, reply.getReplyto()); @@ -930,10 +977,12 @@ public class ServerTests { 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); + 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("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(); @@ -945,7 +994,8 @@ public class ServerTests { assertEquals("Unsubscribed from #" + mid, commandsManager.processCommand(readerUser, "u #" + mid, emptyUri).getText()); assertEquals(0, subscriptionService - .getUsersSubscribedToComments(messagesService.getMessage(mid).get(), messagesService.getReply(mid, rid)) + .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()); @@ -954,12 +1004,14 @@ public class ServerTests { 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(); + Message codeAndTagsMessage = commandsManager.processCommand(user, codeAndTags, emptyUri).getNewMessage() + .get(); Set<Tag> codeAndTagsTags = codeAndTagsMessage.getTags(); 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); + 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, @@ -967,12 +1019,14 @@ public class ServerTests { 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" + "<https://juick.com/settings?hash=VTYZkKV8FWkmu6g1>", + "I'm very smart to post my login url there" + + "<https://juick.com/settings?hash=VTYZkKV8FWkmu6g1>", emptyUri); assertThat(result.getNewMessage().isPresent(), is(true)); assertFalse(result.getNewMessage().get().getText().contains("VTYZkKV8FWkmu6g1")); result = commandsManager.processCommand(user, - "*корм *juick_ppl *рационализм *? *мюсли а сколько микроморт в дневной порции сверхмюслей?", emptyUri); + "*корм *juick_ppl *рационализм *? *мюсли а сколько микроморт в дневной порции сверхмюслей?", + emptyUri); assertThat(result.getNewMessage().isPresent(), is(true)); String tags = "*Juick *Google *Google Play"; String data = "Вчера отправлял *NSFW постинг в топ :)"; @@ -983,7 +1037,8 @@ public class ServerTests { data = "* \u043c\u0443\u0441\u043e\u0440\\n\u0423 \u043c\u0435\u043d\u044f \u043a\u0430\u0436\u0434\u0443\u044e \u043d\u0435\u0434\u0435\u043b\u044e \u0441\u043e\u0431\u0438\u0440\u0430\u0435\u0442\u0441\u044f \u043f\u043e 4-5 \u0431\u0443\u0442\u044b\u043b\u043e\u043a 1,5\u043b \u041f\u0415\u0422. \u041c\u043d\u0435 \u0433\u0435\u043c\u043e\u0440\u043d\u043e \u0441\u043e\u0431\u0438\u0440\u0430\u0442\u044c \u043f\u043e \u043a\u0438\u043b\u043e\u0433\u0440\u0430\u043c\u043c\u0443 \u0438\u043b\u0438 \u043f\u043e 5\u043a\u0433 \u044d\u0442\u043e\u0433\u043e \u043c\u0443\u0441\u043e\u0440\u0430, \u0447\u0442\u043e\u0431\u044b \u0432\u0435\u0437\u0442\u0438 \u0435\u0433\u043e \u0435\u0449\u0435 \u043a\u0443\u0434\u0430-\u0442\u043e.\\n\u041d\u0435, \u043d\u0443 \u0435\u0441\u0442\u044c \u043b\u044e\u0434\u0438, \u043a\u043e\u0442\u043e\u0440\u044b\u0435 \u0441\u043e\u0431\u0438\u0440\u0430\u044e\u0442 \u0432\u0442\u043e\u0440\u0441\u044b\u0440\u044c\u0435 \u043f\u043e \u043c\u0443\u0441\u043e\u0440\u043a\u0430\u043c, \u0441\u0432\u0430\u043b\u043a\u0430\u043c, \u043f\u043e\u0442\u043e\u043c\u0443 \u0447\u0442\u043e \u0434\u0435\u043d\u044c\u0433\u0438 \u043d\u0443\u0436\u043d\u044b. \u0418 \u0431\u044b\u0432\u0430\u044e\u0442 \u0441\u0442\u043e\u044f\u0442 \u043a\u043e\u043d\u0442\u0435\u0439\u043d\u0435\u0440\u044b-\u043a\u043b\u0435\u0442\u043a\u0438 \u0434\u043b\u044f \u043f\u043b\u0430\u0441\u0442\u0438\u043a\u0430, \u043d\u043e \u0442\u0430\u043a \u043a\u0430\u043a \u043c\u0443\u0441\u043e\u0440 \u0432\u044b\u0432\u043e\u0437\u044f\u0442 \u043d\u0435 \u0447\u0430\u0441\u0442\u043e \u0438\u043b\u0438 \u043b\u044e\u0434\u0438 \u0432\u043d\u0435\u0437\u0430\u043f\u043d\u043e \u0432\u044b\u043a\u0438\u0434\u044b\u0432\u0430\u044e\u0442 \u043c\u043d\u043e\u0433\u043e \u043c\u0443\u0441\u043e\u0440\u0430, \u0442\u043e \u0432 \u0442\u043e\u0439 \u043a\u043b\u0435\u0442\u043a\u0435 \u0442\u043e\u0442 \u043c\u0443\u0441\u043e\u0440, \u0447\u0442\u043e \u043d\u0435 \u043f\u043e\u043c\u0435\u0441\u0442\u0438\u043b\u0441\u044f \u0432 \u043e\u0431\u044b\u0447\u043d\u044b\u0445 \u043a\u043e\u043d\u0442\u0435\u0439\u043d\u0435\u0440\u0430\u0445."; result = commandsManager.processCommand(user, String.format("%s %s", tags, data), emptyUri); assertThat(result.getNewMessage().get().getTags().size(), equalTo(2)); - assertThat(result.getNewMessage().get().getTags().stream().findFirst().get().getName(), equalTo("Киев")); + assertThat(result.getNewMessage().get().getTags().stream().findFirst().get().getName(), + equalTo("Киев")); assertThat(result.getNewMessage().get().getText(), equalTo(data)); result = commandsManager.processCommand(user, "S @unknown-user", emptyUri); assertThat(result.getNewMessage(), is(Optional.empty())); @@ -995,28 +1050,37 @@ public class ServerTests { emailService.addEmail(ugnich.getUid(), "ugnich@example.com"); int mid = messagesService.createMessage(ugnich.getUid(), "text", StringUtils.EMPTY, Set.of()); 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" + "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" + + "Date: Fri, 16 Mar 2018 15:31:50 +0300\n" + + "Delivered-To: ugnich@example.com\n" + "Message-ID: <CAF+0zPD_YLVgYovajLqUFwkRAgJT+FzyQ2EzikQsPKsrnfKv-Q@mail.gmail.com>\n" - + "Subject: Re: New reply to TJ\n" + "From: Ugnich <ugnich@example.com>\n" + + "Subject: Re: New reply to TJ\n" + + "From: Ugnich <ugnich@example.com>\n" + "To: Juick <juick@juick.com>\n" - + "Content-Type: multipart/alternative; boundary=\"001a11454886e42be5056786ca70\"\n" + "\n" - + "--001a11454886e42be5056786ca70\n" + "Content-Type: text/plain; charset=\"UTF-8\"\n" + "\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" + "<div dir=\"ltr\">s2313334</div>\n" + + "Content-Type: text/html; charset=\"UTF-8\"\n" + "\n" + + "<div dir=\"ltr\">s2313334</div>\n" + "\n" + "--001a11454886e42be5056786ca70--", mid, mid); mockMvc.perform(post("/api/mail").with(httpBasic(serviceUser.getName(), "password")).content(mail)) .andExpect(status().isOk()); - String reply = "Return-Path: <ugnich@example.com>\n" + "Received: from [192.168.88.140] ([91.244.168.38])\n" + String reply = "Return-Path: <ugnich@example.com>\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 <juick@juick.com>\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 <ugnich@example.com>\n" + + " Thu, 20 Jun 2019 08:39:54 -0700 (PDT)\n" + + "From: Ugnich <ugnich@example.com>\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" + + "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: <CAF+0zPD_YLVgYovajLqUFwkRAgJT+FzyQ2EzikQsPKsrnfKv-Q@mail.gmail.com>\n" + "To: juick@juick.com\n" + "X-Mailer: iPhone Mail (16F203)\n" + "\n" @@ -1038,12 +1102,14 @@ public class ServerTests { 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()); messagesService.createReply(mid, 0, freefd, "reply", null); mockMvc.perform(get("/api/thread?mid=" + mid + "&hash=" + freefdHash)).andExpect(status().isOk()) .andExpect(jsonPath("$.length()", is(2))) .andExpect(jsonPath("$[0].replies", is(1))); - mockMvc.perform(get("/api/thread?mid=" + mid + "&hash=" + freefdHash + "&showReplies=false")).andExpect(status().isOk()) + mockMvc.perform(get("/api/thread?mid=" + mid + "&hash=" + freefdHash + "&showReplies=false")) + .andExpect(status().isOk()) .andExpect(jsonPath("$.length()", is(1))) .andExpect(jsonPath("$[0].replies", is(1))); } @@ -1060,7 +1126,8 @@ public class ServerTests { Message msg4 = messagesService.getMessage(mid1).get(); assertThat(msg4.getRecommendations().size(), is(0)); assertThat( - messagesService.getMessages(AnonymousUser.INSTANCE, Collections.singletonList(mid1)).get(0).getRecommendations().size(), + messagesService.getMessages(AnonymousUser.INSTANCE, Collections.singletonList(mid1)) + .get(0).getRecommendations().size(), is(0)); assertEquals(1, msg4.getReactions().stream().filter(r -> r.getId() == 2).findFirst() .orElseThrow(IllegalStateException::new).getCount()); @@ -1081,12 +1148,14 @@ public class ServerTests { subscriptionService.subscribeMessage(messagesService.getMessage(mid).get(), ugnich); messagesService.createReply(mid, 0, freefd, "new reply", null); BiFunction<User, Integer, Integer> lastRead = (user, m) -> jdbcTemplate.queryForObject( - "SELECT last_read_rid FROM subscr_messages WHERE suser_id=? AND message_id=?", Integer.class, + "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)); - assertThat(messagesService.getMessages(ugnich, Collections.singletonList(mid)).get(0).isUnread(), is(true)); + assertThat(messagesService.getMessages(ugnich, Collections.singletonList(mid)).get(0).isUnread(), + is(true)); messagesService.getReplies(ugnich, mid); assertThat(lastRead.apply(ugnich, mid), is(1)); assertThat(messagesService.getUnread(ugnich).size(), is(0)); @@ -1094,7 +1163,8 @@ public class ServerTests { assertThat(lastRead.apply(ugnich, mid), is(1)); String ugnichHash = userService.getHashByUID(ugnich.getUid()); int freefdrid = messagesService.createReply(mid, 0, freefd, "again", null); - mockMvc.perform(get(String.format("/api/thread/mark_read/%d-%d.gif?hash=%s", mid, freefdrid, ugnichHash))) + mockMvc.perform(get( + String.format("/api/thread/mark_read/%d-%d.gif?hash=%s", mid, freefdrid, ugnichHash))) .andExpect(status().isOk()) .andExpect(content().bytes(IOUtils.toByteArray(invisiblePixel.getInputStream()))); assertThat(lastRead.apply(ugnich, mid), is(freefdrid)); @@ -1109,7 +1179,8 @@ 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)); } @@ -1118,72 +1189,87 @@ public class ServerTests { Tag banned = tagService.getTag("banned", true); int mid = messagesService.createMessage(ugnich.getUid(), "yo", "jpg", Set.of(banned)); privacyQueriesService.blacklistTag(freefd, banned); - assertThat(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getAll(freefd.getUid(), 0)) + assertThat(messagesService + .getMessages(AnonymousUser.INSTANCE, messagesService.getAll(freefd.getUid(), 0)) .stream().noneMatch(m -> m.getTags().contains(banned)), is(true)); - assertFalse(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getAll(ugnich.getUid(), 0)) + assertFalse(messagesService + .getMessages(AnonymousUser.INSTANCE, messagesService.getAll(ugnich.getUid(), 0)) .stream().noneMatch(m -> m.getTags().contains(banned))); - assertThat(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getPhotos(freefd.getUid(), 0)) + assertThat(messagesService + .getMessages(AnonymousUser.INSTANCE, messagesService.getPhotos(freefd.getUid(), 0)) .stream().noneMatch(m -> m.getTags().contains(banned)), is(true)); - assertFalse(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getPhotos(ugnich.getUid(), 0)) + assertFalse(messagesService + .getMessages(AnonymousUser.INSTANCE, messagesService.getPhotos(ugnich.getUid(), 0)) .stream().noneMatch(m -> m.getTags().contains(banned))); messagesService.recommendMessage(mid, serviceUser.getUid()); assertThat(messagesService .getMessages(AnonymousUser.INSTANCE, - messagesService.getUserBlogWithRecommendations(serviceUser, freefd, 0, 0)) + messagesService.getUserBlogWithRecommendations(serviceUser, freefd, 0, + 0)) .stream().noneMatch(m -> m.getTags().contains(banned)), is(true)); assertFalse(messagesService .getMessages(AnonymousUser.INSTANCE, - messagesService.getUserBlogWithRecommendations(serviceUser, ugnich, 0, 0)) + messagesService.getUserBlogWithRecommendations(serviceUser, ugnich, 0, + 0)) .stream().noneMatch(m -> m.getTags().contains(banned))); assertThat( - messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getMyFeed(freefd.getUid(), 0, true)) + 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, Set.of(banned)); messagesService.recommendMessage(newMid, ugnich.getUid()); assertThat( - messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getMyFeed(freefd.getUid(), 0, true)) + 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)); - } - - @Test - public void tagsShouldBeDeserializedFromXml() throws JAXBException { - XmppSessionConfiguration configuration = XmppSessionConfiguration.builder() - .extensions(Extension.of(Message.class)).build(); - XmppSession xmpp = new XmppSession("juick.com", configuration) { - @Override - public void connect(Jid from) { - - } - - @Override - public Jid getConnectedResource() { - return null; - } - }; - String tag = "<tag xmlns='http://juick.com/message'>yo</tag>"; - String xml = "<message xmlns='jabber:client' from='juick@juick.com' type='chat'><body>yo</body><juick mid='1' ts='2017-09-14' uid='1' uname='ugnich' xmlns='http://juick.com/message'><body>yo</body><user uid='1' uname='ugnich' xmlns='http://juick.com/user'/><tag>yo</tag><tag>people</tag></juick></message>"; - Unmarshaller unmarshaller = xmpp.createUnmarshaller(); - 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); - List<Tag> tags = new ArrayList<>(juickMessage.getTags()); - assertThat(tags.get(0).getName(), equalTo("yo")); + 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(); + * XmppSession xmpp = new XmppSession("juick.com", configuration) { + * + * @Override + * public void connect(Jid from) { + * + * } + * + * @Override + * public Jid getConnectedResource() { + * return null; + * } + * }; + * String tag = "<tag xmlns='http://juick.com/message'>yo</tag>"; + * String xml = + * "<message xmlns='jabber:client' from='juick@juick.com' type='chat'><body>yo</body><juick mid='1' ts='2017-09-14' uid='1' uname='ugnich' xmlns='http://juick.com/message'><body>yo</body><user uid='1' uname='ugnich' xmlns='http://juick.com/user'/><tag>yo</tag><tag>people</tag></juick></message>" + * ; + * Unmarshaller unmarshaller = xmpp.createUnmarshaller(); + * 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); + * List<Tag> tags = new ArrayList<>(juickMessage.getTags()); + * assertThat(tags.get(0).getName(), equalTo("yo")); + * } + */ @Test public void messageParserSerializer() throws Exception { String tagsString = "test test" + (char) 0xA0 + "2 test 3"; Set<Tag> tags = MessageUtils.parseTags(tagsString); - List<Tag> tagList = tags.stream().map(t -> tagService.getTag(t.getName(), true)).collect(Collectors.toList()); + List<Tag> 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()); @@ -1194,7 +1280,8 @@ public class ServerTests { map.add("body", "*test *test 2 *test 3 YO"); map.add("hash", userService.getHashByUID(ugnich.getUid())); - ResponseEntity<CommandResult> result = restTemplate.postForEntity("/api/post", request, CommandResult.class); + ResponseEntity<CommandResult> result = restTemplate.postForEntity("/api/post", request, + CommandResult.class); assertThat(result.getStatusCode(), is(HttpStatus.OK)); Message msg = result.getBody().getNewMessage().orElseThrow(); Instant currentDate = msg.getCreated(); @@ -1218,7 +1305,8 @@ public class ServerTests { MvcResult apiResult = mockMvc.perform(get("/api/thread?mid=" + msg.getMid())).andExpect(status().isOk()) .andReturn(); - List<Message> fromApi = jsonMapper.readValue(apiResult.getResponse().getContentAsString(StandardCharsets.UTF_8), + List<Message> fromApi = jsonMapper.readValue( + apiResult.getResponse().getContentAsString(StandardCharsets.UTF_8), new TypeReference<>() { }); assertThat(fromApi.get(0).getTags(), is(tags)); @@ -1251,7 +1339,8 @@ public class ServerTests { 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))) + .andExpect(jsonPath("$.hash", is(hash))) + .andExpect(jsonPath("$.readers.length()", is(1))) .andExpect(jsonPath("$.read.length()", is(1))); } @@ -1262,7 +1351,8 @@ public class ServerTests { int mid = result.getNewMessage().get().getMid(); commandsManager.processCommand(freefd, String.format("#%d ugnich - dick too", mid), emptyUri); commandsManager.processCommand(serviceUser, String.format("#%d/1 ban for a hour!", mid), emptyUri); - commandsManager.processCommand(serviceUser, String.format("#%d freefd is here but it is hidden from you", mid), + commandsManager.processCommand(serviceUser, + 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); @@ -1274,8 +1364,8 @@ public class ServerTests { replies = messagesService.getReplies(ugnich, mid); assertThat(replies.size(), is(1)); mockMvc.perform(get("/api/thread").with(httpBasic(ugnichName, ugnichPassword)).param("mid", - String.valueOf(mid))) - .andExpect(jsonPath("$[0].replies", is(1))); + String.valueOf(mid))) + .andExpect(jsonPath("$[0].replies", is(1))); commandsManager.processCommand(serviceUser, String.format("#%d/4 mmm?!", mid), emptyUri); assertThat(messagesService.getMessage(mid).get().getReplies(), is(5)); replies = messagesService.getReplies(ugnich, mid); @@ -1295,7 +1385,8 @@ public class ServerTests { assertThat(messagesService.getTag(tag.TID, freefd.getUid(), 0, 10).size(), is(1)); assertThat(messagesService.getTag(tag.TID, ugnich.getUid(), 0, 10).size(), is(0)); messagesService.recommendMessage(freefdMsg, serviceUser.getUid()); - assertThat(messagesService.getUserBlogWithRecommendations(serviceUser, ugnich, 0, 0).contains(freefdMsg), + assertThat(messagesService.getUserBlogWithRecommendations(serviceUser, ugnich, 0, 0) + .contains(freefdMsg), is(false)); commandsManager.processCommand(ugnich, "BL @freefd", emptyUri); } @@ -1340,7 +1431,8 @@ public class ServerTests { 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")); + CommandResult postJpgiPhone = commandsManager.processCommand(ugnich, "YO", + URI.create("juick://2915104.jpg")); assertThat(postJpgiPhone.getNewMessage().isPresent(), is(true)); int mid = postJpgiPhone.getNewMessage().get().getMid(); File originalFile = Paths.get(imgDir, "p", String.format("%d.jpg", mid)).toFile(); @@ -1384,7 +1476,8 @@ public class ServerTests { @Test public void messageEditingSpec() throws Exception { MvcResult result = mockMvc - .perform(post("/api/post").with(httpBasic(ugnichName, ugnichPassword)).param("body", "YO")) + .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(); @@ -1394,7 +1487,8 @@ public class ServerTests { Thread.sleep(1000); result = mockMvc .perform(post("/api/update").with(httpBasic(ugnichName, ugnichPassword)) - .param("mid", String.valueOf(original.getMid())).param("body", "PEOPLE")) + .param("mid", String.valueOf(original.getMid())) + .param("body", "PEOPLE")) .andExpect(status().is2xxSuccessful()).andReturn(); Message edited = jsonMapper.readValue(result.getResponse().getContentAsString(), CommandResult.class) .getNewMessage().get(); @@ -1405,36 +1499,45 @@ public class ServerTests { 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)); + .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); + 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())); + 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")) + .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) + Message editedComment = jsonMapper + .readValue(result.getResponse().getContentAsString(), CommandResult.class) .getNewMessage().get(); assertThat(editedComment.getText(), is("HEY, JOE")); assertThat(editedComment.getUpdatedAt(), greaterThan(editedComment.getCreated())); - jdbcTemplate.update("UPDATE replies SET updated_at='1990-05-05 00:00:00' WHERE message_id=? AND reply_id=?", + jdbcTemplate.update( + "UPDATE replies SET updated_at='1990-05-05 00:00:00' WHERE message_id=? AND reply_id=?", editedComment.getMid(), editedComment.getRid()); Message updatedComment = comment.getNewMessage().get(); result = mockMvc .perform(post("/api/update").with(httpBasic(freefdName, freefdPassword)) .param("mid", String.valueOf(updatedComment.getMid())) - .param("rid", String.valueOf(updatedComment.getRid())).param("body", "HEY, JOE AGAIN")) + .param("rid", String.valueOf(updatedComment.getRid())) + .param("body", "HEY, JOE AGAIN")) .andExpect(status().isBadRequest()).andReturn(); - assertThat(messagesService.deleteReply(ugnich.getUid(), updatedComment.getMid(), updatedComment.getRid()), + assertThat(messagesService.deleteReply(ugnich.getUid(), updatedComment.getMid(), + updatedComment.getRid()), is(false)); - assertThat(messagesService.deleteReply(freefd.getUid(), updatedComment.getMid(), updatedComment.getRid()), + assertThat(messagesService.deleteReply(freefd.getUid(), updatedComment.getMid(), + updatedComment.getRid()), is(true)); assertThat(messagesService.getReply(updatedComment.getMid(), updatedComment.getRid()).getUser(), is(archiveUser)); @@ -1451,7 +1554,8 @@ public class ServerTests { @Test public void subscribersToRecommendations() { User reader = userService.createUser("reader", "123456").orElseThrow(IllegalStateException::new); - User recommender = userService.createUser("recommender", "123456").orElseThrow(IllegalStateException::new); + User recommender = userService.createUser("recommender", "123456") + .orElseThrow(IllegalStateException::new); User lateRecommender = userService.createUser("lateRecommender", "123456") .orElseThrow(IllegalStateException::new); User poster = userService.createUser("poster", "123456").orElseThrow(IllegalStateException::new); @@ -1468,20 +1572,25 @@ public class ServerTests { assertThat(recommendSubscribers.size(), is(1)); assertThat(recommendSubscribers.get(0).getUid(), is(reader.getUid())); privacyQueriesService.blacklistUser(reader, poster); - assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()).size(), is(0)); + assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()).size(), + is(0)); privacyQueriesService.blacklistUser(reader, poster); - assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()).size(), is(1)); + assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()).size(), + is(1)); tagService.blacklistTag(reader, sampleTag); - assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()).size(), is(0)); + assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()).size(), + is(0)); tagService.blacklistTag(reader, sampleTag); - assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()).size(), is(1)); + assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()).size(), + is(1)); messagesService.recommendMessage(posterMid, lateRecommender.getUid()); List<User> lateRecommendSubscribers = subscribers.apply(recommender.getUid(), messagesService.getMessage(posterMid).get()); assertThat(lateRecommendSubscribers.size(), is(0)); int readerMid = messagesService.createMessage(reader.getUid(), "PEOPLE", null, Set.of()); messagesService.recommendMessage(readerMid, recommender.getUid()); - assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(readerMid).get()).size(), is(0)); + assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(readerMid).get()).size(), + is(0)); } @Test @@ -1548,28 +1657,35 @@ public class ServerTests { User isilmine = userService.createUser(userName, userPassword).orElseThrow(IllegalStateException::new); int mid = messagesService.createMessage(isilmine.getUid(), msgText, null, Set.of()); - mockMvc.perform(get(String.format("/api/thread?mid=%d", mid)).with(httpBasic(ugnichName, ugnichPassword))) + mockMvc.perform(get(String.format("/api/thread?mid=%d", mid)) + .with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().isOk()); jdbcTemplate.update("UPDATE users SET banned=1 WHERE id=?", isilmine.getUid()); - mockMvc.perform(get(String.format("/api/thread?mid=%d", mid)).with(httpBasic(ugnichName, ugnichPassword))) + mockMvc.perform(get(String.format("/api/thread?mid=%d", mid)) + .with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().isNotFound()); mockMvc.perform(get("/api/messages?uname=isilmine").with(httpBasic(ugnichName, ugnichPassword))) .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 public void emptyPasswordMeansUserIsDisabled() throws Exception { String userName = "oldschooluser"; String userPassword = ""; - 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(get("/api/auth").with(httpBasic(userName, userPassword))) + .andExpect(status().isUnauthorized()); + mockMvc.perform( + post("/login") + .with(csrf()) + .param("username", userName) + .param("password", userPassword)) + .andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/login?error=1")); } @Test @@ -1580,9 +1696,12 @@ public class ServerTests { User pogo = userService.createUser("pogo", "secret").orElseThrow(IllegalStateException::new); User fmap = userService.createUser("fmap", "secret").orElseThrow(IllegalStateException::new); int mid = messagesService.createMessage(monstreek.getUid(), "KURWA", null, Set.of()); - 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)); + assertThat(messagesService.recommendMessage(mid, ermine.getUid()), + is(MessagesService.RecommendStatus.Added)); + assertThat(messagesService.recommendMessage(mid, fmap.getUid()), + is(MessagesService.RecommendStatus.Added)); + assertThat(messagesService.recommendMessage(mid, pogo.getUid()), + is(MessagesService.RecommendStatus.Added)); jdbcTemplate.update("INSERT INTO favorites(user_id, user_uri, message_id, like_id, ts) " + "values (0, 'http://example.com/u/test', ?, 1, now())", mid); assertThat(messagesService.getMessage(mid).get().getRecommendations().size(), is(4)); @@ -1590,7 +1709,8 @@ public class ServerTests { 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().getRecommendations().size(), is(3)); assertThat(CollectionUtils.isEqualCollection( messagesService.getMessagesRecommendations(Collections.singletonList(mid)).stream() @@ -1616,10 +1736,12 @@ public class ServerTests { 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(), + 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)); + assertThat(messagesService.getMessages(banned, Collections.singletonList(mid)).get(0).getReplies(), + is(2)); } @Test @@ -1628,7 +1750,8 @@ public class ServerTests { .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 @@ -1636,18 +1759,21 @@ public class ServerTests { 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()) - .andExpect(jsonPath("$.icon.url", is(String.format("http://localhost:8080/av-96-%s.png", hash)))) + .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<Integer> mids = IteratorUtils.toList(IntStream.rangeClosed(1, 30) .mapToObj( - i -> messagesService.createMessage(ugnich.getUid(), String.format("message %d", i), null, Set.of())) + i -> messagesService.createMessage(ugnich.getUid(), + String.format("message %d", i), null, Set.of())) .collect(Collectors.toCollection(ArrayDeque::new)).descendingIterator()); List<Integer> 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)))); + is("http://localhost:8080/u/ugnich/blog?before=" + + midsPage.get(midsPage.size() - 1)))); } @Test @@ -1662,12 +1788,15 @@ public class ServerTests { public void repliesList() throws IOException { int mid = messagesService.createMessage(ugnich.getUid(), "hello", null, Set.of()); IntStream.range(1, 15) - .forEach(i -> messagesService.createReply(mid, i - 1, freefd, String.valueOf(i - 1), null)); + .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 -> { + .stream(threadPage.getHtmlElementById("replies").getChildElements().spliterator(), + false) + .filter(e -> { StyleElement display = e.getStyleElement("display"); return display == null || !display.getValue().equals("none"); }).count(); @@ -1681,12 +1810,13 @@ public class ServerTests { int mid = messagesService.createMessage(ugnich.getUid(), "freefd bl me", null, Set.of()); messagesService.createReply(mid, 0, ugnich, "yo", null); MvcResult loginResult = mockMvc - .perform(post("/login").param("username", freefdName).param("password", freefdPassword)) + .perform(post("/login").with(csrf()).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)); @@ -1706,7 +1836,8 @@ 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("<a class=\"hashtag\" href=\"/ugnich/?tag=%3E_%3C\">>_<</a>")); } @@ -1714,7 +1845,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() + return page.getElementsByTagName("meta").stream().filter(t -> t.getAttribute("name").equals(name)) + .findFirst() .orElse(emptyMeta); } @@ -1743,7 +1875,7 @@ public class ServerTests { .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)) + .perform(post("/login").with(csrf()).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()) @@ -1765,12 +1897,13 @@ public class ServerTests { int mid = messagesService.createMessage(ugnich.getUid(), msgText, null, Set.of()); int midNew = messagesService.createMessage(ugnich.getUid(), "Я более новый Угнич", null, Set.of()); MvcResult loginResult = mockMvc - .perform(post("/login").param("username", freefdName).param("password", freefdPassword)) + .perform(post("/login").with(csrf()).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)); @@ -1781,13 +1914,15 @@ public class ServerTests { discussions = (HtmlPage) discussions.refresh(); assertThat(discussions.querySelectorAll("article").size(), is(2)); assertThat( - discussions.querySelectorAll("article").get(0).getAttributes().getNamedItem("data-mid").getNodeValue(), + 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(), + 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()); @@ -1795,7 +1930,9 @@ public class ServerTests { assertThat(discussionsOld.querySelectorAll("article").get(0).getAttributes().getNamedItem("data-mid") .getNodeValue(), is(String.valueOf(midNew))); List<Integer> newMids = IntStream.rangeClosed(1, 19) - .map(i -> messagesService.createMessage(ugnich.getUid(), String.valueOf(i), null, Set.of())).boxed() + .map(i -> messagesService.createMessage(ugnich.getUid(), String.valueOf(i), null, + Set.of())) + .boxed() .collect(Collectors.toList()); for (Integer m : newMids) { subscriptionService.subscribeMessage(messagesService.getMessage(m).get(), freefd); @@ -1803,12 +1940,14 @@ public class ServerTests { discussions = (HtmlPage) discussions.refresh(); assertThat(discussions.querySelectorAll("article").size(), is(20)); assertThat( - discussions.querySelectorAll("article").get(19).getAttributes().getNamedItem("data-mid").getNodeValue(), + 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(), + 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()); @@ -1820,12 +1959,13 @@ public class ServerTests { @Test public void redirectParamShouldCorrectlyRedirectLoggedUser() throws Exception { MvcResult formLoginResult = mockMvc - .perform(post("/login").param("username", ugnichName).param("password", ugnichPassword)) + .perform(post("/login").with(csrf()).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()) .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")); } @@ -1850,12 +1990,13 @@ public class ServerTests { jdbcTemplate.execute("DELETE FROM subscr_messages"); jdbcTemplate.execute("DELETE FROM bl_users"); MvcResult loginResult = mockMvc - .perform(post("/login").param("username", freefdName).param("password", freefdPassword)) + .perform(post("/login").with(csrf()).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, Set.of()); subscriptionService.subscribeMessage(messagesService.getMessage(mid).get(), freefd); messagesService.createReply(mid, 0, ugnich, "new reply", null); @@ -1911,7 +2052,8 @@ public class ServerTests { @Test public void oneClickUnsubscribe() throws Exception { - mockMvc.perform(post("/settings/unsubscribe").param("hash", "123456").param("List-Unsubscribe", "One-Click")) + mockMvc.perform(post("/settings/unsubscribe").with(csrf()).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()); @@ -1920,20 +2062,25 @@ public class ServerTests { @Test @Order(3) public void ActivityDeserialization() throws IOException { - String followJsonStr = IOUtils.toString(new ClassPathResource("follow.json").getURI(), StandardCharsets.UTF_8); + String followJsonStr = IOUtils.toString(new ClassPathResource("follow.json").getURI(), + StandardCharsets.UTF_8); Follow follow = (Follow) jsonMapper.readValue(followJsonStr, Context.class); - String personJsonStr = IOUtils.toString(new ClassPathResource("person.json").getURI(), StandardCharsets.UTF_8); + String personJsonStr = IOUtils.toString(new ClassPathResource("person.json").getURI(), + StandardCharsets.UTF_8); Person person = (Person) jsonMapper.readValue(personJsonStr, Context.class); - String undoJsonStr = IOUtils.toString(new ClassPathResource("undo.json").getURI(), StandardCharsets.UTF_8); + String undoJsonStr = IOUtils.toString(new ClassPathResource("undo.json").getURI(), + StandardCharsets.UTF_8); Undo undo = jsonMapper.readValue(undoJsonStr, Undo.class); assertThat(undo.getObject(), instanceOf(Follow.class)); String undoFollower = undo.getObject().getId(); - String createJsonStr = IOUtils.toString(new ClassPathResource("create.json").getURI(), StandardCharsets.UTF_8); + String createJsonStr = IOUtils.toString(new ClassPathResource("create.json").getURI(), + StandardCharsets.UTF_8); Create create = jsonMapper.readValue(createJsonStr, Create.class); Note note = (Note) create.getObject(); Context attachmentObj = note.getAttachment().get(0); String attachment = attachmentObj != null ? (String) attachmentObj.getUrl() : StringUtils.EMPTY; - String deleteJsonStr = IOUtils.toString(new ClassPathResource("delete.json").getURI(), StandardCharsets.UTF_8); + String deleteJsonStr = IOUtils.toString(new ClassPathResource("delete.json").getURI(), + StandardCharsets.UTF_8); Delete delete = jsonMapper.readValue(deleteJsonStr, Delete.class); int mid = messagesService.createMessage(ugnich.getUid(), "YO", "", Set.of()); User extUser = new User(); @@ -1947,16 +2094,21 @@ public class ServerTests { Message replyToExt = messagesService.getReply(mid, rid2); Note replyNote = activityPubManager.makeNote(replyToExt); assertThat(replyNote.getInReplyTo(), equalTo(extMessageUri)); - String noteStr = IOUtils.toString(new ClassPathResource("mention.json").getURI(), StandardCharsets.UTF_8); + 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), + 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), + 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); + 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); @@ -1970,7 +2122,8 @@ public class ServerTests { public void activitySerialization() throws Exception { Message msgNoTags = commandsManager.processCommand(ugnich, "people", emptyUri).getNewMessage().get(); String json = jsonMapper.writeValueAsString(Context.build(activityPubManager.makeNote(msgNoTags))); - Message msg = commandsManager.processCommand(ugnich, "*NSFW *shit happens", emptyUri).getNewMessage().get(); + Message msg = commandsManager.processCommand(ugnich, "*NSFW *shit happens", emptyUri).getNewMessage() + .get(); Note note = activityPubManager.makeNote(msg); assertThat(note.isSensitive(), is(true)); json = jsonMapper.writeValueAsString(Context.build(note)); @@ -1984,13 +2137,17 @@ public class ServerTests { create.setId(replyNote.getId()); create.setActor("http://localhost:8080/u/freefd"); create.setObject(replyNote); - signatureManager.post((Actor) signatureManager.getContext(URI.create("http://localhost:8080/u/freefd")).get(), - (Actor) signatureManager.getContext(URI.create("http://localhost:8080/u/ugnich")).get(), create); + signatureManager.post( + (Actor) signatureManager.getContext(URI.create("http://localhost:8080/u/freefd")).get(), + (Actor) 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() + .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())))); + activityPubManager.makeNote( + messagesService.getReply(replyToExt.getMid(), replyToExt.getRid())))); mockMvc.perform(get("/n/2-0")).andExpect(status().isOk()); mockMvc.perform(get("/n/2222-0")).andExpect(status().isNotFound()); mockMvc.perform(get("/n/2-14")).andExpect(status().isNotFound()); @@ -2017,14 +2174,17 @@ public class ServerTests { Actor ugnichPerson = profileController.getUser("ugnich"); now = Instant.now(); requestDate = DateFormattersHolder.getHttpDateFormatter().format(now); - String signatureString = signatureManager.addSignature(ugnichPerson, testHost, "GET", meUri, requestDate, + 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); - String testappResponseString = IOUtils.toString(testappResponse.getInputStream(), StandardCharsets.UTF_8); + String testuserResponseString = IOUtils.toString(testuserResponse.getInputStream(), + StandardCharsets.UTF_8); + String testappResponseString = IOUtils.toString(testappResponse.getInputStream(), + StandardCharsets.UTF_8); ClientHttpRequestFactory originalRequestFactory = apClient.getRequestFactory(); URI testuserUri = URI.create("https://example.com/u/testuser"); URI testuserkeyUri = URI.create("https://example.com/u/testuser#main-key"); @@ -2049,13 +2209,16 @@ public class ServerTests { 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()); + .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()); + .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)) + .header("Signature", testSignatureString).contentType(Context.LD_JSON_MEDIA_TYPE) + .content(payload)) .andExpect(status().isUnauthorized()); // test flagging as application payload = IOUtils.toByteArray(flagPayload.getInputStream()); @@ -2065,11 +2228,13 @@ public class ServerTests { testRequestDate = DateFormattersHolder.getHttpDateFormatter().format(now2); Application testapp = (Application) signatureManager.getContext(testAppUri).get(); assertThat(testapp.getPublicKey().getPublicKeyPem(), is(testKeystoreManager.getPublicKeyPem())); - testSignatureString = signatureManager.addSignature(testapp, "localhost", "POST", inboxUri, testRequestDate, + testSignatureString = signatureManager.addSignature(testapp, "localhost", "POST", inboxUri, + testRequestDate, digestHeader, testKeystoreManager); mockMvc.perform(post(inboxUri).header("Host", testHost).header("Date", testRequestDate) .header("Signature", testSignatureString).header("Digest", digestHeader) - .contentType(Context.LD_JSON_MEDIA_TYPE).content(payload)).andExpect(status().isAccepted()); + .contentType(Context.LD_JSON_MEDIA_TYPE).content(payload)) + .andExpect(status().isAccepted()); apClient.setRequestFactory(originalRequestFactory); } @@ -2082,7 +2247,8 @@ public class ServerTests { @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(); } @@ -2096,7 +2262,8 @@ public class ServerTests { assertThat(res.getText(), is("Private message sent")); 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); + PrivateChats chats = jsonMapper.readValue(result.getResponse().getContentAsString(), + PrivateChats.class); assertThat(chats.getUsers().size(), is(1)); } @@ -2114,7 +2281,8 @@ public class ServerTests { 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()) + .param("password", "demopassword").param("verificationCode", "123456")) + .andExpect(status().isOk()) .andReturn(); User testuser = jsonMapper.readValue(result.getResponse().getContentAsString(), User.class); assertThat(testuser.getName(), is("testuser")); @@ -2125,14 +2293,17 @@ public class ServerTests { 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) + 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()), + 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(), + String.format("#%d/%d *GOOD *BAD", reply.getMid(), reply.getRid()), + emptyUri).getText(), startsWith("Reply posted")); } @@ -2140,10 +2311,10 @@ public class ServerTests { 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)) + .perform(post("/login").with(csrf()).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") + mockMvc.perform(post("/signup").with(csrf()).cookie(rememberMeFromForm).param("hash", "1").param("type", "xmpp") .param("action", "link")).andExpect(status().isOk()) .andExpect(content().string(containsString("XMPP support is disabled"))); } @@ -2163,9 +2334,11 @@ public class ServerTests { @Test public void verifiedUsersTest() { assertThat(userService.getUserByName("ugnich").isVerified(), is(false)); - jdbcTemplate.update("INSERT INTO telegram(user_id, tg_id) VALUES(?, ?)", ugnich.getUid(), "100001866137681"); + jdbcTemplate.update("INSERT INTO telegram(user_id, tg_id) VALUES(?, ?)", ugnich.getUid(), + "100001866137681"); assertThat(userService.canDeleteTelegramUser(userService.getUserByName("ugnich")), is(false)); - jdbcTemplate.update("INSERT INTO facebook(user_id, fb_id) VALUES(?, ?)", ugnich.getUid(), "100001866137681"); + jdbcTemplate.update("INSERT INTO facebook(user_id, fb_id) VALUES(?, ?)", ugnich.getUid(), + "100001866137681"); assertThat(userService.getUserByName("ugnich").isVerified(), is(true)); assertThat(userService.canDeleteTelegramUser(userService.getUserByName("ugnich")), is(true)); jdbcTemplate.update("DELETE FROM facebook"); @@ -2194,31 +2367,38 @@ public class ServerTests { String convertedAvatarHash = DigestUtils.md5DigestAsHex(IOUtils.toByteArray(convertedAvatarUri)); mockMvc.perform(get("/api/me").with(httpBasic(freefdName, freefdPassword))).andExpect(status().isOk()) .andExpect(jsonPath("$.avatar", is( - String.format("http://localhost:8080/i/a/%d-%s.png", freefd.getUid(), convertedAvatarHash)))); - mockMvc.perform(post("/api/me").with(httpBasic(ugnichName, ugnichPassword)).param("password", "newPassword")) + String.format("http://localhost:8080/i/a/%d-%s.png", freefd.getUid(), + convertedAvatarHash)))); + mockMvc.perform(post("/api/me").with(httpBasic(ugnichName, ugnichPassword)).param("password", + "newPassword")) .andExpect(status().isOk()); mockMvc.perform(get("/api/me").with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().isUnauthorized()); - mockMvc.perform(post("/api/me").with(httpBasic(ugnichName, "newPassword")).param("password", 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(), + "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")) + 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")) + 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()).andExpect(header().string("Vary", "Accept-Language")); + 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("/api/messages")).andExpect(status().isOk()) @@ -2251,7 +2431,8 @@ public class ServerTests { }); 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", + 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); @@ -2270,7 +2451,8 @@ public class ServerTests { MockRestServiceServer restServiceServer = MockRestServiceServer.createServer(apClient); restServiceServer.expect(times(2), requestTo(delete.getObject().getId())) .andRespond(withSuccess( - IOUtils.toString(testSuspendedUserResponse.getInputStream(), StandardCharsets.UTF_8), + IOUtils.toString(testSuspendedUserResponse.getInputStream(), + StandardCharsets.UTF_8), MediaType.APPLICATION_JSON)); Person testuser = (Person) signatureManager.getContext(URI.create(delete.getObject().getId())).get(); Instant now = Instant.now(); @@ -2281,7 +2463,8 @@ public class ServerTests { String testSignatureString = signatureManager.addSignature(testuser, "localhost", "POST", inboxUri, testRequestDate, digestHeader, testKeystoreManager); mockMvc.perform(post(inboxUri).contentType(ACTIVITY_MEDIA_TYPE).content(deleteJsonStr) - .header("Host", "localhost").header("Date", testRequestDate).header("Digest", digestHeader) + .header("Host", "localhost").header("Date", testRequestDate) + .header("Digest", digestHeader) .header("Signature", testSignatureString)).andExpect(status().isAccepted()); apClient.setRequestFactory(originalRequestFactory); Mockito.verify(deleteListener, Mockito.times(1)).onApplicationEvent(deleteEventCaptor.capture()); @@ -2300,7 +2483,8 @@ public class ServerTests { restServiceServer.expect(requestTo(delete.getObject().getId())).andRespond(response -> { throw new ResourceAccessException("Connection reset"); }); - mockMvc.perform(post("/api/inbox").contentType(ACTIVITY_MEDIA_TYPE).content(deleteJsonStr).header("Signature", + 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); @@ -2322,11 +2506,12 @@ public class ServerTests { Create create = jsonMapper.readValue(noteString, Create.class); Note note = (Note) create.getObject(); String markdown = remarkConverter.convertFragment((String) note.getContent()); - String commandBody = note.getContent() == null ? markdown : note.getAttachment().stream().map(attachment -> { - String attachmentUrl = attachment.getUrl(); - String attachmentName = attachment.getName(); - return PlainTextFormatter.markdownUrl(attachmentUrl, attachmentName); - }).reduce(markdown, (current, next) -> String.format("%s\n%s", current, next)); + String commandBody = note.getContent() == null ? markdown + : note.getAttachment().stream().map(attachment -> { + String attachmentUrl = attachment.getUrl(); + String attachmentName = attachment.getName(); + return PlainTextFormatter.markdownUrl(attachmentUrl, attachmentName); + }).reduce(markdown, (current, next) -> String.format("%s\n%s", current, next)); } @Test @@ -2340,7 +2525,8 @@ public class ServerTests { @Test public void nodeinfo() throws Exception { - MvcResult nodeinfoXRD = mockMvc.perform(get("/.well-known/nodeinfo").contentType(MediaType.APPLICATION_JSON)) + 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()); @@ -2398,7 +2584,8 @@ public class ServerTests { 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")); + .andExpect(status().isOk()) + .andExpect(content().contentType("application/rss+xml;charset=UTF-8")); mockMvc.perform(get("/rss/ugnich/feed").accept(MediaType.TEXT_XML)).andExpect(status().isOk()); mockMvc.perform(get("/rss/ugnich/diary").accept(MediaType.TEXT_XML)).andExpect(status().isNotFound()); } @@ -2407,8 +2594,10 @@ public class ServerTests { public void wsThreadsShouldRedirect() throws Exception { int mid = messagesService.createMessage(ugnich.getUid(), "tst", null, Set.of()); 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("/s/" + mid)).andExpect(status().isFound()) + .andExpect(redirectedUrl("/ugnich/" + mid)); + mockMvc.perform(get("/ws/" + mid)).andExpect(status().isFound()) + .andExpect(redirectedUrl("/ugnich/" + mid)); } @MockBean @@ -2432,7 +2621,8 @@ 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); @@ -2457,12 +2647,14 @@ public class ServerTests { 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") + .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") + .renderHtml(MessageUtils.formatHtml(html), PlainTextFormatter.formatUrl(html), html, + "12345") .orElseThrow(); assertThat(htmlPM, is(getSnapshot(testPrivateHtmlEmail))); } @@ -2522,7 +2714,7 @@ public class ServerTests { @Test public void invalidMediaTypeTest() throws Exception { mockMvc.perform(get("/api/messages") - .header("Accept", "application/xml")).andExpect(status().isBadRequest()) + .header("Accept", "application/xml")).andExpect(status().isBadRequest()) .andExpect(content().string("Invalid media type")); } @@ -2540,6 +2732,6 @@ public class ServerTests { get("/api/groups_pms").with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().isOk()) .andExpect(jsonPath("$.pms", empty())); - + } } |