added formatter plugin

This commit is contained in:
Rohan Sircar 2020-08-11 17:30:48 +05:30
parent ced84a05a6
commit af4181185c
44 changed files with 600 additions and 528 deletions

1
.gitignore vendored
View File

@ -29,6 +29,7 @@ build/
### VS Code ### ### VS Code ###
.vscode/ .vscode/
.cache/
node_modules node_modules
bundle.js bundle.js

11
pom.xml
View File

@ -223,6 +223,17 @@
</excludeProperties> </excludeProperties>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>net.revelc.code.formatter</groupId>
<artifactId>formatter-maven-plugin</artifactId>
<version>2.12.0</version>
<configuration>
<configFile>${project.basedir}/eclipse-formatter.xml</configFile>
<compilerSource>11</compilerSource>
<compilerCompliance>11</compilerCompliance>
<compilerTargetPlatform>11</compilerTargetPlatform>
</configuration>
</plugin>
</plugins> </plugins>
</build> </build>
</project> </project>

View File

@ -1,34 +1,34 @@
{ {
"properties": [ "properties" : [
{ {
"name": "chatto.token.timeout-duration", "name" : "chatto.token.timeout-duration",
"type": "java.lang.String", "type" : "java.lang.String",
"description": "The duration for auth token validity. Token expires after this period of inactivity" "description" : "The duration for auth token validity. Token expires after this period of inactivity"
}, },
{ {
"name": "chatto.frontend.log-level", "name" : "chatto.frontend.log-level",
"type": "java.lang.String", "type" : "java.lang.String",
"description": "The log level for the frontend JS application" "description" : "The log level for the frontend JS application"
}, },
{ {
"name": "chatto.frontend.chat-page-size", "name" : "chatto.frontend.chat-page-size",
"type": "java.lang.Integer", "type" : "java.lang.Integer",
"description": "The pagination size for the chat area" "description" : "The pagination size for the chat area"
}, },
{ {
"name": "chat-worker-bundle", "name" : "chat-worker-bundle",
"type": "java.lang.String", "type" : "java.lang.String",
"description": "Name of the chat worker js bundle" "description" : "Name of the chat worker js bundle"
}, },
{ {
"name": "chat-bundle", "name" : "chat-bundle",
"type": "java.lang.String", "type" : "java.lang.String",
"description": "Name of the chatjs bundle" "description" : "Name of the chatjs bundle"
}, },
{ {
"name": "admin-bundle", "name" : "admin-bundle",
"type": "java.lang.String", "type" : "java.lang.String",
"description": "Name of the admin js bundle" "description" : "Name of the admin js bundle"
} }
] ]
} }

View File

@ -15,72 +15,75 @@ import org.springframework.security.crypto.password.PasswordEncoder;
public class V3__add_default_admin extends BaseJavaMigration { 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 */ /** different dictionaries used */
private final String ALPHA_CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private final String ALPHA_CAPS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private final String ALPHA = "abcdefghijklmnopqrstuvwxyz"; private final String ALPHA = "abcdefghijklmnopqrstuvwxyz";
private final String NUMERIC = "0123456789"; private final String NUMERIC = "0123456789";
private final String SPECIAL_CHARS = "!@#$%^&*_=+-/"; private final String SPECIAL_CHARS = "!@#$%^&*_=+-/";
/** /**
* Method will generate random string based on the parameters * Method will generate random string based on the parameters
* *
* @param len the length of the random string * @param len
* @param dic the dictionary used to generate the password * the length of the random string
* @return the random password * @param dic
*/ * the dictionary used to generate the password
public String generatePassword(int len, String dic) { * @return the random password
String result = ""; */
for (int i = 0; i < len; i++) { public String generatePassword(int len, String dic) {
int index = random.nextInt(dic.length()); String result = "";
result += dic.charAt(index); for (int i = 0; i < len; i++) {
} int index = random.nextInt(dic.length());
return result; result += dic.charAt(index);
} }
return result;
}
@Override @Override
public void migrate(final Context context) throws Exception { public void migrate(final Context context) throws Exception {
try (final PreparedStatement ps = context.getConnection() try (final PreparedStatement ps = context.getConnection()
.prepareStatement("insert into users (user_id, name, password) values (0,?,?)")) { .prepareStatement(
final String generatedPassword = generatePassword(60, ALPHA_CAPS + ALPHA + SPECIAL_CHARS); "insert into users (user_id, name, password) values (0,?,?)")) {
final BufferedWriter bw = new BufferedWriter( final String generatedPassword = generatePassword(60,
new FileWriter("gen-password.txt")); ALPHA_CAPS + ALPHA + SPECIAL_CHARS);
final BufferedWriter bw = new BufferedWriter(
bw.write(generatedPassword); new FileWriter("gen-password.txt"));
bw.write("\nPlease delete this file");
bw.close();
final var perms = Files.getPosixFilePermissions(Paths.get( bw.write(generatedPassword);
"gen-password.txt")); bw.write("\nPlease delete this file");
bw.close();
final var perms = Files
.getPosixFilePermissions(Paths.get("gen-password.txt"));
//add owners permission // add owners permission
perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_WRITE);
perms.remove(PosixFilePermission.OWNER_EXECUTE); perms.remove(PosixFilePermission.OWNER_EXECUTE);
//add group permissions // add group permissions
perms.remove(PosixFilePermission.GROUP_READ); perms.remove(PosixFilePermission.GROUP_READ);
perms.remove(PosixFilePermission.GROUP_WRITE); perms.remove(PosixFilePermission.GROUP_WRITE);
perms.remove(PosixFilePermission.GROUP_EXECUTE); perms.remove(PosixFilePermission.GROUP_EXECUTE);
//add others permissions // add others permissions
perms.remove(PosixFilePermission.OTHERS_READ); perms.remove(PosixFilePermission.OTHERS_READ);
perms.remove(PosixFilePermission.OTHERS_WRITE); perms.remove(PosixFilePermission.OTHERS_WRITE);
perms.remove(PosixFilePermission.OTHERS_EXECUTE); perms.remove(PosixFilePermission.OTHERS_EXECUTE);
Files.setPosixFilePermissions(Paths.get("gen-password.txt"), perms); Files.setPosixFilePermissions(Paths.get("gen-password.txt"), perms);
ps.setString(1, "admin");
ps.setString(2, passwordEncoder.encode(generatedPassword));
ps.execute();
}
ps.setString(1, "admin"); try (final PreparedStatement ps = context.getConnection()
ps.setString(2, passwordEncoder.encode(generatedPassword)); .prepareStatement(
ps.execute(); "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();
}
}
} }

View File

@ -17,8 +17,8 @@ public class ChattoApplication extends SpringBootServletInitializer {
} }
@Configuration @Configuration
@Profile("development") @Profile("development")
@ComponentScan(lazyInit = true) @ComponentScan(lazyInit = true)
static class LocalConfig { static class LocalConfig {
} }
} }

View File

@ -12,19 +12,21 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationEn
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
public final class RESTAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { public final class RESTAuthenticationEntryPoint
extends BasicAuthenticationEntryPoint {
@Override @Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) public void commence(HttpServletRequest request,
throws IOException, ServletException { HttpServletResponse response, AuthenticationException authEx)
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); throws IOException, ServletException {
PrintWriter writer = response.getWriter(); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
writer.println("HTTP ApplicationStatus 401 - " + authEx.getMessage()); PrintWriter writer = response.getWriter();
} writer.println("HTTP ApplicationStatus 401 - " + authEx.getMessage());
}
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
setRealmName("Chatto"); setRealmName("Chatto");
super.afterPropertiesSet(); super.afterPropertiesSet();
} }
} }

View File

@ -6,7 +6,8 @@ import org.springframework.boot.web.servlet.support.SpringBootServletInitializer
public class ServletInitializer extends SpringBootServletInitializer { public class ServletInitializer extends SpringBootServletInitializer {
@Override @Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(ChattoApplication.class); return application.sources(ChattoApplication.class);
} }

View File

@ -5,16 +5,14 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration @Configuration
//@EnableWebMvc // @EnableWebMvc
public class WebConfig implements WebMvcConfigurer { public class WebConfig implements WebMvcConfigurer {
@Override @Override
public void addCorsMappings(CorsRegistry registry) { public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**") registry.addMapping("/api/**").allowedOrigins("*")
.allowedOrigins("*") .allowedMethods("POST", "GET", "OPTIONS").allowedHeaders("*")
.allowedMethods("POST","GET","OPTIONS") .allowCredentials(false).maxAge(3600);
.allowedHeaders("*")
.allowCredentials(false).maxAge(3600);
} }
} }

View File

@ -4,7 +4,10 @@ import java.awt.image.BufferedImage;
interface CaptchaBehaviour { interface CaptchaBehaviour {
public BufferedImage generateCaptcha(); public BufferedImage generateCaptcha();
public BufferedImage generateCaptcha(String captchaText); public BufferedImage generateCaptcha(String captchaText);
public String getRandomChars(int size); public String getRandomChars(int size);
public String getRandomChars(); public String getRandomChars();
} }

View File

@ -6,9 +6,10 @@ import lombok.Builder;
/*Class for providing your own captcha generator*/ /*Class for providing your own captcha generator*/
@Builder @Builder
public class ManualCaptchaBehaviour implements CaptchaBehaviour{ public class ManualCaptchaBehaviour implements CaptchaBehaviour {
private final int length; private final int length;
private final String style; private final String style;
@Override @Override
public BufferedImage generateCaptcha() { public BufferedImage generateCaptcha() {
// TODO Auto-generated method stub // TODO Auto-generated method stub
@ -33,5 +34,4 @@ public class ManualCaptchaBehaviour implements CaptchaBehaviour{
return null; return null;
} }
} }

View File

@ -10,174 +10,183 @@ import java.io.IOException;
import java.util.Random; import java.util.Random;
/** /**
* This class represents a simple captcha consisting * This class represents a simple captcha consisting of an image {@code png} and
* of an image {@code png} and its text value. * its text value. Comic Neue Bold Font. Capital english letters {@code ONLY}.
* Comic Neue Bold Font.
* Capital english letters {@code ONLY}.
* *
* @since 1.3 * @since 1.3
* @author Gennadiy Golovin * @author Gennadiy Golovin
*/ */
public final class SimpleCaptcha { public final class SimpleCaptcha {
private BufferedImage imagePng; private BufferedImage imagePng;
private char[] text; private char[] text;
/** /**
* Initializes a newly created default object * Initializes a newly created default object consisting of 8 capital
* consisting of 8 capital english letters. * english letters.
*/ */
public SimpleCaptcha() { public SimpleCaptcha() {
this.text = getRandomChars(); this.text = getRandomChars();
try { try {
generateCaptcha(); generateCaptcha();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* Initializes a newly created object, which length * Initializes a newly created object, which length depends on the passed
* depends on the passed {@code int} parameter, * {@code int} parameter, which {@code MUST} be greater than 0. If the
* which {@code MUST} be greater than 0. * condition is not met, initializes a newly created default object
* If the condition is not met, initializes a newly * consisting of 8 symbols.
* created default object consisting of 8 symbols. *
* * @param length
* @param length the quantity of symbols, that the * the quantity of symbols, that the captcha consists of, greater
* captcha consists of, greater than 0. * than 0.
*/ */
public SimpleCaptcha(int length) { public SimpleCaptcha(int length) {
if (length < 1) { if (length < 1) {
this.text = getRandomChars(); this.text = getRandomChars();
} else { } else {
this.text = getRandomChars(length); this.text = getRandomChars(length);
} }
try { try {
generateCaptcha(); generateCaptcha();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
/** /**
* Initializes a newly created object based on the passed * Initializes a newly created object based on the passed {@link String}
* {@link String} parameter, consisting of capital english * parameter, consisting of capital english letters. If the condition is not
* letters. If the condition is not met, initializes a newly * met, initializes a newly created default object consisting of 8 capital
* created default object consisting of 8 capital english letters. * english letters.
* *
* @param text the text string with the value of the captcha, * @param text
* length greater than 0. * the text string with the value of the captcha, length greater
*/ * than 0.
public SimpleCaptcha(String text) { */
if (text == null || text.equals("")) { public SimpleCaptcha(String text) {
this.text = getRandomChars(); if (text == null || text.equals("")) {
} else { this.text = getRandomChars();
this.text = text.toCharArray(); } else {
} this.text = text.toCharArray();
}
try { try {
generateCaptcha(); generateCaptcha();
} catch (IOException e) { } catch (IOException e) {
this.text = getRandomChars(); this.text = getRandomChars();
try { try {
generateCaptcha(); generateCaptcha();
} catch (IOException ex) { } catch (IOException ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
} }
/** /**
* Returns the picture with captcha * Returns the picture with captcha
* *
* @return {@link BufferedImage} * @return {@link BufferedImage}
*/ */
public BufferedImage getImagePng() { public BufferedImage getImagePng() {
return imagePng; return imagePng;
} }
/** /**
* Returns the text value of the captcha * Returns the text value of the captcha
* *
* @return {@link String} * @return {@link String}
*/ */
public String getText() { public String getText() {
return String.valueOf(text); return String.valueOf(text);
} }
//////// //////// //////// //////// //////// //////// //////// //////// //////// //////// //////// //////// //////// //////// //////// ////////
private char[] getRandomChars() { private char[] getRandomChars() {
return getRandomChars(8); return getRandomChars(8);
} }
private char[] getRandomChars(int quantity) { private char[] getRandomChars(int quantity) {
char[] randomString = new char[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++) { for (int i = 0; i < quantity; i++) {
capitalLetter = 65 + random.nextInt(26); capitalLetter = 65 + random.nextInt(26);
randomString[i] = (char) capitalLetter; randomString[i] = (char) capitalLetter;
} }
return randomString; return randomString;
} }
private void generateCaptcha() throws IOException { private void generateCaptcha() throws IOException {
int charsQuantity = this.text.length; int charsQuantity = this.text.length;
BufferedImage[] images = new BufferedImage[charsQuantity]; BufferedImage[] images = new BufferedImage[charsQuantity];
for (int i = 0; i < charsQuantity; i++) { for (int i = 0; i < charsQuantity; i++) {
images[i] = ImageIO.read(SimpleCaptcha.class.getResourceAsStream("/pictures/" + this.text[i] + ".png")); images[i] = ImageIO.read(SimpleCaptcha.class
if (i % 2 == 0) { .getResourceAsStream("/pictures/" + this.text[i] + ".png"));
images[i] = rotateImage(images[i], 25); if (i % 2 == 0) {
} else { images[i] = rotateImage(images[i], 25);
images[i] = rotateImage(images[i], -20); } else {
} images[i] = rotateImage(images[i], -20);
} }
}
int imageSize = 30; int imageSize = 30;
int rotatedImageSize = (int) Math.sqrt(imageSize * imageSize * 2); int rotatedImageSize = (int) Math.sqrt(imageSize * imageSize * 2);
BufferedImage captchaImg = new BufferedImage(rotatedImageSize * (charsQuantity - 1) / 10 * 6 + rotatedImageSize, rotatedImageSize, BufferedImage.TYPE_INT_ARGB); BufferedImage captchaImg = new BufferedImage(
Graphics2D graphics2d = captchaImg.createGraphics(); rotatedImageSize * (charsQuantity - 1) / 10 * 6
graphics2d.setBackground(Color.WHITE); + rotatedImageSize,
graphics2d.clearRect(0, 0, captchaImg.getWidth(), captchaImg.getHeight()); rotatedImageSize, BufferedImage.TYPE_INT_ARGB);
for (int i = 0; i < charsQuantity; i++) { Graphics2D graphics2d = captchaImg.createGraphics();
captchaImg.getGraphics().drawImage(images[i], rotatedImageSize * i / 10 * 6, 0, null); graphics2d.setBackground(Color.WHITE);
} graphics2d.clearRect(0, 0, captchaImg.getWidth(),
graphics2d.dispose(); captchaImg.getHeight());
this.imagePng = captchaImg; 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) { private BufferedImage rotateImage(BufferedImage buffImage, double angle) {
double radian = Math.toRadians(angle); double radian = Math.toRadians(angle);
double sin = Math.abs(Math.sin(radian)); double sin = Math.abs(Math.sin(radian));
double cos = Math.abs(Math.cos(radian)); double cos = Math.abs(Math.cos(radian));
int width = buffImage.getWidth(); int width = buffImage.getWidth();
int height = buffImage.getHeight(); int height = buffImage.getHeight();
int nWidth = (int) Math.floor((double) width * cos + (double) height * sin); int nWidth = (int) Math
int nHeight = (int) Math.floor((double) height * cos + (double) width * sin); .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); BufferedImage rotatedImage = new BufferedImage(nWidth, nHeight,
BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = rotatedImage.createGraphics(); Graphics2D graphics = rotatedImage.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
graphics.translate((nWidth - width) / 2, (nHeight - height) / 2); RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.rotate(radian, (double) (width / 2), (double) (height / 2)); graphics.translate((nWidth - width) / 2, (nHeight - height) / 2);
graphics.drawImage(buffImage, 0, 0,null); graphics.rotate(radian, (double) (width / 2), (double) (height / 2));
graphics.dispose(); graphics.drawImage(buffImage, 0, 0, null);
graphics.dispose();
return rotatedImage; return rotatedImage;
} }
} }

View File

@ -9,30 +9,30 @@ public class SimpleCaptchaBehavior implements CaptchaBehaviour {
SimpleCaptcha simpleCaptcha = new SimpleCaptcha(); SimpleCaptcha simpleCaptcha = new SimpleCaptcha();
return simpleCaptcha.getImagePng(); return simpleCaptcha.getImagePng();
} }
@Override @Override
public BufferedImage generateCaptcha(String captchaText) { public BufferedImage generateCaptcha(String captchaText) {
SimpleCaptcha simpleCaptcha = new SimpleCaptcha(captchaText); SimpleCaptcha simpleCaptcha = new SimpleCaptcha(captchaText);
return simpleCaptcha.getImagePng(); return simpleCaptcha.getImagePng();
} }
public String getRandomChars() { public String getRandomChars() {
return getRandomChars(8); return getRandomChars(8);
} }
public String getRandomChars(int quantity) public String getRandomChars(int quantity) {
{
char[] randomString = new char[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++) { for (int i = 0; i < quantity; i++) {
capitalLetter = 65 + random.nextInt(26); capitalLetter = 65 + random.nextInt(26);
randomString[i] = (char) capitalLetter; randomString[i] = (char) capitalLetter;
} }
return new String(randomString); return new String(randomString);
} }
} }

View File

@ -7,34 +7,35 @@ import lombok.Builder;
@Builder @Builder
public class WebCaptcha { public class WebCaptcha {
private final CaptchaBehaviour captchaBehaviour; private final CaptchaBehaviour captchaBehaviour;
public BufferedImage generateCaptcha() { public BufferedImage generateCaptcha() {
return captchaBehaviour.generateCaptcha(); return captchaBehaviour.generateCaptcha();
} }
public BufferedImage generateCaptcha(String captchaText) { public BufferedImage generateCaptcha(String captchaText) {
return captchaBehaviour.generateCaptcha(captchaText); return captchaBehaviour.generateCaptcha(captchaText);
} }
public String getRandomChars() {
return captchaBehaviour.getRandomChars();
}
public String getRandomChars(int quantity) { public String getRandomChars() {
return captchaBehaviour.getRandomChars(quantity); return captchaBehaviour.getRandomChars();
} }
public String getRandomChars(int quantity) {
return captchaBehaviour.getRandomChars(quantity);
}
} }
// WebCaptcha webCaptcha = WebCaptcha.builder().captchaBehaviour(new SimpleCaptchaBehavior()).build(); // WebCaptcha webCaptcha = WebCaptcha.builder().captchaBehaviour(new
// webCaptcha.generateCaptcha(); // SimpleCaptchaBehavior()).build();
// webCaptcha.generateCaptcha();
// //
// // @formatter:off // // @formatter:off
// webCaptcha = WebCaptcha.builder() // webCaptcha = WebCaptcha.builder()
// .captchaBehaviour( // .captchaBehaviour(
// ManualCaptchaBehaviour.builder() // ManualCaptchaBehaviour.builder()
// .length(8) // .length(8)
// .style("black") // .style("black")
// .build() // .build()
// ).build(); // ).build();
// //
// // @formatter:on // // @formatter:on

View File

@ -10,13 +10,13 @@ import lombok.Getter;
@PropertySource(value = "classpath:git.properties") @PropertySource(value = "classpath:git.properties")
@Getter @Getter
public class BuildInfo { public class BuildInfo {
private final String buildVersion; private final String buildVersion;
private final String branchName; private final String branchName;
public BuildInfo(@Value("${git.build.version") String buildVersion, public BuildInfo(@Value("${git.build.version") String buildVersion,
@Value("${git.branch") String branchName) { @Value("${git.branch") String branchName) {
this.buildVersion = buildVersion; this.buildVersion = buildVersion;
this.branchName = branchName; this.branchName = branchName;
} }
} }

View File

@ -6,11 +6,14 @@ import org.ehcache.event.CacheEventListener;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
public class CustomCacheEventLogger implements CacheEventListener<Object, Object> { public class CustomCacheEventLogger
implements CacheEventListener<Object, Object> {
@Override @Override
public void onEvent(CacheEvent<? extends Object, ? extends Object> cacheEvent) { public void onEvent(
log.debug("custom Caching event {} key = {} old {} new {} ", cacheEvent.getType(), cacheEvent.getKey(), CacheEvent<? extends Object, ? extends Object> cacheEvent) {
log.debug("custom Caching event {} key = {} old {} new {} ",
cacheEvent.getType(), cacheEvent.getKey(),
cacheEvent.getOldValue(), cacheEvent.getNewValue()); cacheEvent.getOldValue(), cacheEvent.getNewValue());
} }
} }

View File

@ -1,6 +1,5 @@
package org.ros.chatto.config; package org.ros.chatto.config;
import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;

View File

@ -89,8 +89,8 @@ public class ChatMessageController {
@PathVariable final String userName, @PathVariable final String userName,
@PathVariable final Instant lastMessageTime, @PathVariable final Instant lastMessageTime,
final Principal principal) { final Principal principal) {
final List<ChatMessageDTO> chatMessageDTOs = chatService.getNewMessages( final List<ChatMessageDTO> chatMessageDTOs = chatService
principal.getName(), userName, lastMessageTime); .getNewMessages(principal.getName(), userName, lastMessageTime);
return chatMessageDTOs; return chatMessageDTOs;
} }

View File

@ -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;
}
}

View File

@ -45,7 +45,7 @@ public class Home {
|| r.getAuthority().equals("ROLE_SUPER_USER")); || r.getAuthority().equals("ROLE_SUPER_USER"));
log.trace("Is admin? " + isAdmin); log.trace("Is admin? " + isAdmin);
// model.addAttribute("activeUsers", // model.addAttribute("activeUsers",
// userService.getOtherActiveUsers(principal.getName())); // userService.getOtherActiveUsers(principal.getName()));
return "chat"; return "chat";
} }
} }

View File

@ -14,16 +14,16 @@ import lombok.RequiredArgsConstructor;
@RequestMapping("/api/stats") @RequestMapping("/api/stats")
@RequiredArgsConstructor @RequiredArgsConstructor
public class StatisticsController { public class StatisticsController {
private final StatisticsService statisticsService; private final StatisticsService statisticsService;
@GetMapping @GetMapping
public StatsDTO rootStats() { public StatsDTO rootStats() {
return StatsDTO.builder() return StatsDTO.builder()
.totalMessages(statisticsService.totalMessage()) .totalMessages(statisticsService.totalMessage())
.totalOnlineUsers(statisticsService.totalUsersOnline()) .totalOnlineUsers(statisticsService.totalUsersOnline())
.numMessagesToday( .numMessagesToday(
statisticsService.messagesOnDay(Instant.now())) statisticsService.messagesOnDay(Instant.now()))
.totalUsers(statisticsService.totalUsers()).build(); .totalUsers(statisticsService.totalUsers()).build();
} }
} }

View File

@ -6,9 +6,9 @@ import org.springframework.web.bind.annotation.RequestMapping;
@Controller @Controller
@RequestMapping("/user") @RequestMapping("/user")
public class UserController { public class UserController {
@RequestMapping @RequestMapping
public String viewUserProfile() { public String viewUserProfile() {
return "user/home"; return "user/home";
} }
} }

View File

@ -1,6 +1,5 @@
package org.ros.chatto.dto; package org.ros.chatto.dto;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern; import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
@ -12,10 +11,10 @@ import lombok.Data;
public class ChatMessageDTO { public class ChatMessageDTO {
@NotBlank(message = "Username should not be blank") @NotBlank(message = "Username should not be blank")
@Pattern(regexp = "^[A-Za-z0-9]+$", message = "Username must be alphanumeric") @Pattern(regexp = "^[A-Za-z0-9]+$", message = "Username must be alphanumeric")
@Size(max=15) @Size(max = 15)
private String toUser; private String toUser;
@Pattern(regexp = "^[A-Za-z0-9]+$", message = "Username must be alphanumeric") @Pattern(regexp = "^[A-Za-z0-9]+$", message = "Username must be alphanumeric")
@Size(max=15) @Size(max = 15)
private String fromUser; private String fromUser;
private MessageCipherDTO messageCipher; private MessageCipherDTO messageCipher;
private Instant messageTime; private Instant messageTime;

View File

@ -12,7 +12,9 @@ import lombok.Data;
@Data @Data
public class MessageCipherDTO { 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 @NotBlank
private String iv; private String iv;
@Max(1) @Max(1)

View File

@ -16,11 +16,13 @@ public class UserRegistrationDTO {
@Transient @Transient
@Size(min = 4, max = 75, message = "Password must be between 4 and 75 characters") @Size(min = 4, max = 75, message = "Password must be between 4 and 75 characters")
@NotBlank(message = "Password should not be blank") @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 String password;
private Long captchaID; private Long captchaID;
private String captchaText; private String captchaText;
private String captchaInput; private String captchaInput;
} }

View File

@ -7,15 +7,14 @@ import lombok.Data;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
@Data @Data
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class ErrorModel{ public class ErrorModel {
@JsonProperty("field_name") @JsonProperty("field_name")
private String fieldName; private String fieldName;
@JsonProperty("rejected_value") @JsonProperty("rejected_value")
private Object rejectedValue; private Object rejectedValue;
@JsonProperty("error_message") @JsonProperty("error_message")
private String messageError; private String messageError;
} }

View File

@ -15,6 +15,6 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor @AllArgsConstructor
public class ErrorResponse { public class ErrorResponse {
@JsonProperty("errors") @JsonProperty("errors")
private List<ErrorModel> errorMessage; private List<ErrorModel> errorMessage;
} }

View File

@ -4,5 +4,6 @@ import org.springframework.cache.annotation.CacheEvict;
public class TokenCacheUtil { public class TokenCacheUtil {
@CacheEvict(value = "userTokenCache", key = "#cacheKey") @CacheEvict(value = "userTokenCache", key = "#cacheKey")
public static void evictSingleTokenValue(String cacheKey) {} public static void evictSingleTokenValue(String cacheKey) {
}
} }

View File

@ -26,7 +26,8 @@ public class UserLoggingSessionListener implements HttpSessionBindingListener {
@Override @Override
public void valueBound(HttpSessionBindingEvent event) { public void valueBound(HttpSessionBindingEvent event) {
UserLoggingSessionListener user = (UserLoggingSessionListener) event.getValue(); UserLoggingSessionListener user = (UserLoggingSessionListener) event
.getValue();
log.debug("Incrementing session count for user {}", user.getUsername()); log.debug("Incrementing session count for user {}", user.getUsername());
@ -38,7 +39,8 @@ public class UserLoggingSessionListener implements HttpSessionBindingListener {
@Override @Override
public void valueUnbound(HttpSessionBindingEvent event) { public void valueUnbound(HttpSessionBindingEvent event) {
UserLoggingSessionListener user = (UserLoggingSessionListener) event.getValue(); UserLoggingSessionListener user = (UserLoggingSessionListener) event
.getValue();
log.debug("Decrementing session count for user {}", user.getUsername()); log.debug("Decrementing session count for user {}", user.getUsername());

View File

@ -11,17 +11,19 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component("myAuthenticationSuccessHandler") @Component("myAuthenticationSuccessHandler")
public class UserSessionLoggingLoginSuccessHandler implements AuthenticationSuccessHandler { public class UserSessionLoggingLoginSuccessHandler
implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, @Override
HttpServletResponse response, Authentication authentication) public void onAuthenticationSuccess(HttpServletRequest request,
throws IOException { HttpServletResponse response, Authentication authentication)
HttpSession session = request.getSession(false); throws IOException {
if (session != null) { HttpSession session = request.getSession(false);
UserLoggingSessionListener user = new UserLoggingSessionListener(authentication.getName()); if (session != null) {
session.setAttribute("user", user); UserLoggingSessionListener user = new UserLoggingSessionListener(
} authentication.getName());
response.sendRedirect("/chat"); session.setAttribute("user", user);
} }
response.sendRedirect("/chat");
}
} }

View File

@ -12,15 +12,16 @@ import org.springframework.security.web.authentication.logout.LogoutSuccessHandl
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component("myLogoutSuccessHandler") @Component("myLogoutSuccessHandler")
public class UserSessionLoggingLogoutSuccessHandler implements LogoutSuccessHandler{ public class UserSessionLoggingLogoutSuccessHandler
@Override implements LogoutSuccessHandler {
public void onLogoutSuccess(HttpServletRequest request, @Override
HttpServletResponse response, Authentication authentication) public void onLogoutSuccess(HttpServletRequest request,
throws IOException, ServletException { HttpServletResponse response, Authentication authentication)
HttpSession session = request.getSession(); throws IOException, ServletException {
if (session != null){ HttpSession session = request.getSession();
session.removeAttribute("user"); if (session != null) {
} session.removeAttribute("user");
response.sendRedirect("/login?logout"); }
} response.sendRedirect("/login?logout");
}
} }

View File

@ -24,18 +24,18 @@ public class ChatMessage {
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "m_id") @Column(name = "m_id")
private Long messageID; private Long messageID;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "from_user") @JoinColumn(name = "from_user")
private ChatUser fromUser; private ChatUser fromUser;
@ManyToOne(fetch = FetchType.LAZY) @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "to_user") @JoinColumn(name = "to_user")
private ChatUser toUser; private ChatUser toUser;
@OneToOne(fetch = FetchType.LAZY) @OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "message") @JoinColumn(name = "message")
private MessageCipher messageCipher; private MessageCipher messageCipher;
private Instant messageTime; private Instant messageTime;
} }

View File

@ -19,7 +19,7 @@ this is what the json will look like*/
@Entity @Entity
@Table(name = "message_ciphers") @Table(name = "message_ciphers")
@EntityListeners(AuditingEntityListener.class) @EntityListeners(AuditingEntityListener.class)
//@JsonIgnoreProperties(value = { "id"}, allowGetters = false) // @JsonIgnoreProperties(value = { "id"}, allowGetters = false)
public class MessageCipher { public class MessageCipher {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)

View File

@ -16,7 +16,6 @@ import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.ToString; import lombok.ToString;
@Entity @Entity
@Table(name = "roles") @Table(name = "roles")
@Data @Data
@ -24,14 +23,14 @@ public class Role {
@Id @Id
@Column(name = "role_id") @Column(name = "role_id")
private int roleID; private int roleID;
@Column(name = "role_name") @Column(name = "role_name")
private String name; private String name;
private String description; private String description;
@OneToMany(mappedBy = "role", cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, @OneToMany(mappedBy = "role", cascade = { CascadeType.PERSIST,
CascadeType.REFRESH }) CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH })
@JsonBackReference @JsonBackReference
@ToString.Exclude @ToString.Exclude
@EqualsAndHashCode.Exclude @EqualsAndHashCode.Exclude

View File

@ -20,13 +20,13 @@ public class UserSession {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private int id; private int id;
@OneToOne(fetch = FetchType.LAZY) @OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id") @JoinColumn(name = "user_id")
private ChatUser user; private ChatUser user;
private boolean online; private boolean online;
private int numSessions; private int numSessions;
private Instant timeStamp; private Instant timeStamp;
} }

View File

@ -1,9 +1,10 @@
//package org.ros.chatto.repository; // package org.ros.chatto.repository;
// //
//import org.springframework.data.jpa.repository.JpaRepository; // import org.springframework.data.jpa.repository.JpaRepository;
//import org.springframework.stereotype.Repository; // import org.springframework.stereotype.Repository;
// //
//@Repository // @Repository
//public interface DBInitializerRepostory extends JpaRepository<Integer, Integer>{ // public interface DBInitializerRepostory extends JpaRepository<Integer,
// // Integer>{
//} //
// }

View File

@ -5,6 +5,7 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@Repository @Repository
public interface MessageCipherRepository extends JpaRepository<MessageCipher, Long>{ public interface MessageCipherRepository
extends JpaRepository<MessageCipher, Long> {
} }

View File

@ -6,7 +6,7 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
@Repository @Repository
public interface RoleRepository extends JpaRepository<Role, Long>{ public interface RoleRepository extends JpaRepository<Role, Long> {
@Query("select r from Role r where r.name = ?1") @Query("select r from Role r where r.name = ?1")
public Role findByName(String roleName); public Role findByName(String roleName);
} }

View File

@ -4,8 +4,8 @@ import java.util.List;
public interface UserRepositoryCustom { public interface UserRepositoryCustom {
// @Query("select s from Article s where s.author like ?1 and s.title = ?2") // @Query("select s from Article s where s.author like ?1 and s.title = ?2")
// List<Article> findByAuthorAndTitle(String author, String title); // List<Article> findByAuthorAndTitle(String author, String title);
// @Query("select u from ChatUser u") // @Query("select u from ChatUser u")
public List<String> getAllUserNames(String s); public List<String> getAllUserNames(String s);
} }

View File

@ -14,30 +14,34 @@ import org.ros.chatto.model.ChatUser;
import org.ros.chatto.repository.UserRepositoryCustom; import org.ros.chatto.repository.UserRepositoryCustom;
@Service @Service
class UserRepositoryCustomImpl implements UserRepositoryCustom{ class UserRepositoryCustomImpl implements UserRepositoryCustom {
@PersistenceContext @PersistenceContext
private EntityManager entityManager; private EntityManager entityManager;
@Override @Override
public List<String> getAllUserNames(String userName) { public List<String> getAllUserNames(String userName) {
List<String> userNamesList = null; List<String> userNamesList = null;
// Session session = null; // Session session = null;
try { try {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaBuilder criteriaBuilder = entityManager
CriteriaQuery<String> criteriaQuery = criteriaBuilder.createQuery(String.class); .getCriteriaBuilder();
CriteriaQuery<String> criteriaQuery = criteriaBuilder
.createQuery(String.class);
Root<ChatUser> root = criteriaQuery.from(ChatUser.class); Root<ChatUser> root = criteriaQuery.from(ChatUser.class);
criteriaQuery.select(root.get("userName")); criteriaQuery.select(root.get("userName"));
criteriaQuery.where(criteriaBuilder.notEqual(root.get("userName"), userName)); criteriaQuery.where(
criteriaBuilder.notEqual(root.get("userName"), userName));
userNamesList = entityManager.createQuery(criteriaQuery).getResultList();
// for(String un: userNamesList) userNamesList = entityManager.createQuery(criteriaQuery)
// { .getResultList();
// System.out.println(un); // for(String un: userNamesList)
// } // {
// System.out.println(un);
// }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return userNamesList; return userNamesList;
} }
} }

View File

@ -16,20 +16,29 @@ import org.springframework.security.web.authentication.AuthenticationSuccessHand
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@Component @Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler { 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 static final SimpleGrantedAuthority SUPER_USER_AUTHORITY = new SimpleGrantedAuthority(
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); "ROLE_SUPER_USER");
private static final SimpleGrantedAuthority ADMIN_AUTHORITY = new SimpleGrantedAuthority(
"ROLE_ADMIN");
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override @Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
Authentication authentication) throws IOException, ServletException { HttpServletResponse httpServletResponse,
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); Authentication authentication)
if (authorities.contains(ADMIN_AUTHORITY) || authorities.contains(SUPER_USER_AUTHORITY)) { throws IOException, ServletException {
redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, "/admin"); Collection<? extends GrantedAuthority> authorities = authentication
} else { .getAuthorities();
redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, "/user"); if (authorities.contains(ADMIN_AUTHORITY)
} || authorities.contains(SUPER_USER_AUTHORITY)) {
redirectStrategy.sendRedirect(httpServletRequest,
httpServletResponse, "/admin");
} else {
redirectStrategy.sendRedirect(httpServletRequest,
httpServletResponse, "/user");
}
} }
} }

View File

@ -9,18 +9,17 @@ import org.springframework.stereotype.Service;
@Service @Service
public class CaptchaService { public class CaptchaService {
private final WebCaptcha webCaptcha; private final WebCaptcha webCaptcha;
public CaptchaService() { 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); return webCaptcha.generateCaptcha(captchaText);
} }
public String getRandomText() public String getRandomText() {
{
return webCaptcha.getRandomChars(); return webCaptcha.getRandomChars();
} }
} }

View File

@ -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 final PreparedStatement preparedStatement = connection
.prepareStatement(dbInitializerConfig.getResetSessionsQuery()); .prepareStatement(dbInitializerConfig.getResetSessionsQuery());
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
} }
private void clearAllTokens(final Connection connection) throws SQLException { private void clearAllTokens(final Connection connection)
throws SQLException {
final PreparedStatement preparedStatement = connection final PreparedStatement preparedStatement = connection
.prepareStatement(dbInitializerConfig.getClearTokensQuery()); .prepareStatement(dbInitializerConfig.getClearTokensQuery());
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();

View File

@ -15,65 +15,68 @@
// @RunWith(SpringRunner.class) // @RunWith(SpringRunner.class)
// @SpringBootTest // @SpringBootTest
// public class ChattoApplicationTests { // public class ChattoApplicationTests {
// // @Autowired // // @Autowired
// // ChatMessageRepository chatMessageRepository; // // ChatMessageRepository chatMessageRepository;
// //
// // @Mock
// // ChatMessageRepository mockChatMessageRepository;
// //
// @Autowired
// private UserRepository userRepository;
// @Autowired
// private UserRoleRepository userRoleRepository;
// private final Logger logger = LoggerFactory.getLogger(ChattoApplicationTests.class);
// // // //
// @Test // // @Mock
// public void contextLoads() { // // ChatMessageRepository mockChatMessageRepository;
// }
// // // //
// // @Test // @Autowired
// // public void testMessageRepo() { // private UserRepository userRepository;
// // chatMessageRepository.findAll().toString();
// // } // @Autowired
// private UserRoleRepository userRoleRepository;
// @Test
// public void testRoleRepo() { // private final Logger logger =
// List<String> list = userRoleRepository.getAllRegularUser(); // LoggerFactory.getLogger(ChattoApplicationTests.class);
// logger.info("List = {} ", list); // //
// } // @Test
// public void contextLoads() {
// @Test // }
// public void findAllOtherUsers() { // //
// logger.info("Usernames = {}",userRepository.findAllOtherUserNames("hmm").toString()); // // @Test
// } // // public void testMessageRepo() {
// // chatMessageRepository.findAll().toString();
// // @Test // // }
// // public void testSave() {
// // ChatUser fromUser = new ChatUser(); // @Test
// // fromUser = userRepository.findByUserName("hmm"); // public void testRoleRepo() {
// // ChatUser toUser = new ChatUser(); // List<String> list = userRoleRepository.getAllRegularUser();
// // toUser = userRepository.findByUserName("user2"); // logger.info("List = {} ", list);
// // ChatMessage chatMessage = new ChatMessage(); // }
// // chatMessage.setMessage("Hello!");
// // chatMessage.setFromUser(fromUser); // @Test
// // chatMessage.setToUser(toUser); // public void findAllOtherUsers() {
// // // logger.info("Usernames =
// // chatMessageRepository.save(chatMessage); // {}",userRepository.findAllOtherUserNames("hmm").toString());
// // } // }
// /* // // @Test
// * @Test public void testSave() { ChatUser fromUser = new ChatUser(); fromUser = // // public void testSave() {
// * userRepository.findByUserName("hmm"); ChatUser toUser = new ChatUser(); // // ChatUser fromUser = new ChatUser();
// * toUser = userRepository.findByUserName("user2"); ChatMessage chatMessage = // // fromUser = userRepository.findByUserName("hmm");
// * new ChatMessage(); chatMessage.setMessage("Hello!"); // // ChatUser toUser = new ChatUser();
// * chatMessage.setFromUser(fromUser); chatMessage.setToUser(toUser); // // toUser = userRepository.findByUserName("user2");
// * // // ChatMessage chatMessage = new ChatMessage();
// * // chatMessageRepository.save(chatMessage); // // chatMessage.setMessage("Hello!");
// * when(mockChatMessageRepository.save(any(ChatMessage.class))).thenReturn( // // chatMessage.setFromUser(fromUser);
// * chatMessage); verify(mockChatMessageRepository, // // chatMessage.setToUser(toUser);
// * times(1)).save(Mockito.any(ChatMessage.class)); } // //
// */ // // 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)); }
// */
// } // }

View File

@ -32,61 +32,62 @@
// @RunWith(MockitoJUnitRunner.class) // @RunWith(MockitoJUnitRunner.class)
// @Slf4j // @Slf4j
// public class UnitTest { // public class UnitTest {
// @InjectMocks // @InjectMocks
// // private RoleService roleService; // // private RoleService roleService;
// // private UserTokenService userTokenService; // // private UserTokenService userTokenService;
// @Mock // @Mock
// private UserRoleRepository userRoleRepository; // private UserRoleRepository userRoleRepository;
// @Mock // @Mock
// private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// @Mock // @Mock
// private RoleRepository roleRepository; // private RoleRepository roleRepository;
// @Mock // @Mock
// private UserRepositoryCustom userRepositoryCustom; // private UserRepositoryCustom userRepositoryCustom;
// @Mock // @Mock
// private UserSessionRepository userSessionRepository; // private UserSessionRepository userSessionRepository;
// @Mock // @Mock
// private UserRepository userRepository; // private UserRepository userRepository;
// private UserService userService = new UserServiceImpl(userRepository, userRoleRepository, passwordEncoder, roleRepository, // private UserService userService = new UserServiceImpl(userRepository,
// userSessionRepository); // userRoleRepository, passwordEncoder, roleRepository,
// // private ChatUser chatUser; // userSessionRepository);
// // private ChatUser chatUser;
// @Before // @Before
// public void setupMock() { // public void setupMock() {
// // userRepository = mock(UserRepository.class); // // userRepository = mock(UserRepository.class);
// // chatUser = mock(ChatUser.class); // // chatUser = mock(ChatUser.class);
// } // }
// @Test // @Test
// public void userRegistrationTest() { // public void userRegistrationTest() {
// UserRegistrationDTO userRegistrationDTO = new UserRegistrationDTO(); // UserRegistrationDTO userRegistrationDTO = new UserRegistrationDTO();
// userRegistrationDTO.setUserName("mickey"); // userRegistrationDTO.setUserName("mickey");
// userRegistrationDTO.setPassword("mouse"); // userRegistrationDTO.setPassword("mouse");
// ChatUser chatUser = new ChatUser(); // ChatUser chatUser = new ChatUser();
// chatUser.setUserName("mickey"); // chatUser.setUserName("mickey");
// // chatUser.setPassword("mouse"); // // chatUser.setPassword("mouse");
// Role role = new Role(); // Role role = new Role();
// role.setRoleID(2); // role.setRoleID(2);
// role.setName("USER"); // role.setName("USER");
// when(roleRepository.findByName("USER")).thenReturn(role); // when(roleRepository.findByName("USER")).thenReturn(role);
// when(userRepository.save(chatUser)).thenReturn(chatUser); // when(userRepository.save(chatUser)).thenReturn(chatUser);
// UserRole userRole = userService.registerUser(userRegistrationDTO); // UserRole userRole = userService.registerUser(userRegistrationDTO);
// assertArrayEquals(new Object[] { 2, "USER","mickey" }, // assertArrayEquals(new Object[] { 2, "USER","mickey" },
// new Object[] { userRole.getRole().getRoleID(), // new Object[] { userRole.getRole().getRoleID(),
// userRole.getRole().getName(), userRole.getUser().getUserName() }); // userRole.getRole().getName(), userRole.getUser().getUserName() });
// verify(userRepository, times(1)).save(chatUser); // verify(userRepository, times(1)).save(chatUser);
// verify(userRoleRepository,times(1)).save(userRole); // verify(userRoleRepository,times(1)).save(userRole);
// } // }
// } // }