diff options
author | Vitaly Takmazov | 2019-12-12 11:28:12 +0300 |
---|---|---|
committer | Vitaly Takmazov | 2019-12-12 11:28:12 +0300 |
commit | f462d7335567960978e16c5e042c99b54daa94b6 (patch) | |
tree | f298f3ac50ed64d0292bba0a8a6e148e8daa434c /src | |
parent | c0ae480bb5c07ea7b9e1b42df428e2857b0d4816 (diff) |
Cleanup IDEA code issues
Diffstat (limited to 'src')
32 files changed, 235 insertions, 209 deletions
diff --git a/src/main/java/com/juick/model/Auth.java b/src/main/java/com/juick/model/Auth.java index 66125567..26815e04 100644 --- a/src/main/java/com/juick/model/Auth.java +++ b/src/main/java/com/juick/model/Auth.java @@ -21,8 +21,8 @@ package com.juick.model; * Created by vt on 09/02/16. */ public class Auth { - private String account; - private String authCode; + private final String account; + private final String authCode; public Auth(String account, String authCode) { this.account = account; diff --git a/src/main/java/com/juick/server/EmailManager.java b/src/main/java/com/juick/server/EmailManager.java index edff7b70..570d2e6e 100644 --- a/src/main/java/com/juick/server/EmailManager.java +++ b/src/main/java/com/juick/server/EmailManager.java @@ -67,9 +67,7 @@ public class EmailManager implements NotificationListener { } if (MessageUtils.isPM(msg)) { String subject = String.format("Private message from %s", msg.getUser().getName()); - emailService.getEmails(msg.getTo().getUid(), true).forEach(email -> { - emailNotify(email, subject, msg); - }); + emailService.getEmails(msg.getTo().getUid(), true).forEach(email -> emailNotify(email, subject, msg)); } else if (MessageUtils.isReply(msg)) { Message originalMessage = messagesService.getMessage(msg.getMid()).orElseThrow(IllegalStateException::new); String subject = String.format("New reply to %s", originalMessage.getUser().getName()); diff --git a/src/main/java/com/juick/server/KeystoreManager.java b/src/main/java/com/juick/server/KeystoreManager.java index b1ce7a56..15b62e35 100644 --- a/src/main/java/com/juick/server/KeystoreManager.java +++ b/src/main/java/com/juick/server/KeystoreManager.java @@ -23,14 +23,12 @@ public class KeystoreManager { private KeyStore ks; - private KeyManagerFactory kmf; - public KeystoreManager(Resource keystore, String keystorePassword) { this.keystorePassword = keystorePassword; try (InputStream ksIs = keystore.getInputStream()) { ks = KeyStore.getInstance("PKCS12"); ks.load(ksIs, keystorePassword.toCharArray()); - kmf = KeyManagerFactory.getInstance(KeyManagerFactory + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory .getDefaultAlgorithm()); kmf.init(ks, keystorePassword.toCharArray()); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | CertificateException e) { @@ -58,7 +56,7 @@ public class KeystoreManager { public String getPublicKeyPem() { String[] key = Base64Utils.encodeToString(getKeyPair().getPublic().getEncoded()).split("(?<=\\G.{64})"); return String.format("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n", - Arrays.asList(key).stream().collect(Collectors.joining("\n"))); + String.join("\n", key)); } public static PublicKey publicKeyOf(Person person) { String pubkeyPem = person.getPublicKey().getPublicKeyPem(); diff --git a/src/main/java/com/juick/server/TelegramBotManager.java b/src/main/java/com/juick/server/TelegramBotManager.java index 7ca9e347..32bd7096 100644 --- a/src/main/java/com/juick/server/TelegramBotManager.java +++ b/src/main/java/com/juick/server/TelegramBotManager.java @@ -213,7 +213,7 @@ public class TelegramBotManager implements NotificationListener { juickLink.get().url()).build(); String path = uriComponents.getPath(); if (StringUtils.isNotEmpty(path) && path.length() > 1) { - int mid = 0; + int mid; try { mid = Integer.parseInt(path.substring(3)); } catch (NumberFormatException e) { diff --git a/src/main/java/com/juick/server/api/ApiSocialLogin.java b/src/main/java/com/juick/server/api/ApiSocialLogin.java index 2d0a5c7e..efbb56f4 100644 --- a/src/main/java/com/juick/server/api/ApiSocialLogin.java +++ b/src/main/java/com/juick/server/api/ApiSocialLogin.java @@ -79,7 +79,6 @@ public class ApiSocialLogin { private static final String TWITTER_VERIFY_URL = "https://api.twitter.com/1.1/account/verify_credentials.json"; @Inject private ObjectMapper jsonMapper; - private ServiceBuilder facebookBuilder, twitterBuilder, vkBuilder; private OAuth20Service facebookAuthService, vkAuthService; @Value("${twitter_consumer_key:appid}") @@ -110,9 +109,9 @@ public class ApiSocialLogin { @PostConstruct public void init() { - facebookBuilder = new ServiceBuilder(FACEBOOK_APPID); - twitterBuilder = new ServiceBuilder(twitterConsumerKey); - vkBuilder = new ServiceBuilder(VK_APPID); + ServiceBuilder facebookBuilder = new ServiceBuilder(FACEBOOK_APPID); + ServiceBuilder twitterBuilder = new ServiceBuilder(twitterConsumerKey); + ServiceBuilder vkBuilder = new ServiceBuilder(VK_APPID); verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory) .setAudience(Collections.singletonList(googleClientId)) .build(); @@ -260,7 +259,7 @@ public class ApiSocialLogin { throw new HttpBadRequestException(); } - Long vkID = NumberUtils.toLong(jsonUser.getId(), 0); + long vkID = NumberUtils.toLong(jsonUser.getId(), 0); int uid = crosspostService.getUIDbyVKID(vkID); if (uid > 0) { UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(redirectUrl); diff --git a/src/main/java/com/juick/server/api/Notifications.java b/src/main/java/com/juick/server/api/Notifications.java index 72988298..e7eada2a 100644 --- a/src/main/java/com/juick/server/api/Notifications.java +++ b/src/main/java/com/juick/server/api/Notifications.java @@ -41,7 +41,6 @@ import org.springframework.web.bind.annotation.RestController; import springfox.documentation.annotations.ApiIgnore; import javax.inject.Inject; -import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -175,7 +174,7 @@ public class Notifications { @RequestMapping(value = "/api/notifications", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) public Status doPut( @Visitor User visitor, - @RequestBody List<ExternalToken> list) throws IOException { + @RequestBody List<ExternalToken> list) { list.forEach(t -> { switch (t.getType()) { case "gcm": diff --git a/src/main/java/com/juick/server/api/Post.java b/src/main/java/com/juick/server/api/Post.java index 59bd05a7..255b7290 100644 --- a/src/main/java/com/juick/server/api/Post.java +++ b/src/main/java/com/juick/server/api/Post.java @@ -28,7 +28,6 @@ import com.juick.server.util.HttpForbiddenException; import com.juick.server.util.HttpNotFoundException; import com.juick.server.util.HttpUtils; import com.juick.service.MessagesService; -import com.juick.service.SubscriptionService; import com.juick.service.UserService; import com.juick.service.security.annotation.Visitor; import org.apache.commons.lang3.StringUtils; @@ -58,12 +57,8 @@ public class Post { private UserService userService; @Inject private MessagesService messagesService; - @Inject - private SubscriptionService subscriptionService; @Value("${upload_tmp_dir:#{systemEnvironment['TEMP'] ?: '/tmp'}}") private String tmpDir; - @Value("${img_path:#{systemEnvironment['TEMP'] ?: '/tmp'}}") - private String imgDir; @Inject CommandsManager commandsManager; @@ -155,7 +150,7 @@ public class Post { @ResponseStatus(value = HttpStatus.OK) public Status doPostRecomm(@Visitor User visitor, @RequestParam Integer mid) throws Exception { Optional<com.juick.Message> message = messagesService.getMessage(mid); - if (!message.isPresent()) { + if (message.isEmpty()) { throw new HttpNotFoundException(); } Message msg = message.get(); @@ -172,7 +167,7 @@ public class Post { public Status doPostSubscribe(@Visitor User visitor, @RequestParam Integer mid) throws Exception { Optional<com.juick.Message> message = messagesService.getMessage(mid); - if (!message.isPresent()) { + if (message.isEmpty()) { throw new HttpNotFoundException(); } Message msg = message.get(); @@ -199,7 +194,7 @@ public class Post { logger.info("got reaction with type: {}", reactionId); Optional<com.juick.Message> message = messagesService.getMessage(mid); - if (!message.isPresent()) { + if (message.isEmpty()) { throw new HttpNotFoundException(); } Message msg = message.get(); diff --git a/src/main/java/com/juick/server/api/Users.java b/src/main/java/com/juick/server/api/Users.java index 6d7c7a45..d5c1b5d7 100644 --- a/src/main/java/com/juick/server/api/Users.java +++ b/src/main/java/com/juick/server/api/Users.java @@ -28,33 +28,22 @@ import com.juick.server.util.WebUtils; import com.juick.server.www.WebApp; import com.juick.service.*; import com.juick.service.security.annotation.Visitor; -import com.juick.service.security.entities.JuickUser; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.inject.Inject; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import static org.springframework.http.ResponseEntity.ok; -import static org.springframework.http.ResponseEntity.status; - /** * @author ugnich */ @@ -151,7 +140,7 @@ public class Users { "If you don't know, what this mean - just ignore this mail.\n", authCode), StringUtils.EMPTY, Collections.emptyMap())) { throw new HttpBadRequestException(); - }; + } } } } diff --git a/src/main/java/com/juick/server/api/activity/Profile.java b/src/main/java/com/juick/server/api/activity/Profile.java index 88c76a93..a48958d2 100644 --- a/src/main/java/com/juick/server/api/activity/Profile.java +++ b/src/main/java/com/juick/server/api/activity/Profile.java @@ -23,7 +23,6 @@ import com.juick.server.api.activity.model.objects.Note; import com.juick.server.api.activity.model.objects.OrderedCollection; import com.juick.server.api.activity.model.objects.OrderedCollectionPage; import com.juick.server.api.activity.model.objects.Person; -import com.juick.server.util.HttpBadRequestException; import com.juick.server.util.HttpNotFoundException; import com.juick.server.www.WebApp; import com.juick.service.MessagesService; diff --git a/src/main/java/com/juick/server/configuration/SecurityConfig.java b/src/main/java/com/juick/server/configuration/SecurityConfig.java index c5fe4fbb..e69ff8f6 100644 --- a/src/main/java/com/juick/server/configuration/SecurityConfig.java +++ b/src/main/java/com/juick/server/configuration/SecurityConfig.java @@ -30,7 +30,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @@ -38,7 +37,6 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.security.web.authentication.HttpStatusEntryPoint; import org.springframework.security.web.authentication.RememberMeServices; import org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; diff --git a/src/main/java/com/juick/server/util/HttpBadRequestException.java b/src/main/java/com/juick/server/util/HttpBadRequestException.java index 242f2b09..892cb203 100644 --- a/src/main/java/com/juick/server/util/HttpBadRequestException.java +++ b/src/main/java/com/juick/server/util/HttpBadRequestException.java @@ -17,7 +17,6 @@ package com.juick.server.util; -import org.apache.commons.lang3.StringUtils; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; diff --git a/src/main/java/com/juick/server/util/ImageUtils.java b/src/main/java/com/juick/server/util/ImageUtils.java index 2f5d3292..60bce1a0 100644 --- a/src/main/java/com/juick/server/util/ImageUtils.java +++ b/src/main/java/com/juick/server/util/ImageUtils.java @@ -1,6 +1,5 @@ - /* - * Copyright (C) 2008-2017, Juick + * Copyright (C) 2008-2019, Juick * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as @@ -34,7 +33,6 @@ import org.slf4j.LoggerFactory; import javax.imageio.ImageIO; import javax.imageio.ImageReader; -import javax.imageio.stream.FileImageInputStream; import javax.imageio.stream.ImageInputStream; import java.awt.image.BufferedImage; import java.io.File; @@ -128,7 +126,7 @@ public class ImageUtils { int width = originalImage.getWidth(); int height = originalImage.getHeight(); - int maxDimension = (width > height) ? width : height; + int maxDimension = Math.max(width, height); BufferedImage image1024 = (maxDimension > 1024) ? Scalr.resize(originalImage, 1024) : originalImage; BufferedImage image0512 = (maxDimension > 512) ? Scalr.resize(originalImage, 512) : originalImage; BufferedImage image0160 = (maxDimension > 160) ? Scalr.resize(originalImage, 160) : originalImage; diff --git a/src/main/java/com/juick/server/www/controllers/MessagesWWW.java b/src/main/java/com/juick/server/www/controllers/MessagesWWW.java index d845aac6..1cd89914 100644 --- a/src/main/java/com/juick/server/www/controllers/MessagesWWW.java +++ b/src/main/java/com/juick/server/www/controllers/MessagesWWW.java @@ -28,7 +28,6 @@ import com.juick.server.www.WebApp; import com.juick.service.*; import com.juick.service.security.annotation.Visitor; import com.juick.util.MessageUtils; -import org.apache.commons.codec.CharEncoding; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.text.StringEscapeUtils; @@ -44,7 +43,6 @@ import ru.sape.Sape; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; -import java.io.IOException; import java.net.URI; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -101,7 +99,7 @@ public class MessagesWWW { @RequestParam(name = "to", required = false, defaultValue = "0") Long paramTo, @RequestParam(name = "page", required = false, defaultValue = "0") Integer page, @CookieValue(name = "sape_cookie", required = false, defaultValue = StringUtils.EMPTY) String sapeCookie, - ModelMap model) throws IOException { + ModelMap model) { if (tag != null) { return "redirect:/tag/" + URLEncoder.encode(tag, StandardCharsets.UTF_8); } @@ -149,7 +147,7 @@ public class MessagesWWW { throw new HttpNotFoundException(); } - String head = "<meta name=\"Description\" content=\"" + title + "\" />\n";; + String head = "<meta name=\"Description\" content=\"" + title + "\" />\n"; if (paramBefore > 0 || paramShow != null) { head = "<meta name=\"robots\" content=\"noindex\"/>"; @@ -166,9 +164,7 @@ public class MessagesWWW { visitor.setUnreadCount(unread.size()); List<Integer> blUIDs = userService.checkBL(visitor.getUid(), msgs.stream().map(m -> m.getUser().getUid()).collect(Collectors.toList())); - msgs.forEach(m -> { - m.ReadOnly |= blUIDs.contains(m.getUser().getUid()); - }); + msgs.forEach(m -> m.ReadOnly |= blUIDs.contains(m.getUser().getUid())); } model.addAttribute("msgs", msgs); model.addAttribute("tags", tagService.getPopularTags()); @@ -183,7 +179,7 @@ public class MessagesWWW { nextpage += "&show=" + paramShow; } if (paramSearch != null) { - nextpage += "&search=" + URLEncoder.encode(paramSearch, CharEncoding.UTF_8); + nextpage += "&search=" + URLEncoder.encode(paramSearch, StandardCharsets.UTF_8); } model.addAttribute("nextpage", nextpage); } @@ -206,7 +202,7 @@ public class MessagesWWW { @PathVariable String uname, @RequestParam(required = false, defaultValue = "0") Integer before, @CookieValue(name = "sape_cookie", required = false, defaultValue = StringUtils.EMPTY) String sapeCookie, - ModelMap model) throws IOException { + ModelMap model) { com.juick.User user = userService.getUserByName(uname); if (user.isBanned() || user.isAnonymous()) { throw new HttpNotFoundException(); @@ -284,9 +280,7 @@ public class MessagesWWW { visitor.setUnreadCount(unread.size()); List<Integer> blUIDs = userService.checkBL(visitor.getUid(), msgs.stream().map(m -> m.getUser().getUid()).collect(Collectors.toList())); - msgs.forEach(m -> { - m.ReadOnly |= blUIDs.contains(m.getUser().getUid()); - }); + msgs.forEach(m -> m.ReadOnly |= blUIDs.contains(m.getUser().getUid())); } model.addAttribute("msgs", msgs); model.addAttribute("headers", head); @@ -355,7 +349,7 @@ public class MessagesWWW { @GetMapping("/{uname}/readers") protected String doGetReaders( @Visitor User visitor, - @PathVariable String uname, ModelMap model) throws IOException { + @PathVariable String uname, ModelMap model) { com.juick.User user = userService.getUserByName(uname); visitor.setAvatar(webApp.getAvatarWebPath(visitor)); model.addAttribute("title", "Читатели " + user.getName()); @@ -370,7 +364,7 @@ public class MessagesWWW { @GetMapping("/{uname}/bl") protected String doGetBL( @Visitor User visitor, - @PathVariable String uname, ModelMap model) throws IOException { + @PathVariable String uname, ModelMap model) { com.juick.User user = userService.getUserByName(uname); if (visitor.getUid() != user.getUid()) { throw new HttpForbiddenException(); @@ -391,7 +385,7 @@ public class MessagesWWW { @PathVariable String tagName, @CookieValue(name = "sape_cookie", required = false, defaultValue = StringUtils.EMPTY) String sapeCookie, @RequestParam(required = false, defaultValue = "0") int before, - ModelMap model) throws IOException { + ModelMap model) { visitor.setAvatar(webApp.getAvatarWebPath(visitor)); String paramTagStr = StringEscapeUtils.unescapeHtml4(tagName); com.juick.Tag paramTag = tagService.getTag(paramTagStr, false); @@ -399,13 +393,13 @@ public class MessagesWWW { throw new HttpNotFoundException(); } else if (paramTag.SynonymID > 0 && paramTag.TID != paramTag.SynonymID) { com.juick.Tag synTag = tagService.getTag(paramTag.SynonymID); - String url = "/tag/" + URLEncoder.encode(StringEscapeUtils.escapeHtml4(synTag.getName()), CharEncoding.UTF_8); + String url = "/tag/" + URLEncoder.encode(StringEscapeUtils.escapeHtml4(synTag.getName()), StandardCharsets.UTF_8); if (request.getQueryString() != null) { url += "?" + request.getQueryString(); } return "redirect:" + url; } else if (!paramTag.getName().equals(paramTagStr)) { - String url = "/tag/" + URLEncoder.encode(StringEscapeUtils.escapeHtml4(paramTag.getName()), CharEncoding.UTF_8); + String url = "/tag/" + URLEncoder.encode(StringEscapeUtils.escapeHtml4(paramTag.getName()), StandardCharsets.UTF_8); if (request.getQueryString() != null) { url += "?" + request.getQueryString(); } @@ -424,9 +418,7 @@ public class MessagesWWW { visitor.getUid(), msgs.stream().map(m -> m.getUser().getUid()).collect(Collectors.toList()) ); - msgs.forEach(m -> { - m.ReadOnly |= blUIDs.contains(m.getUser().getUid()); - }); + msgs.forEach(m -> m.ReadOnly |= blUIDs.contains(m.getUser().getUid())); fillUserModel(model, visitor, visitor); } diff --git a/src/main/java/com/juick/server/www/controllers/Settings.java b/src/main/java/com/juick/server/www/controllers/Settings.java index 370c2154..e147d058 100644 --- a/src/main/java/com/juick/server/www/controllers/Settings.java +++ b/src/main/java/com/juick/server/www/controllers/Settings.java @@ -111,7 +111,6 @@ public class Settings { model.addAttribute("userinfo", userService.getUserInfo(visitor)); if (page.equals("auth-email")) { if (emailService.verifyAddressByCode(visitor.getUid(), request.getParameter("code"))) { - ; model.addAttribute("result", "OK!"); } else { model.addAttribute("result", "Sorry, code unknown."); diff --git a/src/main/java/com/juick/server/www/controllers/SignUp.java b/src/main/java/com/juick/server/www/controllers/SignUp.java index 5fce2d35..18dfc2eb 100644 --- a/src/main/java/com/juick/server/www/controllers/SignUp.java +++ b/src/main/java/com/juick/server/www/controllers/SignUp.java @@ -17,7 +17,6 @@ package com.juick.server.www.controllers; import com.juick.User; -import com.juick.model.AnonymousUser; import com.juick.server.util.HttpBadRequestException; import com.juick.server.util.HttpForbiddenException; import com.juick.server.www.WebApp; diff --git a/src/main/java/com/juick/server/www/controllers/SocialLogin.java b/src/main/java/com/juick/server/www/controllers/SocialLogin.java index e845247e..602f32c3 100644 --- a/src/main/java/com/juick/server/www/controllers/SocialLogin.java +++ b/src/main/java/com/juick/server/www/controllers/SocialLogin.java @@ -74,12 +74,11 @@ public class SocialLogin { private String FACEBOOK_SECRET; @Value("${ap_base_uri:http://localhost:8080/}") private String baseUri; - private String facebookRedirectUri; private static final String VK_REDIRECT = "http://juick.com/_vklogin"; private static final String TWITTER_VERIFY_URL = "https://api.twitter.com/1.1/account/verify_credentials.json"; @Inject private ObjectMapper jsonMapper; - private ServiceBuilder facebookBuilder, twitterBuilder, vkBuilder; + private ServiceBuilder twitterBuilder; private OAuth20Service facebookAuthService, vkAuthService; @Value("${twitter_consumer_key:appid}") @@ -104,11 +103,11 @@ public class SocialLogin { @PostConstruct public void init() { - facebookBuilder = new ServiceBuilder(FACEBOOK_APPID); + ServiceBuilder facebookBuilder = new ServiceBuilder(FACEBOOK_APPID); twitterBuilder = new ServiceBuilder(twitterConsumerKey); - vkBuilder = new ServiceBuilder(VK_APPID); + ServiceBuilder vkBuilder = new ServiceBuilder(VK_APPID); UriComponentsBuilder facebookRedirectBuilder = UriComponentsBuilder.fromUriString(baseUri); - facebookRedirectUri = facebookRedirectBuilder.replacePath("/_fblogin").build().toUriString(); + String facebookRedirectUri = facebookRedirectBuilder.replacePath("/_fblogin").build().toUriString(); facebookAuthService = facebookBuilder .apiSecret(FACEBOOK_SECRET) .callback(facebookRedirectUri) @@ -168,7 +167,7 @@ public class SocialLogin { } else { if (!crosspostService.createFacebookUser(fbID, state, token.getAccessToken(), fb.getName())) { if (StringUtils.isNotEmpty(fb.getEmail())) { - logger.info("found {} for facebook user {}", fb.getEmail()); + logger.info("found {} for facebook user {}", fb.getEmail(), fb.getName()); Integer userId = crosspostService.getUIDbyFBID(fbID); if (!emailService.getEmails(userId, false).contains(fb.getEmail())) { emailService.addEmail(userId, fb.getEmail()); @@ -265,7 +264,7 @@ public class SocialLogin { throw new HttpBadRequestException(); } - Long vkID = NumberUtils.toLong(jsonUser.getId(), 0); + long vkID = NumberUtils.toLong(jsonUser.getId(), 0); int uid = crosspostService.getUIDbyVKID(vkID); if (uid > 0) { Cookie c = new Cookie("hash", userService.getHashByUID(uid)); @@ -295,7 +294,7 @@ public class SocialLogin { byte[] secretKey = DigestUtils.sha256(telegramToken); String resultString = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, secretKey).hmacHex(dataCheckString); if (hash.equals(resultString)) { - Long tgUser = Long.valueOf(params.get("id")); + long tgUser = Long.parseLong(params.get("id")); int uid = telegramService.getUser(tgUser); if (uid > 0) { Cookie c = new Cookie("hash", userService.getHashByUID(uid)); diff --git a/src/main/java/com/juick/server/www/controllers/AnythingFilter.java b/src/main/java/com/juick/server/www/filters/AnythingFilter.java index 1f4cf75a..33fb62ea 100644 --- a/src/main/java/com/juick/server/www/controllers/AnythingFilter.java +++ b/src/main/java/com/juick/server/www/filters/AnythingFilter.java @@ -1,4 +1,4 @@ -package com.juick.server.www.controllers; +package com.juick.server.www.filters; import com.juick.server.util.WebUtils; import com.juick.service.MessagesService; diff --git a/src/main/java/com/juick/server/xmpp/JidConverter.java b/src/main/java/com/juick/server/xmpp/JidConverter.java index e9a9707e..96c9ca74 100644 --- a/src/main/java/com/juick/server/xmpp/JidConverter.java +++ b/src/main/java/com/juick/server/xmpp/JidConverter.java @@ -4,10 +4,12 @@ import org.springframework.core.convert.converter.Converter; import org.springframework.lang.Nullable; import rocks.xmpp.addr.Jid; +import javax.annotation.Nonnull; + public class JidConverter implements Converter<String, Jid> { @Nullable @Override - public Jid convert(String jidStr) { + public Jid convert(@Nonnull String jidStr) { return Jid.of(jidStr); } } diff --git a/src/main/java/com/juick/service/EmailServiceImpl.java b/src/main/java/com/juick/service/EmailServiceImpl.java index 78bdd42a..d5375ead 100644 --- a/src/main/java/com/juick/service/EmailServiceImpl.java +++ b/src/main/java/com/juick/service/EmailServiceImpl.java @@ -19,12 +19,10 @@ package com.juick.service; import org.apache.commons.lang3.StringUtils; import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; -import javax.inject.Inject; import java.util.List; /** diff --git a/src/main/java/com/juick/service/ImagesServiceImpl.java b/src/main/java/com/juick/service/ImagesServiceImpl.java index 67c8360e..f91b6036 100644 --- a/src/main/java/com/juick/service/ImagesServiceImpl.java +++ b/src/main/java/com/juick/service/ImagesServiceImpl.java @@ -13,10 +13,9 @@ import java.nio.file.Paths; public class ImagesServiceImpl implements ImagesService { private ImageUtils imageUtils; private String imgDir; - private String tmpDir; + public ImagesServiceImpl(String imgDir, String tmpDir) { this.imgDir = imgDir; - this.tmpDir = tmpDir; imageUtils = new ImageUtils(imgDir, tmpDir); } @Override diff --git a/src/main/java/com/juick/service/MessagesServiceImpl.java b/src/main/java/com/juick/service/MessagesServiceImpl.java index 8bcf47d3..c405fde4 100644 --- a/src/main/java/com/juick/service/MessagesServiceImpl.java +++ b/src/main/java/com/juick/service/MessagesServiceImpl.java @@ -23,7 +23,6 @@ import com.juick.User; import com.juick.model.AnonymousUser; import com.juick.model.PrivacyOpts; import com.juick.model.ResponseReply; -import com.juick.server.util.HttpNotFoundException; import com.juick.server.www.WebApp; import com.juick.util.MessageUtils; import org.apache.commons.collections4.CollectionUtils; @@ -601,7 +600,7 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ .addValue("uid", uid) .addValue("before", before); - List<Integer> mids = getNamedParameterJdbcTemplate().queryForList( + return getNamedParameterJdbcTemplate().queryForList( "SELECT message_id FROM messages WHERE " + "(user_id=:uid OR " + "(EXISTS (SELECT 1 FROM subscr_users WHERE subscr_users.suser_id = :uid " + @@ -624,8 +623,6 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ "ORDER BY message_id DESC LIMIT 20", sqlParameterSource, Integer.class); - - return mids; } @Transactional(readOnly = true) diff --git a/src/main/java/com/juick/service/PushQueriesServiceImpl.java b/src/main/java/com/juick/service/PushQueriesServiceImpl.java index 7f97956c..9b1ee2f0 100644 --- a/src/main/java/com/juick/service/PushQueriesServiceImpl.java +++ b/src/main/java/com/juick/service/PushQueriesServiceImpl.java @@ -19,12 +19,10 @@ package com.juick.service; import org.apache.commons.collections4.CollectionUtils; import org.springframework.dao.DuplicateKeyException; -import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; -import javax.inject.Inject; import java.util.Collection; import java.util.Collections; import java.util.List; diff --git a/src/main/java/com/juick/service/SubscriptionServiceImpl.java b/src/main/java/com/juick/service/SubscriptionServiceImpl.java index 5ce3593b..50f87699 100644 --- a/src/main/java/com/juick/service/SubscriptionServiceImpl.java +++ b/src/main/java/com/juick/service/SubscriptionServiceImpl.java @@ -25,7 +25,6 @@ import com.juick.util.MessageUtils; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.IteratorUtils; import org.apache.commons.collections4.ListUtils; -import org.apache.commons.lang3.StringUtils; import org.springframework.dao.DuplicateKeyException; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.stereotype.Repository; diff --git a/src/main/java/com/juick/service/UserService.java b/src/main/java/com/juick/service/UserService.java index 0d4efcfc..16afe08f 100644 --- a/src/main/java/com/juick/service/UserService.java +++ b/src/main/java/com/juick/service/UserService.java @@ -22,7 +22,6 @@ import com.juick.User; import com.juick.model.Auth; import javax.annotation.Nonnull; -import java.time.Instant; import java.util.Collection; import java.util.List; import java.util.Optional; diff --git a/src/main/java/com/juick/service/activities/AnnounceEvent.java b/src/main/java/com/juick/service/activities/AnnounceEvent.java index 00dbea8c..7fb2be22 100644 --- a/src/main/java/com/juick/service/activities/AnnounceEvent.java +++ b/src/main/java/com/juick/service/activities/AnnounceEvent.java @@ -3,8 +3,8 @@ package com.juick.service.activities; import org.springframework.context.ApplicationEvent; public class AnnounceEvent extends ApplicationEvent { - private String actorUri; - private String messageUri; + private final String actorUri; + private final String messageUri; public AnnounceEvent(Object source, String actor, String messageUri) { super(source); diff --git a/src/main/java/com/juick/service/component/SystemEvent.java b/src/main/java/com/juick/service/component/SystemEvent.java index 11a10860..f5852ba4 100644 --- a/src/main/java/com/juick/service/component/SystemEvent.java +++ b/src/main/java/com/juick/service/component/SystemEvent.java @@ -1,12 +1,8 @@ package com.juick.service.component; -import com.juick.Message; -import com.juick.User; import com.juick.server.api.SystemActivity; import org.springframework.context.ApplicationEvent; -import java.util.List; - public class SystemEvent extends ApplicationEvent { private SystemActivity activity; /** diff --git a/src/main/java/com/juick/util/DateFormatter.java b/src/main/java/com/juick/util/DateFormatter.java index 8f569562..0a14f3dc 100644 --- a/src/main/java/com/juick/util/DateFormatter.java +++ b/src/main/java/com/juick/util/DateFormatter.java @@ -20,7 +20,6 @@ package com.juick.util; import org.apache.commons.lang3.StringUtils; import java.time.Instant; -import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; diff --git a/src/main/java/com/juick/util/MessageUtils.java b/src/main/java/com/juick/util/MessageUtils.java index 9b668b7c..b922d980 100644 --- a/src/main/java/com/juick/util/MessageUtils.java +++ b/src/main/java/com/juick/util/MessageUtils.java @@ -28,6 +28,7 @@ import org.springframework.web.util.UriComponentsBuilder; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -270,16 +271,12 @@ public class MessageUtils { // TODO: check if it is really needed public static String percentEncode(final String s) { - String ret = StringUtils.EMPTY; - try { - ret = URLEncoder.encode(s, CharEncoding.UTF_8).replace("+", "%20").replace("*", "%2A").replace("%7E", "~"); - } catch (UnsupportedEncodingException e) { - } - return ret; + return URLEncoder.encode(s, StandardCharsets.UTF_8).replace("+", "%20") + .replace("*", "%2A").replace("%7E", "~"); } public static String formatMarkdownText(final Message msg) { - String s = StringUtils.defaultString(msg.getText()).replaceAll(replyNumberRegex, String.format("$1[/$2](https://juick.com/m/%d#$2)$3", msg.getMid())); - return escapeMarkdown(s); + return StringUtils.defaultString(msg.getText()) + .replaceAll(replyNumberRegex, String.format("$1[/$2](https://juick.com/m/%d#$2)$3", msg.getMid())); } public static String escapeMarkdown(final String s) { return s.replace("_", "\\_").replace("*", "\\*") diff --git a/src/main/java/com/juick/util/PrettyTimeFormatter.java b/src/main/java/com/juick/util/PrettyTimeFormatter.java index 383f4d9a..792d185d 100644 --- a/src/main/java/com/juick/util/PrettyTimeFormatter.java +++ b/src/main/java/com/juick/util/PrettyTimeFormatter.java @@ -32,14 +32,12 @@ public class PrettyTimeFormatter { // Cache PrettyTime per locale. LRU cache to prevent memory leak. private static final Map<Locale, PrettyTime> PRETTY_TIME_LOCALE_MAP = - new LinkedHashMap<Locale, PrettyTime>(MAX_CACHE_SIZE + 1, 1.1F, true) - { - @Override - protected boolean removeEldestEntry(Map.Entry<Locale, PrettyTime> eldest) - { - return size() > MAX_CACHE_SIZE; - } - }; + new LinkedHashMap<>(MAX_CACHE_SIZE + 1, 1.1F, true) { + @Override + protected boolean removeEldestEntry(Map.Entry<Locale, PrettyTime> eldest) { + return size() > MAX_CACHE_SIZE; + } + }; public String format(final Locale locale, final Date value) { diff --git a/src/main/java/com/mitchellbosecke/pebble/extension/filters/FormatMessageFilter.java b/src/main/java/com/mitchellbosecke/pebble/extension/filters/FormatMessageFilter.java index 1b75727e..27b9d970 100644 --- a/src/main/java/com/mitchellbosecke/pebble/extension/filters/FormatMessageFilter.java +++ b/src/main/java/com/mitchellbosecke/pebble/extension/filters/FormatMessageFilter.java @@ -18,7 +18,6 @@ package com.mitchellbosecke.pebble.extension.filters; import com.juick.Message; -import com.juick.model.AnonymousUser; import com.juick.util.MessageUtils; import com.mitchellbosecke.pebble.extension.Filter; import com.mitchellbosecke.pebble.extension.escaper.SafeString; @@ -28,7 +27,6 @@ import org.apache.commons.lang3.StringUtils; import java.util.List; import java.util.Map; -import java.util.Optional; /** * Created by vitalyster on 04.05.2017. diff --git a/src/main/java/ru/sape/SapeConnection.java b/src/main/java/ru/sape/SapeConnection.java index a15658fa..ee5a5e5c 100644 --- a/src/main/java/ru/sape/SapeConnection.java +++ b/src/main/java/ru/sape/SapeConnection.java @@ -11,6 +11,7 @@ import java.io.Reader; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.URL; +import java.nio.charset.StandardCharsets; import java.util.*; public class SapeConnection { @@ -48,7 +49,7 @@ public class SapeConnection { connection.setRequestMethod("GET"); connection.connect(); - r = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); + r = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)); StringWriter sw = new StringWriter(); diff --git a/src/test/java/com/juick/server/tests/ServerTests.java b/src/test/java/com/juick/server/tests/ServerTests.java index f89eca81..479ec750 100644 --- a/src/test/java/com/juick/server/tests/ServerTests.java +++ b/src/test/java/com/juick/server/tests/ServerTests.java @@ -296,6 +296,7 @@ public class ServerTests { } MockitoAnnotations.initMocks(this); } + @After public void teardown() throws IOException { FileSystemUtils.deleteRecursively(Paths.get(imgDir, "p")); @@ -303,6 +304,7 @@ public class ServerTests { FileSystemUtils.deleteRecursively(Paths.get(imgDir, "photos-512")); FileSystemUtils.deleteRecursively(Paths.get(imgDir, "ps")); } + @Test public void getMyFeed() { jdbcTemplate.execute("DELETE FROM telegram"); @@ -312,7 +314,7 @@ public class ServerTests { int mid2 = messagesService.createMessage(ugnich.getUid(), "test2", null, null); List<Integer> freefdFeed = messagesService.getMyFeed(freefd.getUid(), 0, false); assertThat(freefdFeed.get(0), equalTo(mid2)); - User tonya = userService.createUser("Tonya", "secret").orElseThrow(IllegalStateException::new);; + User tonya = userService.createUser("Tonya", "secret").orElseThrow(IllegalStateException::new); int mid3 = messagesService.createMessage(tonya.getUid(), "test3", null, null); messagesService.recommendMessage(mid3, ugnich.getUid()); assertThat(messagesService.getMyFeed(freefd.getUid(), 0, false).get(0), equalTo(mid2)); @@ -352,6 +354,7 @@ public class ServerTests { subscriptionService.subscribeUser(freefd, ugnich); assertThat(subscriptionService.getSubscribedUsers(ugnich.getUid(), mentionMessage).size(), equalTo(1)); } + @Test public void pmTests() { pmQueriesService.createPM(freefd.getUid(), ugnich.getUid(), "hello"); @@ -362,7 +365,7 @@ public class ServerTests { @Test public void messageTests() { - User user = userService.createUser("mmmme", "secret").orElseThrow(IllegalStateException::new);; + User user = userService.createUser("mmmme", "secret").orElseThrow(IllegalStateException::new); assertEquals("it should be me", "mmmme", user.getName()); int mid = messagesService.createMessage(user.getUid(), "yo", null, new ArrayList<>()); Message msg = messagesService.getMessage(mid).get(); @@ -378,7 +381,7 @@ public class ServerTests { Message msg2 = messagesService.getMessage(mid2).get(); assertEquals(1, msg2.getTags().size()); assertEquals("we already have ugnich", Optional.empty(), userService.createUser("ugnich", "x")); - User hugnich = userService.createUser("hugnich", "x").orElseThrow(IllegalStateException::new);; + User hugnich = userService.createUser("hugnich", "x").orElseThrow(IllegalStateException::new); int rid = messagesService.createReply(msg2.getMid(), 0, hugnich, "bla-bla", null); assertEquals(1, rid); assertThat(msg2.getTo(), equalTo(AnonymousUser.INSTANCE)); @@ -421,45 +424,49 @@ public class ServerTests { assertEquals("tags string should be empty", StringUtils.EMPTY, MessageUtils.getTagsString(msg4)); messagesService.deleteMessage(user.getUid(), mid4); } + public ExpectedException exception = ExpectedException.none(); @Test - public void likeTypeStatsTests(){ - User dsdss = userService.createUser("dsdss", "secret").orElseThrow(IllegalStateException::new);; + public void likeTypeStatsTests() { + User dsdss = userService.createUser("dsdss", "secret").orElseThrow(IllegalStateException::new); final int freefdId = freefd.getUid(); int mid = messagesService.createMessage(dsdss.getUid(), "yo", null, new ArrayList<>()); - messagesService.likeMessage(mid, freefdId , 2); - messagesService.likeMessage(mid, freefdId,2); - messagesService.likeMessage(mid, freefdId,3); - messagesService.likeMessage(mid, freefdId,1); + messagesService.likeMessage(mid, freefdId, 2); + messagesService.likeMessage(mid, freefdId, 2); + messagesService.likeMessage(mid, freefdId, 3); + messagesService.likeMessage(mid, freefdId, 1); Message msg4 = messagesService.getMessage(mid).get(); assertThat(msg4.getLikes(), equalTo(1)); Assert.assertEquals(2, msg4.getReactions().stream().filter(r -> r.getId() == 2) .findFirst().orElseThrow(IllegalStateException::new).getCount()); - Assert.assertEquals(1,msg4.getReactions().stream().filter(r -> r.getId() == 3) + Assert.assertEquals(1, msg4.getReactions().stream().filter(r -> r.getId() == 3) .findFirst().orElseThrow(IllegalStateException::new).getCount()); } + @Test public void lastJidShouldNotBeDeleted() { - User hugnich2 = userService.createUser("hugnich2", "x").orElseThrow(IllegalStateException::new);; + User hugnich2 = userService.createUser("hugnich2", "x").orElseThrow(IllegalStateException::new); jdbcTemplate.update("INSERT INTO jids(user_id,jid,active) VALUES(?,?,?)", hugnich2.getUid(), "firstjid@localhost", 1); jdbcTemplate.update("INSERT INTO jids(user_id,jid,active) VALUES(?,?,?)", hugnich2.getUid(), "secondjid@localhost", 1); assertThat(userService.deleteJID(hugnich2.getUid(), "secondjid@localhost"), equalTo(true)); assertThat(userService.deleteJID(hugnich2.getUid(), "firstjid@localhost"), equalTo(false)); } + @Test public void lastEmailShouldNotBeDeleted() { - User hugnich3 = userService.createUser("hugnich3", "x").orElseThrow(IllegalStateException::new);; + User hugnich3 = userService.createUser("hugnich3", "x").orElseThrow(IllegalStateException::new); jdbcTemplate.update("INSERT INTO emails(user_id,email) VALUES(?,?)", hugnich3.getUid(), "first@localhost"); jdbcTemplate.update("INSERT INTO emails(user_id,email) VALUES(?,?)", hugnich3.getUid(), "second@localhost"); assertThat(emailService.deleteEmail(hugnich3.getUid(), "second@localhost"), equalTo(true)); assertThat(emailService.deleteEmail(hugnich3.getUid(), "first@localhost"), equalTo(false)); } + @Test public void messageUpdatedTimeShouldMatchLastReplyTime() throws InterruptedException { - User hugnich4 = userService.createUser("hugnich4", "x").orElseThrow(IllegalStateException::new);; + User hugnich4 = userService.createUser("hugnich4", "x").orElseThrow(IllegalStateException::new); int mid = messagesService.createMessage(hugnich4.getUid(), "yo", null, null); Instant ts = jdbcTemplate.queryForObject("SELECT updated FROM messages WHERE message_id=?", Timestamp.class, mid).toInstant(); @@ -480,7 +487,7 @@ public class ServerTests { mockMvc.perform(get("/api/auth")) .andExpect(status().isUnauthorized()) - .andExpect(header().exists("WwW-Authenticate")); + .andExpect(header().exists("WwW-Authenticate")); mockMvc.perform(get("/api/home")) .andExpect(status().isUnauthorized()); @@ -580,17 +587,17 @@ public class ServerTests { @Test public void messagesUrlTest() throws Exception { - User dsds4345 = userService.createUser("dsds4345", "secret").orElseThrow(IllegalStateException::new);; + User dsds4345 = userService.createUser("dsds4345", "secret").orElseThrow(IllegalStateException::new); String freefdHash = userService.getHashByUID(freefd.getUid()); String userIdHash = userService.getHashByUID(dsds4345.getUid()); final int freefdId = freefd.getUid(); int mid = messagesService.createMessage(dsds4345.getUid(), "yo", null, new ArrayList<>()); - messagesService.likeMessage(mid, freefdId, 2 ); - messagesService.likeMessage(mid, freefdId, 2 ); - messagesService.likeMessage(mid, freefdId, 3 ); + messagesService.likeMessage(mid, freefdId, 2); + messagesService.likeMessage(mid, freefdId, 2); + messagesService.likeMessage(mid, freefdId, 3); - mockMvc.perform(get("/api/messages?"+ "hash=" + userIdHash)) + mockMvc.perform(get("/api/messages?" + "hash=" + userIdHash)) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) @@ -615,7 +622,8 @@ public class ServerTests { .andExpect(status().isOk()) .andReturn(); List<TagStats> tagsFromApi = jsonMapper.readValue(result.getResponse().getContentAsString(), - new TypeReference<List<TagStats>>(){}); + new TypeReference<List<TagStats>>() { + }); 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") @@ -623,7 +631,8 @@ public class ServerTests { .andExpect(status().isOk()) .andReturn(); List<TagStats> ugnichTagsFromApi = jsonMapper.readValue(result2.getResponse().getContentAsString(), - new TypeReference<List<TagStats>>(){}); + new TypeReference<List<TagStats>>() { + }); TagStats yoUgnichStats = ugnichTagsFromApi.stream().filter(t -> t.getTag().getName().equals("yo")).findFirst().get(); assertThat(yoUgnichStats.getUsageCount(), is(1)); } @@ -635,11 +644,13 @@ public class ServerTests { .with(httpBasic(ugnichName, ugnichPassword))) .andExpect(status().isOk()); } + @Test public void threadWithEphemeralNumberShouldReturn404() throws Exception { mockMvc.perform(get("/api/thread").param("mid", "999999999") - .with(httpBasic(ugnichName, ugnichPassword))).andExpect(status().is4xxClientError()); + .with(httpBasic(ugnichName, ugnichPassword))).andExpect(status().is4xxClientError()); } + @Test public void performRequestsWithIssuedToken() throws Exception { String ugnichHash = userService.getHashByUID(ugnich.getUid()); @@ -655,6 +666,7 @@ public class ServerTests { assertThat(authHash, equalTo(ugnichHash)); mockMvc.perform(get("/api/home").param("hash", ugnichHash)).andExpect(status().isOk()); } + @Test public void registerForNotificationsTests() throws Exception { String token = "123456"; @@ -675,31 +687,35 @@ public class ServerTests { assertThat(users.get(0).getTokens().size(), is(1)); assertThat(users.get(0).getTokens().get(0).getToken(), equalTo(token)); } + @Test public void tg2juickLinks() { UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://juick.com/m/123456#23").build(); assertThat(uriComponents.getPath().substring(3), is("123456")); assertThat(uriComponents.getFragment(), is("23")); } + @Test public void notificationsTokensTest() throws Exception { List<ExternalToken> tokens = Collections.singletonList(new ExternalToken(null, "gcm", "123456", null)); mockMvc.perform(delete("/api/notifications").with(httpBasic(ugnichName, ugnichPassword)) - .contentType(MediaType.APPLICATION_JSON) - .content(jsonMapper.writeValueAsBytes(tokens))).andExpect(status().isForbidden()); + .contentType(MediaType.APPLICATION_JSON) + .content(jsonMapper.writeValueAsBytes(tokens))).andExpect(status().isForbidden()); mockMvc.perform(delete("/api/notifications").with(httpBasic(juickName, juickPassword)) .contentType(MediaType.APPLICATION_JSON) .content(jsonMapper.writeValueAsBytes(tokens))).andExpect(status().isOk()); } + @Test public void notificationsSettingsAllowedOnlyForServiceUser() throws Exception { CommandResult result = commandsManager.processCommand(ugnich, "yo", emptyUri); String stringValueOfMid = String.valueOf(result.getNewMessage().get().getMid()); mockMvc.perform(get("/api/notifications").with(httpBasic(juickName, juickPassword)) - .param("mid", stringValueOfMid).param("uid", String.valueOf(ugnich.getUid()))).andExpect(status().isOk()); + .param("mid", stringValueOfMid).param("uid", String.valueOf(ugnich.getUid()))).andExpect(status().isOk()); mockMvc.perform(get("/api/notifications") .param("mid", stringValueOfMid).param("uid", String.valueOf(ugnich.getUid()))).andExpect(status().isUnauthorized()); } + @Test public void topTest() { int topmid = messagesService.createMessage(ugnich.getUid(), "top message", null, null); @@ -724,6 +740,7 @@ public class ServerTests { tagService.updateTags(topmid, Collections.singletonList(nsfw)); assertThat(messagesService.getPopularCandidates().isEmpty(), is(true)); } + @Test public void inReplyToScannerTest() { String header = "<123456.56@juick.com>"; @@ -733,6 +750,7 @@ public class ServerTests { assertThat(mid, equalTo(123456)); assertThat(rid, equalTo(56)); } + @Test public void lastMessagesTest() throws Exception { mockMvc.perform( @@ -741,6 +759,7 @@ public class ServerTests { .andExpect(content().contentType("application/rss+xml;charset=UTF-8")) .andExpect(xpath("/rss/channel/description").string("The latest messages at Juick")); } + @Test public void botCommandsTests() throws Exception { assertThat(commandsManager.processCommand(AnonymousUser.INSTANCE, "PING", emptyUri).getText(), is("PONG")); @@ -750,7 +769,7 @@ public class ServerTests { @Test public void protocolTests() throws Exception { - User user = userService.createUser("me", "secret").orElseThrow(IllegalStateException::new);; + User user = userService.createUser("me", "secret").orElseThrow(IllegalStateException::new); Tag yo = tagService.getTag("yo", true); Message msg = commandsManager.processCommand(user, "*yo yoyo", URI.create("https://static.juick.com/settings/facebook.png")).getNewMessage().get(); assertThat(msg.getAttachmentType(), is("png")); @@ -769,7 +788,7 @@ public class ServerTests { assertThat(last.toInstant(), equalTo(yoyoMsg.getNewMessage().get().getCreated())); assertEquals("should be message", true, commandsManager.processCommand(user, String.format("#%d", mid), emptyUri).getText().startsWith("@me")); - User readerUser = userService.createUser("dummyReader", "dummySecret").orElseThrow(IllegalStateException::new);; + User readerUser = userService.createUser("dummyReader", "dummySecret").orElseThrow(IllegalStateException::new); assertThat(commandsManager.processCommand(readerUser, "s", emptyUri).getText().startsWith("You are subscribed to"), is(true)); assertThat(commandsManager.processCommand(readerUser, "S", emptyUri).getText().startsWith("You are subscribed to"), is(true)); assertEquals("should be subscribed", "Subscribed", @@ -827,7 +846,7 @@ public class ServerTests { commandsManager.processCommand(user, "#" + mid + " *there", emptyUri).getText()); assertEquals("number of tags should match", 1, tagService.getMessageTags(mid).size()); - User taggerUser = userService.createUser("dummyTagger", "dummySecret").orElseThrow(IllegalStateException::new);; + User taggerUser = userService.createUser("dummyTagger", "dummySecret").orElseThrow(IllegalStateException::new); assertEquals("should be subscribed", "Subscribed", commandsManager.processCommand(taggerUser, "S *yo", emptyUri).getText()); assertEquals("number of subscribed users should match", 2, @@ -898,6 +917,7 @@ public class ServerTests { assertThat(result.getNewMessage(), is(Optional.empty())); assertThat(result.getText(), is("User not found")); } + @Test public void mailParserTest() throws Exception { emailService.addEmail(ugnich.getUid(), "ugnich@example.com"); @@ -969,22 +989,22 @@ public class ServerTests { } @Test - public void likesTests() throws Exception{ - User dsds = userService.createUser("dsds", "secret").orElseThrow(IllegalStateException::new);; - String freefdHash = userService.getHashByUID(freefd.getUid()); - int mid1 = messagesService.createMessage(dsds.getUid(), "yo", null, new ArrayList<>()); + public void likesTests() throws Exception { + User dsds = userService.createUser("dsds", "secret").orElseThrow(IllegalStateException::new); + String freefdHash = userService.getHashByUID(freefd.getUid()); + int mid1 = messagesService.createMessage(dsds.getUid(), "yo", null, new ArrayList<>()); - mockMvc.perform(post("/api/react?mid=" + mid1 + "&hash=" + freefdHash+ "&reactionId=2")) - .andExpect(status().isOk()); + mockMvc.perform(post("/api/react?mid=" + mid1 + "&hash=" + freefdHash + "&reactionId=2")) + .andExpect(status().isOk()); - Message msg4 = messagesService.getMessage(mid1).get(); - assertThat(msg4.getLikes(), is(0)); - assertThat(messagesService.getMessages(AnonymousUser.INSTANCE, Collections.singletonList(mid1)).get(0).getLikes(), is(0)); - Assert.assertEquals(1, msg4.getReactions().stream().filter(r -> r.getId() == 2) - .findFirst().orElseThrow(IllegalStateException::new).getCount()); - mockMvc.perform(post("/api/react?mid=" + mid1 + "&hash=" + freefdHash+ "&reactionId=1")) + Message msg4 = messagesService.getMessage(mid1).get(); + assertThat(msg4.getLikes(), is(0)); + assertThat(messagesService.getMessages(AnonymousUser.INSTANCE, Collections.singletonList(mid1)).get(0).getLikes(), is(0)); + Assert.assertEquals(1, msg4.getReactions().stream().filter(r -> r.getId() == 2) + .findFirst().orElseThrow(IllegalStateException::new).getCount()); + mockMvc.perform(post("/api/react?mid=" + mid1 + "&hash=" + freefdHash + "&reactionId=1")) .andExpect(status().isOk()); - mockMvc.perform(post("/api/react?mid=" + mid1 + "&hash=" + freefdHash+ "&reactionId=1")) + mockMvc.perform(post("/api/react?mid=" + mid1 + "&hash=" + freefdHash + "&reactionId=1")) .andExpect(status().isOk()); assertThat(messagesService.getMessage(mid1).get().getLikes(), is(1)); } @@ -1030,6 +1050,7 @@ public class ServerTests { .andExpect(status().isOk()); assertThat(lastRead.apply(ugnich, mid), is(newfreefdrid)); } + @Test public void feedsShouldNotContainMessagesWithBannedTags() { Tag banned = tagService.getTag("banned", true); @@ -1051,7 +1072,7 @@ public class ServerTests { .stream().noneMatch(m -> m.getTags().contains(banned))); assertTrue(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getMyFeed(freefd.getUid(), 0, true)) .stream().noneMatch(m -> m.getTags().contains(banned))); - User newUser1 = userService.createUser("newUser1", "12345").orElseThrow(IllegalStateException::new);; + User newUser1 = userService.createUser("newUser1", "12345").orElseThrow(IllegalStateException::new); int newMid = messagesService.createMessage(newUser1.getUid(), "people", null, Collections.singletonList(banned)); messagesService.recommendMessage(newMid, ugnich.getUid()); assertTrue(messagesService.getMessages(AnonymousUser.INSTANCE, messagesService.getMyFeed(freefd.getUid(), 0, true)) @@ -1062,6 +1083,7 @@ public class ServerTests { assertTrue(messagesService.getMyFeed(freefd.getUid(), 0, true) .stream().noneMatch(m -> m == newMid)); } + @Test public void tagsShouldBeDeserializedFromXml() throws JAXBException { XmppSessionConfiguration configuration = XmppSessionConfiguration.builder() @@ -1088,6 +1110,7 @@ public class ServerTests { 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"; @@ -1139,12 +1162,14 @@ public class ServerTests { }); assertThat(fromApi.get(0).getTags(), is(tags)); } + @Test public void emptyAuthenticatedPostShouldThrowBadRequest() throws Exception { mockMvc.perform(post("/api/post") .with(httpBasic(juickName, juickPassword))) .andExpect(status().isBadRequest()); } + @Test public void attachmentSizeTests() throws IOException { ImageUtils imageUtils = new ImageUtils(StringUtils.EMPTY, StringUtils.EMPTY); @@ -1152,6 +1177,7 @@ public class ServerTests { assertThat(attachment.getHeight(), is(1)); assertThat(attachment.getWidth(), is(1)); } + @Test public void meContainsAllInfo() throws Exception { jdbcTemplate.update("DELETE FROM subscr_users"); @@ -1167,6 +1193,7 @@ public class ServerTests { .andExpect(jsonPath("$.readers.length()", is(1))) .andExpect(jsonPath("$.read.length()", is(1))); } + @Test public void feedsShouldNotContainBannedUsers() throws Exception { commandsManager.processCommand(ugnich, "BL @freefd", emptyUri); @@ -1204,6 +1231,7 @@ public class ServerTests { assertThat(messagesService.getTag(tag.TID, ugnich.getUid(), 0, 10).size(), is(0)); commandsManager.processCommand(ugnich, "BL @freefd", emptyUri); } + @Test public void cmykJpegShouldBeProcessedCorrectly() throws Exception { CommandResult postJpgCmyk = commandsManager.processCommand(ugnich, "YO", cmykJpeg.getURI()); @@ -1218,6 +1246,7 @@ public class ServerTests { assertThat(postJpgCmyk.getNewMessage().get().getAttachment().getMedium().getHeight(), is(1024)); assertThat(postJpgCmyk.getNewMessage().get().getAttachment().getSmall().getHeight(), is(512)); } + @Test public void JpegWithoutJfifShouldBeProcessedCorrectly() throws Exception { CommandResult postJpgCmyk = commandsManager.processCommand(ugnich, "YO", nojfif.getURI()); @@ -1232,6 +1261,7 @@ public class ServerTests { assertThat(postJpgCmyk.getNewMessage().get().getAttachment().getMedium().getHeight(), is(768)); assertThat(postJpgCmyk.getNewMessage().get().getAttachment().getSmall().getHeight(), is(384)); } + @Test public void JpegFromJuickUriShouldBeProcessedCorrectly() throws Exception { Path tmpFile = Paths.get(tmpDir, "2915104.jpg"); @@ -1256,6 +1286,7 @@ public class ServerTests { File mediumFile2 = Paths.get(imgDir, "photos-1024", String.format("%d.jpg", mid2)).toFile(); assertThat(mediumFile2.exists(), is(true)); } + @Test public void changeExtensionWhenReceiveFileWithWrongContentType() throws Exception { Path pngOutput = Paths.get(tmpDir, "cmyk.png"); @@ -1269,10 +1300,11 @@ public class ServerTests { assertThat(replyJpgCmyk.getNewMessage().isPresent(), is(true)); assertThat(replyJpgCmyk.getNewMessage().get().getAttachmentType(), is("jpg")); } + @Test public void messageEditingSpec() throws Exception { MvcResult result = mockMvc.perform(post("/api/post").with(httpBasic(ugnichName, ugnichPassword)) - .param("body", "YO")).andExpect(status().is2xxSuccessful()).andReturn(); + .param("body", "YO")).andExpect(status().is2xxSuccessful()).andReturn(); Message original = jsonMapper.readValue(result.getResponse().getContentAsString(), CommandResult.class) .getNewMessage().get(); assertThat(original.getText(), equalTo("YO")); @@ -1280,8 +1312,8 @@ public class ServerTests { // to have updated_at greater than ts Thread.sleep(1000); result = mockMvc.perform(post("/api/update").with(httpBasic(ugnichName, ugnichPassword)) - .param("mid", String.valueOf(original.getMid())) - .param("body", "PEOPLE")).andExpect(status().is2xxSuccessful()).andReturn(); + .param("mid", String.valueOf(original.getMid())) + .param("body", "PEOPLE")).andExpect(status().is2xxSuccessful()).andReturn(); Message edited = jsonMapper.readValue(result.getResponse().getContentAsString(), CommandResult.class) .getNewMessage().get(); assertThat(edited.getText(), equalTo("PEOPLE")); @@ -1290,8 +1322,8 @@ public class ServerTests { .param("mid", String.valueOf(original.getMid())) .param("body", "PEOPLE")).andExpect(status().is(403)); result = mockMvc.perform(post("/api/comment").with(httpBasic(freefdName, freefdPassword)) - .param("mid", String.valueOf(original.getMid())) - .param("body", "HEY")).andExpect(status().is2xxSuccessful()).andReturn(); + .param("mid", String.valueOf(original.getMid())) + .param("body", "HEY")).andExpect(status().is2xxSuccessful()).andReturn(); CommandResult comment = jsonMapper.readValue(result.getResponse().getContentAsString(), CommandResult.class); assertThat(comment.getNewMessage().get().getText(), is("HEY")); assertThat(comment.getNewMessage().get().getUpdatedAt(), is(comment.getNewMessage().get().getCreated())); @@ -1307,12 +1339,13 @@ public class ServerTests { assertThat(editedComment.getUpdatedAt(), greaterThan(editedComment.getCreated())); messagesService.deleteMessage(ugnich.getUid(), original.getMid()); } + @Test public void subscribersToRecommendations() { - User reader = userService.createUser("reader", "123456").orElseThrow(IllegalStateException::new);; - User recommender = userService.createUser("recommender", "123456").orElseThrow(IllegalStateException::new);; - User lateRecommender = userService.createUser("lateRecommender", "123456").orElseThrow(IllegalStateException::new);; - User poster = userService.createUser("poster", "123456").orElseThrow(IllegalStateException::new);; + User reader = userService.createUser("reader", "123456").orElseThrow(IllegalStateException::new); + User recommender = userService.createUser("recommender", "123456").orElseThrow(IllegalStateException::new); + User lateRecommender = userService.createUser("lateRecommender", "123456").orElseThrow(IllegalStateException::new); + User poster = userService.createUser("poster", "123456").orElseThrow(IllegalStateException::new); subscriptionService.subscribeUser(reader, recommender); subscriptionService.subscribeUser(reader, lateRecommender); Tag sampleTag = tagService.getTag("banned", true); @@ -1338,11 +1371,12 @@ public class ServerTests { messagesService.recommendMessage(readerMid, recommender.getUid()); assertThat(subscribers.apply(recommender.getUid(), messagesService.getMessage(readerMid).get()).size(), is(0)); } + @Test public void mentionsInComments() { - User poster = userService.createUser("p", "secret").orElseThrow(IllegalStateException::new);; - User commenter = userService.createUser("cc", "secret").orElseThrow(IllegalStateException::new);; - User mentioner = userService.createUser("mmm", "secret").orElseThrow(IllegalStateException::new);; + User poster = userService.createUser("p", "secret").orElseThrow(IllegalStateException::new); + User commenter = userService.createUser("cc", "secret").orElseThrow(IllegalStateException::new); + User mentioner = userService.createUser("mmm", "secret").orElseThrow(IllegalStateException::new); int mid = messagesService.createMessage(poster.getUid(), "who is dick?", null, null); Message msg = messagesService.getMessage(mid).get(); int rid = messagesService.createReply(mid, 0, commenter, @@ -1354,9 +1388,10 @@ public class ServerTests { privacyQueriesService.blacklistUser(mentioner, commenter); assertThat(subscriptionService.getUsersSubscribedToComments(msg, reply).size(), is(0)); } + @Test public void credentialsShouldNeverBeSerialized() throws Exception { - User yyy = userService.createUser("yyy", "xxxx").orElseThrow(IllegalStateException::new);; + User yyy = userService.createUser("yyy", "xxxx").orElseThrow(IllegalStateException::new); assertThat(yyy.getCredentials(), is("xxxx")); ObjectMapper jsonMapper = new ObjectMapper(); jsonMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT); @@ -1380,6 +1415,7 @@ public class ServerTests { // uid, name, xmlns, xmlns:user assertThat(attrs.getLength(), is(4)); } + @Test public void bannedUserBlogandPostShouldReturn404() throws Exception { String userName = "isilmine"; @@ -1414,13 +1450,14 @@ public class ServerTests { .param("password", userPassword)).andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/login?error=1")); } + @Test public void bannedUserShouldBeShadowedFromRecommendationsList() throws IOException { jdbcTemplate.execute("DELETE FROM bl_users"); - User ermine = userService.createUser("ermine", "secret").orElseThrow(IllegalStateException::new);; - User monstreek = userService.createUser("monstreek", "secret").orElseThrow(IllegalStateException::new);; - User pogo = userService.createUser("pogo", "secret").orElseThrow(IllegalStateException::new);; - User fmap = userService.createUser("fmap", "secret").orElseThrow(IllegalStateException::new);; + User ermine = userService.createUser("ermine", "secret").orElseThrow(IllegalStateException::new); + User monstreek = userService.createUser("monstreek", "secret").orElseThrow(IllegalStateException::new); + User pogo = userService.createUser("pogo", "secret").orElseThrow(IllegalStateException::new); + User fmap = userService.createUser("fmap", "secret").orElseThrow(IllegalStateException::new); int mid = messagesService.createMessage(monstreek.getUid(), "KURWA", null, null); assertThat(messagesService.recommendMessage(mid, ermine.getUid()), is(MessagesService.RecommendStatus.Added)); assertThat(messagesService.recommendMessage(mid, fmap.getUid()), is(MessagesService.RecommendStatus.Added)); @@ -1430,21 +1467,22 @@ public class ServerTests { assertThat(messagesService.getMessage(mid).get().getLikes(), is(4)); assertThat(CollectionUtils.isEqualCollection(messagesService.getMessagesRecommendations( Collections.singletonList(mid)) - .stream().map(p -> p.getRight()).map(User::getName).collect(Collectors.toList()), + .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")); assertThat(messagesService.getMessage(mid).get().getLikes(), is(4)); assertThat(CollectionUtils.isEqualCollection(messagesService.getMessagesRecommendations( Collections.singletonList(mid)) - .stream().map(p -> p.getRight()).map(User::getName).collect(Collectors.toList()), + .stream().map(p -> p.getRight()).map(User::getName).collect(Collectors.toList()), Arrays.asList("fmap", "ermine", "Anonymous")), is(true)); } + @Test public void bannedUserShouldNotBeVisibleToOthers() { jdbcTemplate.execute("DELETE FROM messages"); - User casualUser = userService.createUser("user", "secret").orElseThrow(IllegalStateException::new);; - User bannedUser = userService.createUser("banned", "banned").orElseThrow(IllegalStateException::new);; + User casualUser = userService.createUser("user", "secret").orElseThrow(IllegalStateException::new); + User bannedUser = userService.createUser("banned", "banned").orElseThrow(IllegalStateException::new); jdbcTemplate.update("UPDATE users SET banned=1 WHERE id=?", bannedUser.getUid()); messagesService.createMessage(bannedUser.getUid(), "KURWA", null, Collections.emptyList()); assertThat(messagesService.getAll(casualUser.getUid(), 0).size(), is(0)); @@ -1471,14 +1509,15 @@ public class ServerTests { mockMvc.perform(get("/.well-known/webfinger?resource=acct:durov@localhost")) .andExpect(status().isNotFound()); } + @Test public void userProfileAndBlogShouldBeExposedAsActivityStream() throws Exception { ClassPathResource defaultAvatar = new ClassPathResource("static/av-96.png"); String hash = DigestUtils.md5DigestAsHex(IOUtils.toByteArray(defaultAvatar.getInputStream())); mockMvc.perform(get("/u/ugnich").accept(Context.LD_JSON_MEDIA_TYPE)) .andExpect(status().isOk()) - .andExpect(jsonPath("$.icon.url", is(String.format("http://localhost:8080/av-96-%s.png", hash)))) - .andExpect(jsonPath("$.publicKey.publicKeyPem", is(keystoreManager.getPublicKeyPem()))); + .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(), @@ -1488,8 +1527,9 @@ public class ServerTests { mockMvc.perform(get("/u/ugnich/blog").accept(Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE)) .andExpect(status().isOk()) .andExpect(jsonPath("$.orderedItems", hasSize(20))) - .andExpect(jsonPath("$.next", is("http://localhost:8080/u/ugnich/blog?before=" + midsPage.get(midsPage.size() - 1)))); + .andExpect(jsonPath("$.next", is("http://localhost:8080/u/ugnich/blog?before=" + midsPage.get(midsPage.size() - 1)))); } + @Test public void postWithoutTagsShouldNotHaveAsteriskInTitle() throws Exception { String msgText = "Привет, я - Угнич"; @@ -1497,11 +1537,12 @@ public class ServerTests { HtmlPage threadPage = webClient.getPage(String.format("http://localhost:8080/ugnich/%d", mid)); assertThat(threadPage.getTitleText(), equalTo("ugnich:")); } + @Test public void repliesList() throws IOException { int mid = messagesService.createMessage(ugnich.getUid(), "hello", null, null); IntStream.range(1, 15).forEach(i -> - messagesService.createReply(mid, i-1, freefd, String.valueOf(i-1), null )); + 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)); @@ -1512,6 +1553,7 @@ public class ServerTests { }).count(); assertThat(visibleItems, equalTo(14L)); } + @Test public void userShouldNotSeeReplyButtonToBannedUser() throws Exception { int mid = messagesService.createMessage(ugnich.getUid(), "freefd bl me", null, null); @@ -1533,12 +1575,13 @@ public class ServerTests { privacyQueriesService.blacklistUser(freefd, ugnich); assertThat(userService.isInBLAny(freefd.getUid(), ugnich.getUid()), equalTo(true)); User renha = userService.createUser("renha", "secret").orElseThrow(IllegalStateException::new); - messagesService.createReply(mid, 0, renha,"people", null); + messagesService.createReply(mid, 0, renha, "people", null); threadPage = webClient.getPage(String.format("http://localhost:8080/ugnich/%d", mid)); assertThat(threadPage.getWebResponse().getStatusCode(), equalTo(200)); assertThat(threadPage.querySelectorAll(".msg-comment-target").isEmpty(), equalTo(true)); assertThat(threadPage.querySelectorAll(".a-thread-comment").isEmpty(), equalTo(true)); } + @Test public void correctTagsEscaping() throws PebbleException, IOException { PebbleTemplate template = pebbleEngine.getTemplate("views/test"); @@ -1556,6 +1599,7 @@ public class ServerTests { return page.getElementsByTagName("meta").stream() .filter(t -> t.getAttribute("name").equals(name)).findFirst().orElse(emptyMeta); } + @Test public void testTwitterCards() throws Exception { @@ -1571,6 +1615,7 @@ public class ServerTests { .getAttribute("content"), startsWith(StringEscapeUtils.escapeHtml4(MessageUtils.getMessageHashTags(message)))); } + @Test public void hashLoginShouldNotUseSession() throws Exception { String hash = userService.getHashByUID(ugnich.getUid()); @@ -1592,10 +1637,12 @@ public class ServerTests { .andExpect(model().attribute("visitor", hasProperty("authHash", equalTo(hash)))) .andExpect(content().string(containsString(hash))); } + @Test public void nonExistentBlogShouldReturn404() throws Exception { mockMvc.perform(get("/ololoe/")).andExpect(status().isNotFound()); } + @Test public void discussionsShouldBePageableByTimestamp() throws Exception { String msgText = "Привет, я снова Угнич"; @@ -1647,6 +1694,7 @@ public class ServerTests { assertThat(discussionsOld.querySelectorAll("article") .get(0).getAttributes().getNamedItem("data-mid").getNodeValue(), is(String.valueOf(mid))); } + @Test public void redirectParamShouldCorrectlyRedirectLoggedUser() throws Exception { MvcResult formLoginResult = mockMvc.perform(post("/login") @@ -1661,6 +1709,7 @@ public class ServerTests { .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/login/success")); } + @Test public void anythingRedirects() throws Exception { int mid = messagesService.createMessage(ugnich.getUid(), "yo", null, null); @@ -1668,6 +1717,7 @@ public class ServerTests { .andExpect(status().isMovedPermanently()) .andExpect(redirectedUrl(String.format("/%s/%d", ugnich.getName(), mid))); } + @Test public void appAssociationsTest() throws Exception { mockMvc.perform((get("/.well-known/apple-app-site-association"))) @@ -1675,6 +1725,7 @@ public class ServerTests { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.webcredentials.apps[0]", is(appId))); } + @Test public void notificationsTests() throws Exception { jdbcTemplate.execute("DELETE FROM messages"); @@ -1698,15 +1749,17 @@ public class ServerTests { HtmlPage unreadThread = webClient.getPage(String.format("http://localhost:8080/ugnich/%d", mid)); assertThat(unreadThread.querySelectorAll("#global a .badge").size(), is(0)); } + @Test public void escapeSqlTests() { String sql = String.format("SELECT * FROM table WHERE data='%s'", Utils.encodeSphinx("';-- DROP TABLE table")); assertThat(sql, is("SELECT * FROM table WHERE data='\\';-- DROP TABLE table\'")); } + @Test public void swaggerOutput() throws Exception { MvcResult result = mockMvc.perform(get("/v2/api-docs") - .accept(MediaType.APPLICATION_JSON)) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn(); String outputDir = System.getProperty("io.springfox.staticdocs.outputDir"); @@ -1717,40 +1770,43 @@ public class ServerTests { writer.flush(); } } + @Test public void newMessageShouldNotContainDuplicatedTags() throws Exception { CommandResult result = commandsManager.processCommand(ugnich, "*test1 *test2 *test1 test3", emptyUri); assertThat(result.getNewMessage().isPresent(), is(true)); Message msg = result.getNewMessage().get(); List<Tag> tags = new ArrayList<>(msg.getTags()); - assertThat(tags.size(), is (2)); + assertThat(tags.size(), is(2)); assertThat(tags.get(0).getName(), is("test1")); assertThat(tags.get(1).getName(), is("test2")); assertThat(msg.getText(), is("test3")); } + @Test public void oneClickUnsubscribe() throws Exception { mockMvc.perform(post("/settings/unsubscribe") .param("hash", "123456") .param("List-Unsubscribe", "One-Click")).andExpect(status().isBadRequest()); mockMvc.perform(post("/settings/unsubscribe") - .param("hash", userService.getHashByUID(ugnich.getUid())) - .param("List-Unsubscribe", "One-Click")).andExpect(status().isOk()); + .param("hash", userService.getHashByUID(ugnich.getUid())) + .param("List-Unsubscribe", "One-Click")).andExpect(status().isOk()); } + @Test public void ActivityDeserialization() throws IOException { String followJsonStr = IOUtils.toString(new ClassPathResource("follow.json").getURI(), StandardCharsets.UTF_8); - Follow follow = (Follow)jsonMapper.readValue(followJsonStr, Context.class); + Follow follow = (Follow) jsonMapper.readValue(followJsonStr, Context.class); String personJsonStr = IOUtils.toString(new ClassPathResource("person.json").getURI(), StandardCharsets.UTF_8); - Person person = (Person)jsonMapper.readValue(personJsonStr, Context.class); + Person person = (Person) jsonMapper.readValue(personJsonStr, Context.class); String undoJsonStr = IOUtils.toString(new ClassPathResource("undo.json").getURI(), StandardCharsets.UTF_8); Undo undo = jsonMapper.readValue(undoJsonStr, Undo.class); - String undoFollower = (String)((Map)undo.getObject()).get("object"); + String undoFollower = (String) ((Map) undo.getObject()).get("object"); String createJsonStr = IOUtils.toString(new ClassPathResource("create.json").getURI(), StandardCharsets.UTF_8); Create create = jsonMapper.readValue(createJsonStr, Create.class); Map<String, Object> note = (Map<String, Object>) create.getObject(); - Map<String, Object> attachmentObj = (Map<String, Object> )((List<Object>) note.get("attachment")).get(0); - String attachment = attachmentObj != null ? (String)attachmentObj.get("url") : StringUtils.EMPTY; + Map<String, Object> attachmentObj = (Map<String, Object>) ((List<Object>) note.get("attachment")).get(0); + String attachment = attachmentObj != null ? (String) attachmentObj.get("url") : StringUtils.EMPTY; 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", "", null); @@ -1773,10 +1829,11 @@ public class ServerTests { Like like = jsonMapper.readValue(IOUtils.toString(new ClassPathResource("like.json").getURI(), StandardCharsets.UTF_8), Like.class); String undoPleromaStr = IOUtils.toString(new ClassPathResource("undo_pleroma.json").getURI(), StandardCharsets.UTF_8); Undo undoPleroma = jsonMapper.readValue(undoPleromaStr, Undo.class); - String undoPleromaFollower = (String)((Map)undoPleroma.getObject()).get("object"); + String undoPleromaFollower = (String) ((Map) undoPleroma.getObject()).get("object"); String deletev3JsonStr = IOUtils.toString(new ClassPathResource("delete_v3.json").getURI(), StandardCharsets.UTF_8); Delete deleteObject = jsonMapper.readValue(deletev3JsonStr, Delete.class); } + @Test public void activitySerialization() throws Exception { Message msgNoTags = commandsManager.processCommand(ugnich, "people", emptyUri).getNewMessage().get(); @@ -1799,6 +1856,7 @@ public class ServerTests { Message replyToExt = commandsManager.processCommand(ugnich, String.format("#%d/1 PSSH YOBA ETO TI", msg.getMid()), emptyUri).getNewMessage().get(); json = jsonMapper.writeValueAsString(Context.build(activityPubManager.makeNote(messagesService.getReply(replyToExt.getMid(), replyToExt.getRid())))); } + @Test public void signingSpec() throws IOException { Person from = (Person) signatureManager.getContext(URI.create("http://localhost:8080/u/freefd")).get(); @@ -1808,6 +1866,7 @@ public class ServerTests { follow.setObject("http://localhost:8080/u/ugnich"); signatureManager.post(from, to, follow); } + @Test public void serviceSignatureAuth() throws Exception { String meUri = "/api/me"; @@ -1838,7 +1897,7 @@ public class ServerTests { .andRespond(withSuccess(testuserResponseString, MediaType.APPLICATION_JSON)); restServiceServer.expect(times(3), requestTo(testuserkeyUri)) .andRespond(withSuccess(testuserResponseString, MediaType.APPLICATION_JSON)); - Person testuser = (Person)signatureManager.getContext(testuserUri).get(); + Person testuser = (Person) signatureManager.getContext(testuserUri).get(); Assert.assertThat(testuser.getPublicKey().getPublicKeyPem(), is(testKeystoreManager.getPublicKeyPem())); Instant now2 = Instant.now(); String testRequestDate = DateFormattersHolder.getHttpDateFormatter().format(now2); @@ -1862,6 +1921,7 @@ public class ServerTests { .andExpect(status().isUnauthorized()); apClient.setRequestFactory(originalRequestFactory); } + @Test public void hostmeta() throws Exception { MvcResult result = mockMvc.perform(get("/.well-known/host-meta")) @@ -1870,6 +1930,7 @@ public class ServerTests { result = mockMvc.perform(get("/.well-known/x-nodeinfo2")) .andExpect(status().isOk()).andReturn(); } + @Test public void pms() throws Exception { jdbcTemplate.execute("DELETE FROM pm"); @@ -1878,31 +1939,34 @@ public class ServerTests { assertThat(res.getNewMessage(), is(Optional.empty())); assertThat(res.getText(), is("Private message sent")); MvcResult result = mockMvc.perform(get("/api/groups_pms") - .with(httpBasic(freefdName, freefdPassword))) + .with(httpBasic(freefdName, freefdPassword))) .andExpect(status().isOk()) .andReturn(); PrivateChats chats = jsonMapper.readValue(result.getResponse().getContentAsString(), PrivateChats.class); assertThat(chats.getUsers().size(), is(1)); } + @Test public void seenTests() { Instant now = Instant.now(); - User newUser = userService.createUser("newuser", "assword").orElseThrow(IllegalStateException::new);; + User newUser = userService.createUser("newuser", "assword").orElseThrow(IllegalStateException::new); assertThat(newUser.getUid(), greaterThanOrEqualTo(0)); assertThat(newUser.getSeen(), is(nullValue())); messagesService.createMessage(newUser.getUid(), "YO", "", null); assertThat(userService.getUserByUID(newUser.getUid()).get().getSeen(), greaterThanOrEqualTo(now)); } + @Test public void signupTest() throws Exception { emailService.addVerificationCode(null, "demo@email.com", "123456"); MvcResult result = mockMvc.perform(post("/api/signup") - .param("username", "testuser") - .param("password", "demopassword") - .param("verificationCode", "123456")).andExpect(status().isOk()).andReturn(); + .param("username", "testuser") + .param("password", "demopassword") + .param("verificationCode", "123456")).andExpect(status().isOk()).andReturn(); com.juick.User testuser = jsonMapper.readValue(result.getResponse().getContentAsString(), User.class); assertThat(testuser.getName(), is("testuser")); } + @Test public void doNotAllowRepliesToNonExistingReplyAndNotAllowToEditTagsOfComment() throws Exception { assertThat(commandsManager.processCommand(ugnich, "#23213213/2 BAD COMMENT", emptyUri).getText(), is("Message not found")); @@ -1930,6 +1994,7 @@ public class ServerTests { .andExpect(status().isOk()) .andExpect(content().string(containsString("XMPP support is disabled"))); } + @Test public void ActivityPubLikesShouldNotMirrorMessage() throws Exception { jdbcTemplate.execute("DELETE FROM messages"); @@ -1940,12 +2005,14 @@ public class ServerTests { List<Message> top = messagesService.getMessages(ugnich, messagesService.getPopular(ugnich.getUid(), 0)); assertThat(top.size(), is(1)); } + @Test - public void verifiedUsersTest(){ + public void verifiedUsersTest() { assertThat(userService.getUserByName("ugnich").isVerified(), is(false)); jdbcTemplate.update("INSERT INTO facebook(user_id, fb_id) VALUES(?, ?)", ugnich.getUid(), "100001866137681"); assertThat(userService.getUserByName("ugnich").isVerified(), is(true)); } + @Test public void changeProfileOverApi() throws Exception { ClassPathResource defaultAvatar = new ClassPathResource("static/av-96.png"); @@ -1956,7 +2023,7 @@ public class ServerTests { byte[] newAvatarData = IOUtils.toByteArray(newAvatar.getInputStream()); mockMvc.perform(MockMvcRequestBuilders.multipart("/api/me/upload") .file("avatar", newAvatarData) - .with(httpBasic(freefdName, freefdPassword)) + .with(httpBasic(freefdName, freefdPassword)) ).andExpect(status().isOk()); String newHash = DigestUtils.md5DigestAsHex(newAvatarData); URI newUri = Paths.get(imgDir, "ao", String.format("%d.png", freefd.getUid())).toUri(); @@ -2005,6 +2072,7 @@ public class ServerTests { .andExpect(status().isOk()) .andExpect(header().string("Vary", "Accept-Language")); } + @Test public void apiInfo() throws Exception { userService.createUser("tst", "tst"); @@ -2020,6 +2088,7 @@ public class ServerTests { tst = jsonMapper.readValue(result.getResponse().getContentAsString(), User.class); assertThat(tst.getReaders().size(), is(1)); } + @Test public void federatedUserDeletionFlow() throws Exception { String deleteJsonStr = IOUtils.toString(new ClassPathResource("delete_user.json").getURI(), StandardCharsets.UTF_8); @@ -2043,6 +2112,7 @@ public class ServerTests { .andExpect(status().isAccepted()); apClient.setRequestFactory(originalRequestFactory); } + @Test public void handleIncorrectCertificates() throws Exception { String deleteJsonStr = IOUtils.toString(new ClassPathResource("delete_user.json").getURI(), StandardCharsets.UTF_8); @@ -2068,6 +2138,7 @@ public class ServerTests { .andExpect(status().isOk()) .andExpect(content().bytes(IOUtils.toByteArray(defaultAvatar.getInputStream()))); } + @Test public void federatedAttachmentsAsLinks() throws Exception { int mid = messagesService.createMessage(ugnich.getUid(), "test", StringUtils.EMPTY, Collections.emptyList()); @@ -2075,6 +2146,7 @@ public class ServerTests { String activity = IOUtils.toString(noteWithDocument.getInputStream(), StandardCharsets.UTF_8); Announce announce = jsonMapper.readValue(activity, Announce.class); } + @Test public void hubzillaActor() throws Exception { String activity = IOUtils.toString(hubzillaActivity.getInputStream(), StandardCharsets.UTF_8); @@ -2083,6 +2155,7 @@ public class ServerTests { Follow follow = jsonMapper.readValue(followData, Follow.class); assertThat(follow.getActor(), is("https://ussr.win/channel/zlax")); } + @Test public void nodeinfo() throws Exception { MvcResult nodeinfoXRD = mockMvc.perform(get("/.well-known/nodeinfo") @@ -2107,27 +2180,30 @@ public class ServerTests { assertThat(xnodeinfo.get("server"), notNullValue()); assertThat(xnodeinfo.get("software"), nullValue()); } + @Test public void anonymousUserFromZero() { User user = userService.getUserByUID(0).orElse(AnonymousUser.INSTANCE); assertThat(user.isAnonymous(), is(true)); } + @Test public void messagePropertiesTest() { int mid = messagesService.createMessage(ugnich.getUid(), "YO", null, null); - messagesService.setMessageProperty(mid, 0,"tg_id", "YO"); - assertThat(messagesService.getMessageProperty(mid, 0,"tg_id"), is("YO")); - messagesService.setMessageProperty(mid, 0,"tg_id", "YO2"); - assertThat(messagesService.getMessageProperty(mid, 0,"tg_id"), is("YO2")); + messagesService.setMessageProperty(mid, 0, "tg_id", "YO"); + assertThat(messagesService.getMessageProperty(mid, 0, "tg_id"), is("YO")); + messagesService.setMessageProperty(mid, 0, "tg_id", "YO2"); + assertThat(messagesService.getMessageProperty(mid, 0, "tg_id"), is("YO2")); Pair<Integer, Integer> messageId = messagesService.findMessageByProperty("tg_id", "YO2").orElseThrow(); assertThat(messageId.getLeft(), is(mid)); messagesService.setMessageProperty(mid, 0, "tg_id", ""); - assertThat(messagesService.getMessageProperty(mid, 0,"tg_id"), is(StringUtils.EMPTY)); + assertThat(messagesService.getMessageProperty(mid, 0, "tg_id"), is(StringUtils.EMPTY)); int rid = messagesService.createReply(mid, 0, ugnich, "EOPLE", null); messagesService.setMessageProperty(mid, rid, "tg_id", "hrhr"); Pair<Integer, Integer> replyId = messagesService.findMessageByProperty("tg_id", "hrhr").orElseThrow(); assertThat(replyId.getRight(), is(rid)); } + @Test public void forbiddenForAnonymousEndpoints() throws Exception { mockMvc.perform(post("/api/comment")).andExpect(status().isUnauthorized()); @@ -2137,10 +2213,11 @@ public class ServerTests { mockMvc.perform(get("/api/notifications")).andExpect(status().isUnauthorized()); mockMvc.perform(delete("/api/notifications")).andExpect(status().isUnauthorized()); } + @Test public void rssFeeds() throws Exception { mockMvc.perform(get("/rss/ugnich/blog") - .accept(MediaType.TEXT_XML)) + .accept(MediaType.TEXT_XML)) .andExpect(status().isOk()); // fallback mockMvc.perform(get("/rss/ugnich/blog") @@ -2148,7 +2225,7 @@ public class ServerTests { "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(content().contentType("application/rss+xml;charset=UTF-8")); } @Test @@ -2163,10 +2240,12 @@ public class ServerTests { .andExpect(status().isFound()) .andExpect(redirectedUrl("/ugnich/" + mid)); } + @MockBean private MockNotificationListener notificationListener; @Captor protected ArgumentCaptor<SystemEvent> topEventCaptor; + @Test public void topEventShouldNotLossUser() { Message topMessage = MockUtils.mockMessage(1000, ugnich, "top message"); @@ -2177,6 +2256,7 @@ public class ServerTests { SystemEvent receivedEvent = topEventCaptor.getValue(); assertThat(receivedEvent.getActivity().getMessage().getUser(), is(ugnich)); } + @Test public void tagStatsSpec() throws Exception { String newUserName = "tagger"; @@ -2186,7 +2266,7 @@ public class ServerTests { commandsManager.processCommand(newUser, "*test yo", emptyUri); commandsManager.processCommand(newUser, "*test yo2", emptyUri); commandsManager.processCommand(newUser, "*rare yo3", emptyUri); - MvcResult userResponse = mockMvc.perform(get("/api/me").with(httpBasic(newUserName, newUserSecret))) + MvcResult userResponse = mockMvc.perform(get("/api/me").with(httpBasic(newUserName, newUserSecret))) .andExpect(status().isOk()).andReturn(); User userData = jsonMapper.readValue(userResponse.getResponse().getContentAsString(), User.class); List<TagStats> userTags = userData.getTagStats(); @@ -2195,9 +2275,11 @@ public class ServerTests { .findFirst().orElseThrow(IllegalStateException::new); assertThat(rareTagStats.getUsageCount(), is(1)); } + private String getSnapshot(Resource resource) throws IOException { return IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); } + @Test public void emailTemplatesTest() throws IOException { String plainText = emailManager.renderPlaintext("yo", "https://localhost/m/1").orElseThrow(); @@ -2218,6 +2300,7 @@ public class ServerTests { .orElseThrow(); assertThat(htmlPM, is(getSnapshot(testPrivateHtmlEmail))); } + @Test public void readonlyTest() throws Exception { var result = commandsManager.processCommand(ugnich, "YO", emptyUri); @@ -2228,6 +2311,7 @@ public class ServerTests { var authorResult = commandsManager.processCommand(ugnich, String.format("#%d PEOPLE", mid), emptyUri); assertThat(authorResult.getNewMessage().isPresent(), is(true)); } + @Test public void activitySerializationTest() throws JsonProcessingException { var freefd = MockUtils.mockUser(10, "freefd", "secret"); |