From af4181185cd699e76b5f6af7864b081375c59817 Mon Sep 17 00:00:00 2001 From: Rohan Sircar Date: Tue, 11 Aug 2020 17:30:48 +0530 Subject: [PATCH] added formatter plugin --- .gitignore | 1 + pom.xml | 11 + ...itional-spring-configuration-metadata.json | 64 ++-- .../db/migration/V3__add_default_admin.java | 119 ++++--- .../org/ros/chatto/ChattoApplication.java | 8 +- .../chatto/RESTAuthenticationEntryPoint.java | 28 +- .../org/ros/chatto/ServletInitializer.java | 3 +- src/main/java/org/ros/chatto/WebConfig.java | 16 +- .../ros/chatto/captcha/CaptchaBehaviour.java | 3 + .../captcha/ManualCaptchaBehaviour.java | 4 +- .../org/ros/chatto/captcha/SimpleCaptcha.java | 337 +++++++++--------- .../chatto/captcha/SimpleCaptchaBehavior.java | 26 +- .../org/ros/chatto/captcha/WebCaptcha.java | 45 +-- .../java/org/ros/chatto/config/BuildInfo.java | 14 +- .../chatto/config/CustomCacheEventLogger.java | 9 +- .../org/ros/chatto/config/EhCacheConfig.java | 1 - .../controller/ChatMessageController.java | 4 +- .../ros/chatto/controller/CsrfController.java | 14 + .../java/org/ros/chatto/controller/Home.java | 2 +- .../controller/StatisticsController.java | 20 +- .../ros/chatto/controller/UserController.java | 10 +- .../org/ros/chatto/dto/ChatMessageDTO.java | 5 +- .../org/ros/chatto/dto/MessageCipherDTO.java | 4 +- .../ros/chatto/dto/UserRegistrationDTO.java | 8 +- .../java/org/ros/chatto/error/ErrorModel.java | 13 +- .../org/ros/chatto/error/ErrorResponse.java | 4 +- .../org/ros/chatto/logged/TokenCacheUtil.java | 3 +- .../logged/UserLoggingSessionListener.java | 6 +- ...UserSessionLoggingLoginSuccessHandler.java | 28 +- ...serSessionLoggingLogoutSuccessHandler.java | 23 +- .../org/ros/chatto/model/ChatMessage.java | 10 +- .../org/ros/chatto/model/MessageCipher.java | 2 +- src/main/java/org/ros/chatto/model/Role.java | 13 +- .../org/ros/chatto/model/UserSession.java | 6 +- .../repository/DBInitializerRepostory.java | 15 +- .../repository/MessageCipherRepository.java | 3 +- .../ros/chatto/repository/RoleRepository.java | 2 +- .../repository/UserRepositoryCustom.java | 6 +- .../repository/UserRepositoryCustomImpl.java | 28 +- .../AuthenticationSuccessHandlerImpl.java | 35 +- .../ros/chatto/service/CaptchaService.java | 15 +- .../chatto/service/DBInitializerService.java | 6 +- .../ros/chatto/ChattoApplicationTests.java | 121 ++++--- src/test/java/org/ros/chatto/UnitTest.java | 113 +++--- 44 files changed, 640 insertions(+), 568 deletions(-) create mode 100644 src/main/java/org/ros/chatto/controller/CsrfController.java diff --git a/.gitignore b/.gitignore index 8f84f22..8a15cc3 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,7 @@ build/ ### VS Code ### .vscode/ +.cache/ node_modules bundle.js diff --git a/pom.xml b/pom.xml index 1f9c820..e962e3b 100644 --- a/pom.xml +++ b/pom.xml @@ -223,6 +223,17 @@ + + net.revelc.code.formatter + formatter-maven-plugin + 2.12.0 + + ${project.basedir}/eclipse-formatter.xml + 11 + 11 + 11 + + \ No newline at end of file diff --git a/src/main/java/META-INF/additional-spring-configuration-metadata.json b/src/main/java/META-INF/additional-spring-configuration-metadata.json index e8fe397..ec86c25 100644 --- a/src/main/java/META-INF/additional-spring-configuration-metadata.json +++ b/src/main/java/META-INF/additional-spring-configuration-metadata.json @@ -1,34 +1,34 @@ { - "properties": [ - { - "name": "chatto.token.timeout-duration", - "type": "java.lang.String", - "description": "The duration for auth token validity. Token expires after this period of inactivity" - }, - { - "name": "chatto.frontend.log-level", - "type": "java.lang.String", - "description": "The log level for the frontend JS application" - }, - { - "name": "chatto.frontend.chat-page-size", - "type": "java.lang.Integer", - "description": "The pagination size for the chat area" - }, - { - "name": "chat-worker-bundle", - "type": "java.lang.String", - "description": "Name of the chat worker js bundle" - }, - { - "name": "chat-bundle", - "type": "java.lang.String", - "description": "Name of the chatjs bundle" - }, - { - "name": "admin-bundle", - "type": "java.lang.String", - "description": "Name of the admin js bundle" - } - ] + "properties" : [ + { + "name" : "chatto.token.timeout-duration", + "type" : "java.lang.String", + "description" : "The duration for auth token validity. Token expires after this period of inactivity" + }, + { + "name" : "chatto.frontend.log-level", + "type" : "java.lang.String", + "description" : "The log level for the frontend JS application" + }, + { + "name" : "chatto.frontend.chat-page-size", + "type" : "java.lang.Integer", + "description" : "The pagination size for the chat area" + }, + { + "name" : "chat-worker-bundle", + "type" : "java.lang.String", + "description" : "Name of the chat worker js bundle" + }, + { + "name" : "chat-bundle", + "type" : "java.lang.String", + "description" : "Name of the chatjs bundle" + }, + { + "name" : "admin-bundle", + "type" : "java.lang.String", + "description" : "Name of the admin js bundle" + } + ] } \ No newline at end of file diff --git a/src/main/java/db/migration/V3__add_default_admin.java b/src/main/java/db/migration/V3__add_default_admin.java index d54ac9d..fcb1321 100644 --- a/src/main/java/db/migration/V3__add_default_admin.java +++ b/src/main/java/db/migration/V3__add_default_admin.java @@ -15,72 +15,75 @@ import org.springframework.security.crypto.password.PasswordEncoder; public class V3__add_default_admin extends BaseJavaMigration { - private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); - private final SecureRandom random = new SecureRandom(); + private final SecureRandom random = new SecureRandom(); - /** different dictionaries used */ - private final String ALPHA_CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - private final String ALPHA = "abcdefghijklmnopqrstuvwxyz"; - private final String NUMERIC = "0123456789"; - private final String SPECIAL_CHARS = "!@#$%^&*_=+-/"; + /** different dictionaries used */ + private final String ALPHA_CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private final String ALPHA = "abcdefghijklmnopqrstuvwxyz"; + private final String NUMERIC = "0123456789"; + private final String SPECIAL_CHARS = "!@#$%^&*_=+-/"; - /** - * Method will generate random string based on the parameters - * - * @param len the length of the random string - * @param dic the dictionary used to generate the password - * @return the random password - */ - public String generatePassword(int len, String dic) { - String result = ""; - for (int i = 0; i < len; i++) { - int index = random.nextInt(dic.length()); - result += dic.charAt(index); - } - return result; - } + /** + * Method will generate random string based on the parameters + * + * @param len + * the length of the random string + * @param dic + * the dictionary used to generate the password + * @return the random password + */ + public String generatePassword(int len, String dic) { + String result = ""; + for (int i = 0; i < len; i++) { + int index = random.nextInt(dic.length()); + result += dic.charAt(index); + } + return result; + } - @Override - public void migrate(final Context context) throws Exception { - try (final PreparedStatement ps = context.getConnection() - .prepareStatement("insert into users (user_id, name, password) values (0,?,?)")) { - final String generatedPassword = generatePassword(60, ALPHA_CAPS + ALPHA + SPECIAL_CHARS); - final BufferedWriter bw = new BufferedWriter( - new FileWriter("gen-password.txt")); - - bw.write(generatedPassword); - bw.write("\nPlease delete this file"); - bw.close(); + @Override + public void migrate(final Context context) throws Exception { + try (final PreparedStatement ps = context.getConnection() + .prepareStatement( + "insert into users (user_id, name, password) values (0,?,?)")) { + final String generatedPassword = generatePassword(60, + ALPHA_CAPS + ALPHA + SPECIAL_CHARS); + final BufferedWriter bw = new BufferedWriter( + new FileWriter("gen-password.txt")); - final var perms = Files.getPosixFilePermissions(Paths.get( - "gen-password.txt")); + bw.write(generatedPassword); + bw.write("\nPlease delete this file"); + bw.close(); + final var perms = Files + .getPosixFilePermissions(Paths.get("gen-password.txt")); - //add owners permission - perms.add(PosixFilePermission.OWNER_READ); - perms.add(PosixFilePermission.OWNER_WRITE); - perms.remove(PosixFilePermission.OWNER_EXECUTE); - //add group permissions - perms.remove(PosixFilePermission.GROUP_READ); - perms.remove(PosixFilePermission.GROUP_WRITE); - perms.remove(PosixFilePermission.GROUP_EXECUTE); - //add others permissions - perms.remove(PosixFilePermission.OTHERS_READ); - perms.remove(PosixFilePermission.OTHERS_WRITE); - perms.remove(PosixFilePermission.OTHERS_EXECUTE); - Files.setPosixFilePermissions(Paths.get("gen-password.txt"), perms); + // add owners permission + perms.add(PosixFilePermission.OWNER_READ); + perms.add(PosixFilePermission.OWNER_WRITE); + perms.remove(PosixFilePermission.OWNER_EXECUTE); + // add group permissions + perms.remove(PosixFilePermission.GROUP_READ); + perms.remove(PosixFilePermission.GROUP_WRITE); + perms.remove(PosixFilePermission.GROUP_EXECUTE); + // add others permissions + perms.remove(PosixFilePermission.OTHERS_READ); + perms.remove(PosixFilePermission.OTHERS_WRITE); + perms.remove(PosixFilePermission.OTHERS_EXECUTE); + Files.setPosixFilePermissions(Paths.get("gen-password.txt"), perms); + ps.setString(1, "admin"); + ps.setString(2, passwordEncoder.encode(generatedPassword)); + ps.execute(); + } - ps.setString(1, "admin"); - ps.setString(2, passwordEncoder.encode(generatedPassword)); - ps.execute(); - } - - try (final PreparedStatement ps = context.getConnection() - .prepareStatement("insert into users_roles (user_id, role_id) values (1,0)")) { - ps.execute(); - } - } + try (final PreparedStatement ps = context.getConnection() + .prepareStatement( + "insert into users_roles (user_id, role_id) values (1,0)")) { + ps.execute(); + } + } } \ No newline at end of file diff --git a/src/main/java/org/ros/chatto/ChattoApplication.java b/src/main/java/org/ros/chatto/ChattoApplication.java index 5a42691..bbce3b4 100644 --- a/src/main/java/org/ros/chatto/ChattoApplication.java +++ b/src/main/java/org/ros/chatto/ChattoApplication.java @@ -17,8 +17,8 @@ public class ChattoApplication extends SpringBootServletInitializer { } @Configuration - @Profile("development") - @ComponentScan(lazyInit = true) - static class LocalConfig { - } + @Profile("development") + @ComponentScan(lazyInit = true) + static class LocalConfig { + } } \ No newline at end of file diff --git a/src/main/java/org/ros/chatto/RESTAuthenticationEntryPoint.java b/src/main/java/org/ros/chatto/RESTAuthenticationEntryPoint.java index 6267be3..de0908c 100644 --- a/src/main/java/org/ros/chatto/RESTAuthenticationEntryPoint.java +++ b/src/main/java/org/ros/chatto/RESTAuthenticationEntryPoint.java @@ -12,19 +12,21 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationEn import org.springframework.stereotype.Component; @Component -public final class RESTAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { +public final class RESTAuthenticationEntryPoint + extends BasicAuthenticationEntryPoint { - @Override - public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) - throws IOException, ServletException { - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - PrintWriter writer = response.getWriter(); - writer.println("HTTP ApplicationStatus 401 - " + authEx.getMessage()); - } + @Override + public void commence(HttpServletRequest request, + HttpServletResponse response, AuthenticationException authEx) + throws IOException, ServletException { + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + PrintWriter writer = response.getWriter(); + writer.println("HTTP ApplicationStatus 401 - " + authEx.getMessage()); + } - @Override - public void afterPropertiesSet() throws Exception { - setRealmName("Chatto"); - super.afterPropertiesSet(); - } + @Override + public void afterPropertiesSet() throws Exception { + setRealmName("Chatto"); + super.afterPropertiesSet(); + } } diff --git a/src/main/java/org/ros/chatto/ServletInitializer.java b/src/main/java/org/ros/chatto/ServletInitializer.java index 2f24f20..6837be5 100644 --- a/src/main/java/org/ros/chatto/ServletInitializer.java +++ b/src/main/java/org/ros/chatto/ServletInitializer.java @@ -6,7 +6,8 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer public class ServletInitializer extends SpringBootServletInitializer { @Override - protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + protected SpringApplicationBuilder configure( + SpringApplicationBuilder application) { return application.sources(ChattoApplication.class); } diff --git a/src/main/java/org/ros/chatto/WebConfig.java b/src/main/java/org/ros/chatto/WebConfig.java index f2c7136..36b82ec 100644 --- a/src/main/java/org/ros/chatto/WebConfig.java +++ b/src/main/java/org/ros/chatto/WebConfig.java @@ -5,16 +5,14 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration -//@EnableWebMvc +// @EnableWebMvc public class WebConfig implements WebMvcConfigurer { - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/api/**") - .allowedOrigins("*") - .allowedMethods("POST","GET","OPTIONS") - .allowedHeaders("*") - .allowCredentials(false).maxAge(3600); + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/api/**").allowedOrigins("*") + .allowedMethods("POST", "GET", "OPTIONS").allowedHeaders("*") + .allowCredentials(false).maxAge(3600); - } + } } \ No newline at end of file diff --git a/src/main/java/org/ros/chatto/captcha/CaptchaBehaviour.java b/src/main/java/org/ros/chatto/captcha/CaptchaBehaviour.java index ead3ba2..eda0be1 100644 --- a/src/main/java/org/ros/chatto/captcha/CaptchaBehaviour.java +++ b/src/main/java/org/ros/chatto/captcha/CaptchaBehaviour.java @@ -4,7 +4,10 @@ import java.awt.image.BufferedImage; interface CaptchaBehaviour { public BufferedImage generateCaptcha(); + public BufferedImage generateCaptcha(String captchaText); + public String getRandomChars(int size); + public String getRandomChars(); } diff --git a/src/main/java/org/ros/chatto/captcha/ManualCaptchaBehaviour.java b/src/main/java/org/ros/chatto/captcha/ManualCaptchaBehaviour.java index a33ff07..7d2e20e 100644 --- a/src/main/java/org/ros/chatto/captcha/ManualCaptchaBehaviour.java +++ b/src/main/java/org/ros/chatto/captcha/ManualCaptchaBehaviour.java @@ -6,9 +6,10 @@ import lombok.Builder; /*Class for providing your own captcha generator*/ @Builder -public class ManualCaptchaBehaviour implements CaptchaBehaviour{ +public class ManualCaptchaBehaviour implements CaptchaBehaviour { private final int length; private final String style; + @Override public BufferedImage generateCaptcha() { // TODO Auto-generated method stub @@ -33,5 +34,4 @@ public class ManualCaptchaBehaviour implements CaptchaBehaviour{ return null; } - } diff --git a/src/main/java/org/ros/chatto/captcha/SimpleCaptcha.java b/src/main/java/org/ros/chatto/captcha/SimpleCaptcha.java index 7849576..c33b608 100644 --- a/src/main/java/org/ros/chatto/captcha/SimpleCaptcha.java +++ b/src/main/java/org/ros/chatto/captcha/SimpleCaptcha.java @@ -10,174 +10,183 @@ import java.io.IOException; import java.util.Random; /** - * This class represents a simple captcha consisting - * of an image {@code png} and its text value. - * Comic Neue Bold Font. - * Capital english letters {@code ONLY}. + * This class represents a simple captcha consisting of an image {@code png} and + * its text value. Comic Neue Bold Font. Capital english letters {@code ONLY}. * * @since 1.3 * @author Gennadiy Golovin */ public final class SimpleCaptcha { - private BufferedImage imagePng; - private char[] text; - - /** - * Initializes a newly created default object - * consisting of 8 capital english letters. - */ - public SimpleCaptcha() { - this.text = getRandomChars(); - - try { - generateCaptcha(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Initializes a newly created object, which length - * depends on the passed {@code int} parameter, - * which {@code MUST} be greater than 0. - * If the condition is not met, initializes a newly - * created default object consisting of 8 symbols. - * - * @param length the quantity of symbols, that the - * captcha consists of, greater than 0. - */ - public SimpleCaptcha(int length) { - if (length < 1) { - this.text = getRandomChars(); - } else { - this.text = getRandomChars(length); - } - - try { - generateCaptcha(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * Initializes a newly created object based on the passed - * {@link String} parameter, consisting of capital english - * letters. If the condition is not met, initializes a newly - * created default object consisting of 8 capital english letters. - * - * @param text the text string with the value of the captcha, - * length greater than 0. - */ - public SimpleCaptcha(String text) { - if (text == null || text.equals("")) { - this.text = getRandomChars(); - } else { - this.text = text.toCharArray(); - } - - try { - generateCaptcha(); - } catch (IOException e) { - this.text = getRandomChars(); - try { - generateCaptcha(); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - } - - /** - * Returns the picture with captcha - * - * @return {@link BufferedImage} - */ - public BufferedImage getImagePng() { - return imagePng; - } - - /** - * Returns the text value of the captcha - * - * @return {@link String} - */ - public String getText() { - return String.valueOf(text); - } - - //////// //////// //////// //////// //////// //////// //////// //////// - - private char[] getRandomChars() { - return getRandomChars(8); - } - - private char[] getRandomChars(int quantity) { - - char[] randomString = new char[quantity]; - - Random random = new Random(); - - int capitalLetter; - - for (int i = 0; i < quantity; i++) { - capitalLetter = 65 + random.nextInt(26); - randomString[i] = (char) capitalLetter; - } - - return randomString; - } - - private void generateCaptcha() throws IOException { - int charsQuantity = this.text.length; - BufferedImage[] images = new BufferedImage[charsQuantity]; - - for (int i = 0; i < charsQuantity; i++) { - images[i] = ImageIO.read(SimpleCaptcha.class.getResourceAsStream("/pictures/" + this.text[i] + ".png")); - if (i % 2 == 0) { - images[i] = rotateImage(images[i], 25); - } else { - images[i] = rotateImage(images[i], -20); - } - } - - int imageSize = 30; - int rotatedImageSize = (int) Math.sqrt(imageSize * imageSize * 2); - - BufferedImage captchaImg = new BufferedImage(rotatedImageSize * (charsQuantity - 1) / 10 * 6 + rotatedImageSize, rotatedImageSize, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics2d = captchaImg.createGraphics(); - graphics2d.setBackground(Color.WHITE); - graphics2d.clearRect(0, 0, captchaImg.getWidth(), captchaImg.getHeight()); - for (int i = 0; i < charsQuantity; i++) { - captchaImg.getGraphics().drawImage(images[i], rotatedImageSize * i / 10 * 6, 0, null); - } - graphics2d.dispose(); - this.imagePng = captchaImg; - } - - private BufferedImage rotateImage(BufferedImage buffImage, double angle) { - - double radian = Math.toRadians(angle); - double sin = Math.abs(Math.sin(radian)); - double cos = Math.abs(Math.cos(radian)); - - int width = buffImage.getWidth(); - int height = buffImage.getHeight(); - - int nWidth = (int) Math.floor((double) width * cos + (double) height * sin); - int nHeight = (int) Math.floor((double) height * cos + (double) width * sin); - - BufferedImage rotatedImage = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_INT_ARGB); - - Graphics2D graphics = rotatedImage.createGraphics(); - - graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); - graphics.translate((nWidth - width) / 2, (nHeight - height) / 2); - graphics.rotate(radian, (double) (width / 2), (double) (height / 2)); - graphics.drawImage(buffImage, 0, 0,null); - graphics.dispose(); - - return rotatedImage; - } + private BufferedImage imagePng; + private char[] text; + + /** + * Initializes a newly created default object consisting of 8 capital + * english letters. + */ + public SimpleCaptcha() { + this.text = getRandomChars(); + + try { + generateCaptcha(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Initializes a newly created object, which length depends on the passed + * {@code int} parameter, which {@code MUST} be greater than 0. If the + * condition is not met, initializes a newly created default object + * consisting of 8 symbols. + * + * @param length + * the quantity of symbols, that the captcha consists of, greater + * than 0. + */ + public SimpleCaptcha(int length) { + if (length < 1) { + this.text = getRandomChars(); + } else { + this.text = getRandomChars(length); + } + + try { + generateCaptcha(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Initializes a newly created object based on the passed {@link String} + * parameter, consisting of capital english letters. If the condition is not + * met, initializes a newly created default object consisting of 8 capital + * english letters. + * + * @param text + * the text string with the value of the captcha, length greater + * than 0. + */ + public SimpleCaptcha(String text) { + if (text == null || text.equals("")) { + this.text = getRandomChars(); + } else { + this.text = text.toCharArray(); + } + + try { + generateCaptcha(); + } catch (IOException e) { + this.text = getRandomChars(); + try { + generateCaptcha(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + + /** + * Returns the picture with captcha + * + * @return {@link BufferedImage} + */ + public BufferedImage getImagePng() { + return imagePng; + } + + /** + * Returns the text value of the captcha + * + * @return {@link String} + */ + public String getText() { + return String.valueOf(text); + } + + //////// //////// //////// //////// //////// //////// //////// //////// + + private char[] getRandomChars() { + return getRandomChars(8); + } + + private char[] getRandomChars(int quantity) { + + char[] randomString = new char[quantity]; + + Random random = new Random(); + + int capitalLetter; + + for (int i = 0; i < quantity; i++) { + capitalLetter = 65 + random.nextInt(26); + randomString[i] = (char) capitalLetter; + } + + return randomString; + } + + private void generateCaptcha() throws IOException { + int charsQuantity = this.text.length; + BufferedImage[] images = new BufferedImage[charsQuantity]; + + for (int i = 0; i < charsQuantity; i++) { + images[i] = ImageIO.read(SimpleCaptcha.class + .getResourceAsStream("/pictures/" + this.text[i] + ".png")); + if (i % 2 == 0) { + images[i] = rotateImage(images[i], 25); + } else { + images[i] = rotateImage(images[i], -20); + } + } + + int imageSize = 30; + int rotatedImageSize = (int) Math.sqrt(imageSize * imageSize * 2); + + BufferedImage captchaImg = new BufferedImage( + rotatedImageSize * (charsQuantity - 1) / 10 * 6 + + rotatedImageSize, + rotatedImageSize, BufferedImage.TYPE_INT_ARGB); + Graphics2D graphics2d = captchaImg.createGraphics(); + graphics2d.setBackground(Color.WHITE); + graphics2d.clearRect(0, 0, captchaImg.getWidth(), + captchaImg.getHeight()); + for (int i = 0; i < charsQuantity; i++) { + captchaImg.getGraphics().drawImage(images[i], + rotatedImageSize * i / 10 * 6, 0, null); + } + graphics2d.dispose(); + this.imagePng = captchaImg; + } + + private BufferedImage rotateImage(BufferedImage buffImage, double angle) { + + double radian = Math.toRadians(angle); + double sin = Math.abs(Math.sin(radian)); + double cos = Math.abs(Math.cos(radian)); + + int width = buffImage.getWidth(); + int height = buffImage.getHeight(); + + int nWidth = (int) Math + .floor((double) width * cos + (double) height * sin); + int nHeight = (int) Math + .floor((double) height * cos + (double) width * sin); + + BufferedImage rotatedImage = new BufferedImage(nWidth, nHeight, + BufferedImage.TYPE_INT_ARGB); + + Graphics2D graphics = rotatedImage.createGraphics(); + + graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, + RenderingHints.VALUE_INTERPOLATION_BICUBIC); + graphics.translate((nWidth - width) / 2, (nHeight - height) / 2); + graphics.rotate(radian, (double) (width / 2), (double) (height / 2)); + graphics.drawImage(buffImage, 0, 0, null); + graphics.dispose(); + + return rotatedImage; + } } \ No newline at end of file diff --git a/src/main/java/org/ros/chatto/captcha/SimpleCaptchaBehavior.java b/src/main/java/org/ros/chatto/captcha/SimpleCaptchaBehavior.java index d9d7eb3..2969816 100644 --- a/src/main/java/org/ros/chatto/captcha/SimpleCaptchaBehavior.java +++ b/src/main/java/org/ros/chatto/captcha/SimpleCaptchaBehavior.java @@ -9,30 +9,30 @@ public class SimpleCaptchaBehavior implements CaptchaBehaviour { SimpleCaptcha simpleCaptcha = new SimpleCaptcha(); return simpleCaptcha.getImagePng(); } + @Override public BufferedImage generateCaptcha(String captchaText) { SimpleCaptcha simpleCaptcha = new SimpleCaptcha(captchaText); return simpleCaptcha.getImagePng(); } - + public String getRandomChars() { - return getRandomChars(8); - } - - public String getRandomChars(int quantity) - { + return getRandomChars(8); + } + + public String getRandomChars(int quantity) { char[] randomString = new char[quantity]; - Random random = new Random(); + Random random = new Random(); - int capitalLetter; + int capitalLetter; - for (int i = 0; i < quantity; i++) { - capitalLetter = 65 + random.nextInt(26); - randomString[i] = (char) capitalLetter; - } + for (int i = 0; i < quantity; i++) { + capitalLetter = 65 + random.nextInt(26); + randomString[i] = (char) capitalLetter; + } - return new String(randomString); + return new String(randomString); } } diff --git a/src/main/java/org/ros/chatto/captcha/WebCaptcha.java b/src/main/java/org/ros/chatto/captcha/WebCaptcha.java index e6d6de6..5aa084a 100644 --- a/src/main/java/org/ros/chatto/captcha/WebCaptcha.java +++ b/src/main/java/org/ros/chatto/captcha/WebCaptcha.java @@ -7,34 +7,35 @@ import lombok.Builder; @Builder public class WebCaptcha { private final CaptchaBehaviour captchaBehaviour; - + public BufferedImage generateCaptcha() { return captchaBehaviour.generateCaptcha(); - } - + } + public BufferedImage generateCaptcha(String captchaText) { return captchaBehaviour.generateCaptcha(captchaText); - } - + } + public String getRandomChars() { - return captchaBehaviour.getRandomChars(); - } + return captchaBehaviour.getRandomChars(); + } - public String getRandomChars(int quantity) { - return captchaBehaviour.getRandomChars(quantity); - } + public String getRandomChars(int quantity) { + return captchaBehaviour.getRandomChars(quantity); + } } -// WebCaptcha webCaptcha = WebCaptcha.builder().captchaBehaviour(new SimpleCaptchaBehavior()).build(); -// webCaptcha.generateCaptcha(); +// WebCaptcha webCaptcha = WebCaptcha.builder().captchaBehaviour(new +// SimpleCaptchaBehavior()).build(); +// webCaptcha.generateCaptcha(); +// +// // @formatter:off +// webCaptcha = WebCaptcha.builder() +// .captchaBehaviour( +// ManualCaptchaBehaviour.builder() +// .length(8) +// .style("black") +// .build() +// ).build(); // -// // @formatter:off -// webCaptcha = WebCaptcha.builder() -// .captchaBehaviour( -// ManualCaptchaBehaviour.builder() -// .length(8) -// .style("black") -// .build() -// ).build(); -// -// // @formatter:on +// // @formatter:on diff --git a/src/main/java/org/ros/chatto/config/BuildInfo.java b/src/main/java/org/ros/chatto/config/BuildInfo.java index 1adc015..54c8861 100644 --- a/src/main/java/org/ros/chatto/config/BuildInfo.java +++ b/src/main/java/org/ros/chatto/config/BuildInfo.java @@ -10,13 +10,13 @@ import lombok.Getter; @PropertySource(value = "classpath:git.properties") @Getter public class BuildInfo { - private final String buildVersion; - private final String branchName; + private final String buildVersion; + private final String branchName; - public BuildInfo(@Value("${git.build.version") String buildVersion, - @Value("${git.branch") String branchName) { - this.buildVersion = buildVersion; - this.branchName = branchName; - } + public BuildInfo(@Value("${git.build.version") String buildVersion, + @Value("${git.branch") String branchName) { + this.buildVersion = buildVersion; + this.branchName = branchName; + } } \ No newline at end of file diff --git a/src/main/java/org/ros/chatto/config/CustomCacheEventLogger.java b/src/main/java/org/ros/chatto/config/CustomCacheEventLogger.java index 2062c7d..b96d7d0 100644 --- a/src/main/java/org/ros/chatto/config/CustomCacheEventLogger.java +++ b/src/main/java/org/ros/chatto/config/CustomCacheEventLogger.java @@ -6,11 +6,14 @@ import org.ehcache.event.CacheEventListener; import lombok.extern.slf4j.Slf4j; @Slf4j -public class CustomCacheEventLogger implements CacheEventListener { +public class CustomCacheEventLogger + implements CacheEventListener { @Override - public void onEvent(CacheEvent cacheEvent) { - log.debug("custom Caching event {} key = {} old {} new {} ", cacheEvent.getType(), cacheEvent.getKey(), + public void onEvent( + CacheEvent cacheEvent) { + log.debug("custom Caching event {} key = {} old {} new {} ", + cacheEvent.getType(), cacheEvent.getKey(), cacheEvent.getOldValue(), cacheEvent.getNewValue()); } } diff --git a/src/main/java/org/ros/chatto/config/EhCacheConfig.java b/src/main/java/org/ros/chatto/config/EhCacheConfig.java index 6e53976..d34542b 100644 --- a/src/main/java/org/ros/chatto/config/EhCacheConfig.java +++ b/src/main/java/org/ros/chatto/config/EhCacheConfig.java @@ -1,6 +1,5 @@ package org.ros.chatto.config; - import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/org/ros/chatto/controller/ChatMessageController.java b/src/main/java/org/ros/chatto/controller/ChatMessageController.java index 1f683ae..f08c6c7 100644 --- a/src/main/java/org/ros/chatto/controller/ChatMessageController.java +++ b/src/main/java/org/ros/chatto/controller/ChatMessageController.java @@ -89,8 +89,8 @@ public class ChatMessageController { @PathVariable final String userName, @PathVariable final Instant lastMessageTime, final Principal principal) { - final List chatMessageDTOs = chatService.getNewMessages( - principal.getName(), userName, lastMessageTime); + final List chatMessageDTOs = chatService + .getNewMessages(principal.getName(), userName, lastMessageTime); return chatMessageDTOs; } diff --git a/src/main/java/org/ros/chatto/controller/CsrfController.java b/src/main/java/org/ros/chatto/controller/CsrfController.java new file mode 100644 index 0000000..0917bf1 --- /dev/null +++ b/src/main/java/org/ros/chatto/controller/CsrfController.java @@ -0,0 +1,14 @@ +package org.ros.chatto.controller; + +import org.springframework.security.web.csrf.CsrfToken; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CsrfController { + + @RequestMapping("/csrf") + public CsrfToken csrf(CsrfToken token) { + return token; + } +} \ No newline at end of file diff --git a/src/main/java/org/ros/chatto/controller/Home.java b/src/main/java/org/ros/chatto/controller/Home.java index fe482d8..3d1ffdf 100644 --- a/src/main/java/org/ros/chatto/controller/Home.java +++ b/src/main/java/org/ros/chatto/controller/Home.java @@ -45,7 +45,7 @@ public class Home { || r.getAuthority().equals("ROLE_SUPER_USER")); log.trace("Is admin? " + isAdmin); // model.addAttribute("activeUsers", - // userService.getOtherActiveUsers(principal.getName())); + // userService.getOtherActiveUsers(principal.getName())); return "chat"; } } diff --git a/src/main/java/org/ros/chatto/controller/StatisticsController.java b/src/main/java/org/ros/chatto/controller/StatisticsController.java index abf5176..27df50b 100644 --- a/src/main/java/org/ros/chatto/controller/StatisticsController.java +++ b/src/main/java/org/ros/chatto/controller/StatisticsController.java @@ -14,16 +14,16 @@ import lombok.RequiredArgsConstructor; @RequestMapping("/api/stats") @RequiredArgsConstructor public class StatisticsController { - private final StatisticsService statisticsService; + private final StatisticsService statisticsService; - @GetMapping - public StatsDTO rootStats() { - return StatsDTO.builder() - .totalMessages(statisticsService.totalMessage()) - .totalOnlineUsers(statisticsService.totalUsersOnline()) - .numMessagesToday( - statisticsService.messagesOnDay(Instant.now())) - .totalUsers(statisticsService.totalUsers()).build(); - } + @GetMapping + public StatsDTO rootStats() { + return StatsDTO.builder() + .totalMessages(statisticsService.totalMessage()) + .totalOnlineUsers(statisticsService.totalUsersOnline()) + .numMessagesToday( + statisticsService.messagesOnDay(Instant.now())) + .totalUsers(statisticsService.totalUsers()).build(); + } } \ No newline at end of file diff --git a/src/main/java/org/ros/chatto/controller/UserController.java b/src/main/java/org/ros/chatto/controller/UserController.java index bbd2cd8..529592b 100644 --- a/src/main/java/org/ros/chatto/controller/UserController.java +++ b/src/main/java/org/ros/chatto/controller/UserController.java @@ -6,9 +6,9 @@ import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/user") public class UserController { - - @RequestMapping - public String viewUserProfile() { - return "user/home"; - } + + @RequestMapping + public String viewUserProfile() { + return "user/home"; + } } \ No newline at end of file diff --git a/src/main/java/org/ros/chatto/dto/ChatMessageDTO.java b/src/main/java/org/ros/chatto/dto/ChatMessageDTO.java index 56700ee..ae5aa08 100644 --- a/src/main/java/org/ros/chatto/dto/ChatMessageDTO.java +++ b/src/main/java/org/ros/chatto/dto/ChatMessageDTO.java @@ -1,6 +1,5 @@ package org.ros.chatto.dto; - import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; @@ -12,10 +11,10 @@ import lombok.Data; public class ChatMessageDTO { @NotBlank(message = "Username should not be blank") @Pattern(regexp = "^[A-Za-z0-9]+$", message = "Username must be alphanumeric") - @Size(max=15) + @Size(max = 15) private String toUser; @Pattern(regexp = "^[A-Za-z0-9]+$", message = "Username must be alphanumeric") - @Size(max=15) + @Size(max = 15) private String fromUser; private MessageCipherDTO messageCipher; private Instant messageTime; diff --git a/src/main/java/org/ros/chatto/dto/MessageCipherDTO.java b/src/main/java/org/ros/chatto/dto/MessageCipherDTO.java index 602338d..2f57def 100644 --- a/src/main/java/org/ros/chatto/dto/MessageCipherDTO.java +++ b/src/main/java/org/ros/chatto/dto/MessageCipherDTO.java @@ -12,7 +12,9 @@ import lombok.Data; @Data public class MessageCipherDTO { - @Pattern(regexp = "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") // regex for base64 + @Pattern(regexp = "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") // regex + // for + // base64 @NotBlank private String iv; @Max(1) diff --git a/src/main/java/org/ros/chatto/dto/UserRegistrationDTO.java b/src/main/java/org/ros/chatto/dto/UserRegistrationDTO.java index b47a339..e557033 100644 --- a/src/main/java/org/ros/chatto/dto/UserRegistrationDTO.java +++ b/src/main/java/org/ros/chatto/dto/UserRegistrationDTO.java @@ -16,11 +16,13 @@ public class UserRegistrationDTO { @Transient @Size(min = 4, max = 75, message = "Password must be between 4 and 75 characters") @NotBlank(message = "Password should not be blank") -// @Pattern(regexp = "^.*(?=.{6,})(?=.*d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$", message = "Invalid password format") + // @Pattern(regexp = + // "^.*(?=.{6,})(?=.*d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$", message + // = "Invalid password format") private String password; - + private Long captchaID; private String captchaText; - + private String captchaInput; } diff --git a/src/main/java/org/ros/chatto/error/ErrorModel.java b/src/main/java/org/ros/chatto/error/ErrorModel.java index 8e497c3..587e312 100644 --- a/src/main/java/org/ros/chatto/error/ErrorModel.java +++ b/src/main/java/org/ros/chatto/error/ErrorModel.java @@ -7,15 +7,14 @@ import lombok.Data; import lombok.NoArgsConstructor; @Data -@NoArgsConstructor +@NoArgsConstructor @AllArgsConstructor -public class ErrorModel{ +public class ErrorModel { @JsonProperty("field_name") - private String fieldName; + private String fieldName; @JsonProperty("rejected_value") - private Object rejectedValue; + private Object rejectedValue; @JsonProperty("error_message") - private String messageError; - - + private String messageError; + } \ No newline at end of file diff --git a/src/main/java/org/ros/chatto/error/ErrorResponse.java b/src/main/java/org/ros/chatto/error/ErrorResponse.java index bec8e49..6016816 100644 --- a/src/main/java/org/ros/chatto/error/ErrorResponse.java +++ b/src/main/java/org/ros/chatto/error/ErrorResponse.java @@ -15,6 +15,6 @@ import lombok.NoArgsConstructor; @AllArgsConstructor public class ErrorResponse { @JsonProperty("errors") - private List errorMessage; - + private List errorMessage; + } \ No newline at end of file diff --git a/src/main/java/org/ros/chatto/logged/TokenCacheUtil.java b/src/main/java/org/ros/chatto/logged/TokenCacheUtil.java index 2748749..b6eba73 100644 --- a/src/main/java/org/ros/chatto/logged/TokenCacheUtil.java +++ b/src/main/java/org/ros/chatto/logged/TokenCacheUtil.java @@ -4,5 +4,6 @@ import org.springframework.cache.annotation.CacheEvict; public class TokenCacheUtil { @CacheEvict(value = "userTokenCache", key = "#cacheKey") - public static void evictSingleTokenValue(String cacheKey) {} + public static void evictSingleTokenValue(String cacheKey) { + } } diff --git a/src/main/java/org/ros/chatto/logged/UserLoggingSessionListener.java b/src/main/java/org/ros/chatto/logged/UserLoggingSessionListener.java index a40aaba..0c800ae 100644 --- a/src/main/java/org/ros/chatto/logged/UserLoggingSessionListener.java +++ b/src/main/java/org/ros/chatto/logged/UserLoggingSessionListener.java @@ -26,7 +26,8 @@ public class UserLoggingSessionListener implements HttpSessionBindingListener { @Override public void valueBound(HttpSessionBindingEvent event) { - UserLoggingSessionListener user = (UserLoggingSessionListener) event.getValue(); + UserLoggingSessionListener user = (UserLoggingSessionListener) event + .getValue(); log.debug("Incrementing session count for user {}", user.getUsername()); @@ -38,7 +39,8 @@ public class UserLoggingSessionListener implements HttpSessionBindingListener { @Override public void valueUnbound(HttpSessionBindingEvent event) { - UserLoggingSessionListener user = (UserLoggingSessionListener) event.getValue(); + UserLoggingSessionListener user = (UserLoggingSessionListener) event + .getValue(); log.debug("Decrementing session count for user {}", user.getUsername()); diff --git a/src/main/java/org/ros/chatto/logged/UserSessionLoggingLoginSuccessHandler.java b/src/main/java/org/ros/chatto/logged/UserSessionLoggingLoginSuccessHandler.java index 33f8c27..169d79d 100644 --- a/src/main/java/org/ros/chatto/logged/UserSessionLoggingLoginSuccessHandler.java +++ b/src/main/java/org/ros/chatto/logged/UserSessionLoggingLoginSuccessHandler.java @@ -11,17 +11,19 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand import org.springframework.stereotype.Component; @Component("myAuthenticationSuccessHandler") -public class UserSessionLoggingLoginSuccessHandler implements AuthenticationSuccessHandler { - - @Override - public void onAuthenticationSuccess(HttpServletRequest request, - HttpServletResponse response, Authentication authentication) - throws IOException { - HttpSession session = request.getSession(false); - if (session != null) { - UserLoggingSessionListener user = new UserLoggingSessionListener(authentication.getName()); - session.setAttribute("user", user); - } - response.sendRedirect("/chat"); - } +public class UserSessionLoggingLoginSuccessHandler + implements AuthenticationSuccessHandler { + + @Override + public void onAuthenticationSuccess(HttpServletRequest request, + HttpServletResponse response, Authentication authentication) + throws IOException { + HttpSession session = request.getSession(false); + if (session != null) { + UserLoggingSessionListener user = new UserLoggingSessionListener( + authentication.getName()); + session.setAttribute("user", user); + } + response.sendRedirect("/chat"); + } } \ No newline at end of file diff --git a/src/main/java/org/ros/chatto/logged/UserSessionLoggingLogoutSuccessHandler.java b/src/main/java/org/ros/chatto/logged/UserSessionLoggingLogoutSuccessHandler.java index 1ddd9f9..7db3286 100644 --- a/src/main/java/org/ros/chatto/logged/UserSessionLoggingLogoutSuccessHandler.java +++ b/src/main/java/org/ros/chatto/logged/UserSessionLoggingLogoutSuccessHandler.java @@ -12,15 +12,16 @@ import org.springframework.security.web.authentication.logout.LogoutSuccessHandl import org.springframework.stereotype.Component; @Component("myLogoutSuccessHandler") -public class UserSessionLoggingLogoutSuccessHandler implements LogoutSuccessHandler{ - @Override - public void onLogoutSuccess(HttpServletRequest request, - HttpServletResponse response, Authentication authentication) - throws IOException, ServletException { - HttpSession session = request.getSession(); - if (session != null){ - session.removeAttribute("user"); - } - response.sendRedirect("/login?logout"); - } +public class UserSessionLoggingLogoutSuccessHandler + implements LogoutSuccessHandler { + @Override + public void onLogoutSuccess(HttpServletRequest request, + HttpServletResponse response, Authentication authentication) + throws IOException, ServletException { + HttpSession session = request.getSession(); + if (session != null) { + session.removeAttribute("user"); + } + response.sendRedirect("/login?logout"); + } } \ No newline at end of file diff --git a/src/main/java/org/ros/chatto/model/ChatMessage.java b/src/main/java/org/ros/chatto/model/ChatMessage.java index c4849db..6748300 100644 --- a/src/main/java/org/ros/chatto/model/ChatMessage.java +++ b/src/main/java/org/ros/chatto/model/ChatMessage.java @@ -24,18 +24,18 @@ public class ChatMessage { @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "m_id") private Long messageID; - + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "from_user") private ChatUser fromUser; - + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "to_user") private ChatUser toUser; - + @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "message") private MessageCipher messageCipher; - - private Instant messageTime; + + private Instant messageTime; } diff --git a/src/main/java/org/ros/chatto/model/MessageCipher.java b/src/main/java/org/ros/chatto/model/MessageCipher.java index be9a8c8..17e4ec5 100644 --- a/src/main/java/org/ros/chatto/model/MessageCipher.java +++ b/src/main/java/org/ros/chatto/model/MessageCipher.java @@ -19,7 +19,7 @@ this is what the json will look like*/ @Entity @Table(name = "message_ciphers") @EntityListeners(AuditingEntityListener.class) -//@JsonIgnoreProperties(value = { "id"}, allowGetters = false) +// @JsonIgnoreProperties(value = { "id"}, allowGetters = false) public class MessageCipher { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/src/main/java/org/ros/chatto/model/Role.java b/src/main/java/org/ros/chatto/model/Role.java index 52ac2be..710f16a 100644 --- a/src/main/java/org/ros/chatto/model/Role.java +++ b/src/main/java/org/ros/chatto/model/Role.java @@ -16,7 +16,6 @@ import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; - @Entity @Table(name = "roles") @Data @@ -24,14 +23,14 @@ public class Role { @Id @Column(name = "role_id") private int roleID; - + @Column(name = "role_name") - private String name; - + private String name; + private String description; - - @OneToMany(mappedBy = "role", cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, - CascadeType.REFRESH }) + + @OneToMany(mappedBy = "role", cascade = { CascadeType.PERSIST, + CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH }) @JsonBackReference @ToString.Exclude @EqualsAndHashCode.Exclude diff --git a/src/main/java/org/ros/chatto/model/UserSession.java b/src/main/java/org/ros/chatto/model/UserSession.java index ccb4a9a..66ccdd3 100644 --- a/src/main/java/org/ros/chatto/model/UserSession.java +++ b/src/main/java/org/ros/chatto/model/UserSession.java @@ -20,13 +20,13 @@ public class UserSession { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; - + @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id") private ChatUser user; - + private boolean online; - + private int numSessions; private Instant timeStamp; } diff --git a/src/main/java/org/ros/chatto/repository/DBInitializerRepostory.java b/src/main/java/org/ros/chatto/repository/DBInitializerRepostory.java index e8b3112..6c8822f 100644 --- a/src/main/java/org/ros/chatto/repository/DBInitializerRepostory.java +++ b/src/main/java/org/ros/chatto/repository/DBInitializerRepostory.java @@ -1,9 +1,10 @@ -//package org.ros.chatto.repository; +// package org.ros.chatto.repository; // -//import org.springframework.data.jpa.repository.JpaRepository; -//import org.springframework.stereotype.Repository; +// import org.springframework.data.jpa.repository.JpaRepository; +// import org.springframework.stereotype.Repository; // -//@Repository -//public interface DBInitializerRepostory extends JpaRepository{ -// -//} +// @Repository +// public interface DBInitializerRepostory extends JpaRepository{ +// +// } diff --git a/src/main/java/org/ros/chatto/repository/MessageCipherRepository.java b/src/main/java/org/ros/chatto/repository/MessageCipherRepository.java index d8b4dc2..46b94e6 100644 --- a/src/main/java/org/ros/chatto/repository/MessageCipherRepository.java +++ b/src/main/java/org/ros/chatto/repository/MessageCipherRepository.java @@ -5,6 +5,7 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository -public interface MessageCipherRepository extends JpaRepository{ +public interface MessageCipherRepository + extends JpaRepository { } diff --git a/src/main/java/org/ros/chatto/repository/RoleRepository.java b/src/main/java/org/ros/chatto/repository/RoleRepository.java index 59447d3..73231d6 100644 --- a/src/main/java/org/ros/chatto/repository/RoleRepository.java +++ b/src/main/java/org/ros/chatto/repository/RoleRepository.java @@ -6,7 +6,7 @@ import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository -public interface RoleRepository extends JpaRepository{ +public interface RoleRepository extends JpaRepository { @Query("select r from Role r where r.name = ?1") public Role findByName(String roleName); } diff --git a/src/main/java/org/ros/chatto/repository/UserRepositoryCustom.java b/src/main/java/org/ros/chatto/repository/UserRepositoryCustom.java index a5f7434..d27c9cf 100644 --- a/src/main/java/org/ros/chatto/repository/UserRepositoryCustom.java +++ b/src/main/java/org/ros/chatto/repository/UserRepositoryCustom.java @@ -4,8 +4,8 @@ import java.util.List; public interface UserRepositoryCustom { -// @Query("select s from Article s where s.author like ?1 and s.title = ?2") -// List
findByAuthorAndTitle(String author, String title); -// @Query("select u from ChatUser u") + // @Query("select s from Article s where s.author like ?1 and s.title = ?2") + // List
findByAuthorAndTitle(String author, String title); + // @Query("select u from ChatUser u") public List getAllUserNames(String s); } diff --git a/src/main/java/org/ros/chatto/repository/UserRepositoryCustomImpl.java b/src/main/java/org/ros/chatto/repository/UserRepositoryCustomImpl.java index ddb8a89..a6f7f74 100644 --- a/src/main/java/org/ros/chatto/repository/UserRepositoryCustomImpl.java +++ b/src/main/java/org/ros/chatto/repository/UserRepositoryCustomImpl.java @@ -14,30 +14,34 @@ import org.ros.chatto.model.ChatUser; import org.ros.chatto.repository.UserRepositoryCustom; @Service -class UserRepositoryCustomImpl implements UserRepositoryCustom{ +class UserRepositoryCustomImpl implements UserRepositoryCustom { @PersistenceContext private EntityManager entityManager; @Override public List getAllUserNames(String userName) { List userNamesList = null; -// Session session = null; + // Session session = null; try { - CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); - CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(String.class); + CriteriaBuilder criteriaBuilder = entityManager + .getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder + .createQuery(String.class); Root root = criteriaQuery.from(ChatUser.class); criteriaQuery.select(root.get("userName")); - criteriaQuery.where(criteriaBuilder.notEqual(root.get("userName"), userName)); - - userNamesList = entityManager.createQuery(criteriaQuery).getResultList(); -// for(String un: userNamesList) -// { -// System.out.println(un); -// } + criteriaQuery.where( + criteriaBuilder.notEqual(root.get("userName"), userName)); + + userNamesList = entityManager.createQuery(criteriaQuery) + .getResultList(); + // for(String un: userNamesList) + // { + // System.out.println(un); + // } } catch (Exception e) { e.printStackTrace(); } return userNamesList; } - + } diff --git a/src/main/java/org/ros/chatto/security/AuthenticationSuccessHandlerImpl.java b/src/main/java/org/ros/chatto/security/AuthenticationSuccessHandlerImpl.java index 3330c53..e8ca70a 100644 --- a/src/main/java/org/ros/chatto/security/AuthenticationSuccessHandlerImpl.java +++ b/src/main/java/org/ros/chatto/security/AuthenticationSuccessHandlerImpl.java @@ -16,20 +16,29 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand import org.springframework.stereotype.Component; @Component -public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler { - - private static final SimpleGrantedAuthority SUPER_USER_AUTHORITY = new SimpleGrantedAuthority("ROLE_SUPER_USER"); - private static final SimpleGrantedAuthority ADMIN_AUTHORITY = new SimpleGrantedAuthority("ROLE_ADMIN"); - private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); +public class AuthenticationSuccessHandlerImpl + implements AuthenticationSuccessHandler { + + private static final SimpleGrantedAuthority SUPER_USER_AUTHORITY = new SimpleGrantedAuthority( + "ROLE_SUPER_USER"); + private static final SimpleGrantedAuthority ADMIN_AUTHORITY = new SimpleGrantedAuthority( + "ROLE_ADMIN"); + private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Override - public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, - Authentication authentication) throws IOException, ServletException { - Collection authorities = authentication.getAuthorities(); - if (authorities.contains(ADMIN_AUTHORITY) || authorities.contains(SUPER_USER_AUTHORITY)) { - redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, "/admin"); - } else { - redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, "/user"); - } + public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, + HttpServletResponse httpServletResponse, + Authentication authentication) + throws IOException, ServletException { + Collection authorities = authentication + .getAuthorities(); + if (authorities.contains(ADMIN_AUTHORITY) + || authorities.contains(SUPER_USER_AUTHORITY)) { + redirectStrategy.sendRedirect(httpServletRequest, + httpServletResponse, "/admin"); + } else { + redirectStrategy.sendRedirect(httpServletRequest, + httpServletResponse, "/user"); + } } } diff --git a/src/main/java/org/ros/chatto/service/CaptchaService.java b/src/main/java/org/ros/chatto/service/CaptchaService.java index c372bc1..4e94f81 100644 --- a/src/main/java/org/ros/chatto/service/CaptchaService.java +++ b/src/main/java/org/ros/chatto/service/CaptchaService.java @@ -9,18 +9,17 @@ import org.springframework.stereotype.Service; @Service public class CaptchaService { private final WebCaptcha webCaptcha; - + public CaptchaService() { - webCaptcha = WebCaptcha.builder().captchaBehaviour(new SimpleCaptchaBehavior()).build(); + webCaptcha = WebCaptcha.builder() + .captchaBehaviour(new SimpleCaptchaBehavior()).build(); } - - public BufferedImage createCaptchaImage(final String captchaText) - { + + public BufferedImage createCaptchaImage(final String captchaText) { return webCaptcha.generateCaptcha(captchaText); } - - public String getRandomText() - { + + public String getRandomText() { return webCaptcha.getRandomChars(); } } diff --git a/src/main/java/org/ros/chatto/service/DBInitializerService.java b/src/main/java/org/ros/chatto/service/DBInitializerService.java index 18b84df..64913e1 100644 --- a/src/main/java/org/ros/chatto/service/DBInitializerService.java +++ b/src/main/java/org/ros/chatto/service/DBInitializerService.java @@ -46,13 +46,15 @@ public class DBInitializerService { }); } - private void resetAllUserSessions(final Connection connection) throws SQLException { + private void resetAllUserSessions(final Connection connection) + throws SQLException { final PreparedStatement preparedStatement = connection .prepareStatement(dbInitializerConfig.getResetSessionsQuery()); preparedStatement.executeUpdate(); } - private void clearAllTokens(final Connection connection) throws SQLException { + private void clearAllTokens(final Connection connection) + throws SQLException { final PreparedStatement preparedStatement = connection .prepareStatement(dbInitializerConfig.getClearTokensQuery()); preparedStatement.executeUpdate(); diff --git a/src/test/java/org/ros/chatto/ChattoApplicationTests.java b/src/test/java/org/ros/chatto/ChattoApplicationTests.java index 31ca047..8b0a3cc 100644 --- a/src/test/java/org/ros/chatto/ChattoApplicationTests.java +++ b/src/test/java/org/ros/chatto/ChattoApplicationTests.java @@ -15,65 +15,68 @@ // @RunWith(SpringRunner.class) // @SpringBootTest // public class ChattoApplicationTests { - -// // @Autowired -// // ChatMessageRepository chatMessageRepository; -// // -// // @Mock -// // ChatMessageRepository mockChatMessageRepository; -// // -// @Autowired -// private UserRepository userRepository; - -// @Autowired -// private UserRoleRepository userRoleRepository; - -// private final Logger logger = LoggerFactory.getLogger(ChattoApplicationTests.class); + +// // @Autowired +// // ChatMessageRepository chatMessageRepository; +// // +// // @Mock +// // ChatMessageRepository mockChatMessageRepository; // // -// @Test -// public void contextLoads() { -// } +// @Autowired +// private UserRepository userRepository; + +// @Autowired +// private UserRoleRepository userRoleRepository; + +// private final Logger logger = +// LoggerFactory.getLogger(ChattoApplicationTests.class); // // -// // @Test -// // public void testMessageRepo() { -// // chatMessageRepository.findAll().toString(); -// // } - -// @Test -// public void testRoleRepo() { -// List list = userRoleRepository.getAllRegularUser(); -// logger.info("List = {} ", list); -// } - -// @Test -// public void findAllOtherUsers() { -// logger.info("Usernames = {}",userRepository.findAllOtherUserNames("hmm").toString()); -// } - -// // @Test -// // public void testSave() { -// // ChatUser fromUser = new ChatUser(); -// // fromUser = userRepository.findByUserName("hmm"); -// // ChatUser toUser = new ChatUser(); -// // toUser = userRepository.findByUserName("user2"); -// // ChatMessage chatMessage = new ChatMessage(); -// // chatMessage.setMessage("Hello!"); -// // chatMessage.setFromUser(fromUser); -// // chatMessage.setToUser(toUser); -// // -// // chatMessageRepository.save(chatMessage); -// // } - -// /* -// * @Test public void testSave() { ChatUser fromUser = new ChatUser(); fromUser = -// * userRepository.findByUserName("hmm"); ChatUser toUser = new ChatUser(); -// * toUser = userRepository.findByUserName("user2"); ChatMessage chatMessage = -// * new ChatMessage(); chatMessage.setMessage("Hello!"); -// * chatMessage.setFromUser(fromUser); chatMessage.setToUser(toUser); -// * -// * // chatMessageRepository.save(chatMessage); -// * when(mockChatMessageRepository.save(any(ChatMessage.class))).thenReturn( -// * chatMessage); verify(mockChatMessageRepository, -// * times(1)).save(Mockito.any(ChatMessage.class)); } -// */ +// @Test +// public void contextLoads() { +// } +// // +// // @Test +// // public void testMessageRepo() { +// // chatMessageRepository.findAll().toString(); +// // } + +// @Test +// public void testRoleRepo() { +// List list = userRoleRepository.getAllRegularUser(); +// logger.info("List = {} ", list); +// } + +// @Test +// public void findAllOtherUsers() { +// logger.info("Usernames = +// {}",userRepository.findAllOtherUserNames("hmm").toString()); +// } + +// // @Test +// // public void testSave() { +// // ChatUser fromUser = new ChatUser(); +// // fromUser = userRepository.findByUserName("hmm"); +// // ChatUser toUser = new ChatUser(); +// // toUser = userRepository.findByUserName("user2"); +// // ChatMessage chatMessage = new ChatMessage(); +// // chatMessage.setMessage("Hello!"); +// // chatMessage.setFromUser(fromUser); +// // chatMessage.setToUser(toUser); +// // +// // chatMessageRepository.save(chatMessage); +// // } + +// /* +// * @Test public void testSave() { ChatUser fromUser = new ChatUser(); fromUser +// = +// * userRepository.findByUserName("hmm"); ChatUser toUser = new ChatUser(); +// * toUser = userRepository.findByUserName("user2"); ChatMessage chatMessage = +// * new ChatMessage(); chatMessage.setMessage("Hello!"); +// * chatMessage.setFromUser(fromUser); chatMessage.setToUser(toUser); +// * +// * // chatMessageRepository.save(chatMessage); +// * when(mockChatMessageRepository.save(any(ChatMessage.class))).thenReturn( +// * chatMessage); verify(mockChatMessageRepository, +// * times(1)).save(Mockito.any(ChatMessage.class)); } +// */ // } diff --git a/src/test/java/org/ros/chatto/UnitTest.java b/src/test/java/org/ros/chatto/UnitTest.java index e236388..58e2c13 100644 --- a/src/test/java/org/ros/chatto/UnitTest.java +++ b/src/test/java/org/ros/chatto/UnitTest.java @@ -32,61 +32,62 @@ // @RunWith(MockitoJUnitRunner.class) // @Slf4j // public class UnitTest { -// @InjectMocks - -// // private RoleService roleService; -// // private UserTokenService userTokenService; - -// @Mock -// private UserRoleRepository userRoleRepository; - -// @Mock -// private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); - -// @Mock -// private RoleRepository roleRepository; - -// @Mock -// private UserRepositoryCustom userRepositoryCustom; - -// @Mock -// private UserSessionRepository userSessionRepository; - -// @Mock -// private UserRepository userRepository; - -// private UserService userService = new UserServiceImpl(userRepository, userRoleRepository, passwordEncoder, roleRepository, -// userSessionRepository); -// // private ChatUser chatUser; - -// @Before -// public void setupMock() { -// // userRepository = mock(UserRepository.class); -// // chatUser = mock(ChatUser.class); -// } - -// @Test -// public void userRegistrationTest() { -// UserRegistrationDTO userRegistrationDTO = new UserRegistrationDTO(); -// userRegistrationDTO.setUserName("mickey"); -// userRegistrationDTO.setPassword("mouse"); - -// ChatUser chatUser = new ChatUser(); -// chatUser.setUserName("mickey"); -// // chatUser.setPassword("mouse"); - -// Role role = new Role(); -// role.setRoleID(2); -// role.setName("USER"); -// when(roleRepository.findByName("USER")).thenReturn(role); -// when(userRepository.save(chatUser)).thenReturn(chatUser); - -// UserRole userRole = userService.registerUser(userRegistrationDTO); -// assertArrayEquals(new Object[] { 2, "USER","mickey" }, -// new Object[] { userRole.getRole().getRoleID(), -// userRole.getRole().getName(), userRole.getUser().getUserName() }); -// verify(userRepository, times(1)).save(chatUser); -// verify(userRoleRepository,times(1)).save(userRole); -// } +// @InjectMocks + +// // private RoleService roleService; +// // private UserTokenService userTokenService; + +// @Mock +// private UserRoleRepository userRoleRepository; + +// @Mock +// private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + +// @Mock +// private RoleRepository roleRepository; + +// @Mock +// private UserRepositoryCustom userRepositoryCustom; + +// @Mock +// private UserSessionRepository userSessionRepository; + +// @Mock +// private UserRepository userRepository; + +// private UserService userService = new UserServiceImpl(userRepository, +// userRoleRepository, passwordEncoder, roleRepository, +// userSessionRepository); +// // private ChatUser chatUser; + +// @Before +// public void setupMock() { +// // userRepository = mock(UserRepository.class); +// // chatUser = mock(ChatUser.class); +// } + +// @Test +// public void userRegistrationTest() { +// UserRegistrationDTO userRegistrationDTO = new UserRegistrationDTO(); +// userRegistrationDTO.setUserName("mickey"); +// userRegistrationDTO.setPassword("mouse"); + +// ChatUser chatUser = new ChatUser(); +// chatUser.setUserName("mickey"); +// // chatUser.setPassword("mouse"); + +// Role role = new Role(); +// role.setRoleID(2); +// role.setName("USER"); +// when(roleRepository.findByName("USER")).thenReturn(role); +// when(userRepository.save(chatUser)).thenReturn(chatUser); + +// UserRole userRole = userService.registerUser(userRegistrationDTO); +// assertArrayEquals(new Object[] { 2, "USER","mickey" }, +// new Object[] { userRole.getRole().getRoleID(), +// userRole.getRole().getName(), userRole.getUser().getUserName() }); +// verify(userRepository, times(1)).save(chatUser); +// verify(userRoleRepository,times(1)).save(userRole); +// } // }