Test using Optional in repository

Trying out fetching values from repository as Optional.
Plus set line length to 80
This commit is contained in:
Rohan Sircar 2020-05-27 16:16:04 +05:30
parent 4c64dfd2b1
commit 5978eaebaa
13 changed files with 189 additions and 175 deletions

View File

@ -0,0 +1,7 @@
## chatto DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
chatto.datasource.url = jdbc:mysql://localhost:3306/chatto_db2?useSSL=false
chatto.datasource.username = chatto_user
chatto.datasource.password = password
chatto.datasource.database-name = chatto_db2
website-url = 192.168.1.13
test.bindAddress=192.168.1.106

View File

@ -34,8 +34,8 @@ public class AdminRESTController {
private UserService userService;
@PostMapping(value = "/post/re-encrypt", consumes = { "application/json" })
@ResponseBody
public ResponseEntity<ReencryptionDTO> reencryptMessages(@RequestBody @Valid List<ReencryptionDTO> reencryptionDTOs,
public ResponseEntity<ReencryptionDTO> reencryptMessages(
@RequestBody @Valid List<ReencryptionDTO> reencryptionDTOs,
Principal principal) {
if (reencryptionDTOs.size() > 0) {
chatService.reencryptMessages(reencryptionDTOs);
@ -44,16 +44,16 @@ public class AdminRESTController {
}
@GetMapping(value = "/get/messages/{userName}")
@ResponseBody
public List<ReencryptionDTO> sendAllMessages(@PathVariable String userName, Principal principal) {
List<ReencryptionDTO> reencryptionDTOs = chatService.getAllMessagesForReencryption(principal.getName(), userName);
public List<ReencryptionDTO> sendAllMessages(@PathVariable String userName,
Principal principal) {
List<ReencryptionDTO> reencryptionDTOs = chatService
.getAllMessagesForReencryption(principal.getName(), userName);
return reencryptionDTOs;
}
@GetMapping(value = "/get/messages/{userName}/{lastMessageTime}")
@ResponseBody
public List<ChatMessageDTO> sendNewMessages(@PathVariable String userName, @PathVariable String lastMessageTime,
Principal principal) {
public List<ChatMessageDTO> sendNewMessages(@PathVariable String userName,
@PathVariable String lastMessageTime, Principal principal) {
System.out.println("Last message time = " + lastMessageTime);
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
// date/time
@ -66,9 +66,11 @@ public class AdminRESTController {
.optionalStart().appendOffset("+HH", "Z").optionalEnd()
// create formatter
.toFormatter();
Date date = Date.from(OffsetDateTime.parse(lastMessageTime, formatter).toInstant());
Date date = Date.from(
OffsetDateTime.parse(lastMessageTime, formatter).toInstant());
List<ChatMessageDTO> chatMessageDTOs = chatService.getNewMessages(principal.getName(), userName, date);
List<ChatMessageDTO> chatMessageDTOs = chatService
.getNewMessages(principal.getName(), userName, date);
return chatMessageDTOs;
}
@ -78,11 +80,13 @@ public class AdminRESTController {
}
}
//public ResponseEntity<List<ChatMessage>> getMessages(@PathVariable String userName, Principal principal) {
////List<ChatMessage> chatMessages = chatMessageRepository.getAllMessages(principal.getName(), userName);
// public ResponseEntity<List<ChatMessage>> getMessages(@PathVariable String
// userName, Principal principal) {
//// List<ChatMessage> chatMessages =
// chatMessageRepository.getAllMessages(principal.getName(), userName);
//
//// return posts.stream()
//// .map(post -> convertToDto(post))
//// .collect(Collectors.toList());
//return new ResponseEntity<List<ChatMessage>>(chatMessages, HttpStatus.OK);
//}
// return new ResponseEntity<List<ChatMessage>>(chatMessages, HttpStatus.OK);
// }

View File

@ -2,6 +2,7 @@ package org.ros.chatto.controller;
import java.security.Principal;
import java.util.List;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -34,7 +35,7 @@ import org.springframework.web.servlet.ModelAndView;
@RestController
@RequestMapping("/api/demo")
//@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")
// @CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")
public class DemoRestController {
@Autowired
@ -51,6 +52,7 @@ public class DemoRestController {
ChatMessageRepository chatMessageRepository;
@Autowired
private UserService userService;
@GetMapping("/users")
public List<ChatUser> getAllUsers() {
return userRepository.findAll();
@ -62,13 +64,14 @@ public class DemoRestController {
}
@GetMapping("/user_old")
public ChatUser getUser() {
public Optional<ChatUser> getUser() {
return userRepository.findByUserName("hmm");
}
@GetMapping("/user")
public ChatUser currentUserName(Principal principal) {
ChatUser user = userRepository.findByUserName(principal.getName());
public Optional<ChatUser> currentUserName(Principal principal) {
Optional<ChatUser> user = userRepository
.findByUserName(principal.getName());
return user;
}
@ -93,7 +96,8 @@ public class DemoRestController {
}
@PostMapping(value = "/post-message", consumes = { "application/json" })
public ResponseEntity<MessageCipher> postMessage(@RequestBody MessageCipher messageCipher) {
public ResponseEntity<MessageCipher> postMessage(
@RequestBody MessageCipher messageCipher) {
System.out.println("Message cipher = " + messageCipher);
messageCipherRepository.save(messageCipher);
return new ResponseEntity<MessageCipher>(HttpStatus.OK);
@ -106,8 +110,10 @@ public class DemoRestController {
}
@RequestMapping(value = "perform_logout", method = RequestMethod.POST)
public String performLogout(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
public String performLogout(HttpServletRequest request,
HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
@ -115,8 +121,7 @@ public class DemoRestController {
}
@GetMapping(value = "/loggedUsers2")
public List<ActiveUserDTO> getOtherActiveUsers(Principal principal)
{
public List<ActiveUserDTO> getOtherActiveUsers(Principal principal) {
return userService.getOtherActiveUsers(principal.getName());
}
}

View File

@ -30,9 +30,10 @@ public class LoggedUser implements HttpSessionBindingListener {
log.debug("Incrementing session count for user {}", user.getUsername());
UserSession userSession = userService.incrementUserSession(user.getUsername());
userService.incrementUserSession(user.getUsername());
log.trace("Username = {} with sessions = {}", userSession.getUser(), userSession.getNumSessions());
// log.trace("Username = {} with sessions = {}", userSession.getUser(),
// userSession.getNumSessions());
}
@Override
@ -41,9 +42,11 @@ public class LoggedUser implements HttpSessionBindingListener {
log.debug("Decrementing session count for user {}", user.getUsername());
UserSession userSession = userService.decrementUserSession(user.getUsername());
UserSession userSession = userService
.decrementUserSession(user.getUsername());
log.trace("Username = {} with sessions = {}", userSession.getUser(), userSession.getNumSessions());
log.trace("Username = {} with sessions = {}", userSession.getUser(),
userSession.getNumSessions());
}
}

View File

@ -1,6 +1,7 @@
package org.ros.chatto.repository;
import java.util.List;
import java.util.Optional;
import org.ros.chatto.model.ChatUser;
import org.springframework.data.jpa.repository.JpaRepository;
@ -8,9 +9,9 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<ChatUser, Long>{
public interface UserRepository extends JpaRepository<ChatUser, Long> {
@Query("select cu from ChatUser cu where cu.userName = ?1")
public ChatUser findByUserName(String userName);
public Optional<ChatUser> findByUserName(String userName);
@Query("select cu from ChatUser cu join fetch cu.userRoles where cu.userName = ?1")
public ChatUser findByUserNameWithRole(String userName);

View File

@ -1,5 +1,8 @@
package org.ros.chatto.security;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ros.chatto.model.UserToken;
import org.ros.chatto.service.UserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
@ -19,24 +22,27 @@ public class CustomBasicAuthenticationFilter extends BasicAuthenticationFilter {
private UserTokenService userTokenService;
@Autowired
public CustomBasicAuthenticationFilter(final AuthenticationManager authenticationManager) {
public CustomBasicAuthenticationFilter(
final AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
protected void onSuccessfulAuthentication(final javax.servlet.http.HttpServletRequest request,
final javax.servlet.http.HttpServletResponse response, final Authentication authResult) {
protected void onSuccessfulAuthentication(final HttpServletRequest request,
final HttpServletResponse response,
final Authentication authResult) {
// Generate Token
// Save the token for the logged in user
// send token in the response
UserToken userToken = userTokenService.getTokenByUserName(authResult.getName());
Token token;
UserToken userToken = userTokenService
.getTokenByUserName(authResult.getName());
if (userToken == null) {
token = tokenService.allocateToken("");
final Token token = tokenService.allocateToken("");
userToken = new UserToken();
userToken.setTokenContent(token.getKey());
userToken.setUserName(authResult.getName());
userToken.setRole(authResult.getAuthorities().iterator().next().getAuthority());
userToken.setRole(authResult.getAuthorities().iterator().next()
.getAuthority());
userTokenService.saveToken(userToken);
response.setHeader("X-AUTH-TOKEN", token.getKey());
} else {

View File

@ -2,8 +2,10 @@ package org.ros.chatto.service;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.modelmapper.ModelMapper;
import org.ros.chatto.dto.ChatMessageDTO;
import org.ros.chatto.dto.MessageCipherDTO;
import org.ros.chatto.dto.ReencryptionDTO;
@ -24,6 +26,7 @@ import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {
private final ModelMapper modelMapper;
private final UserRepository userRepository;
private final MessageCipherRepository messageCipherRepository;
private final ChatMessageRepository chatMessageRepository;
@ -32,20 +35,25 @@ public class ChatServiceImpl implements ChatService {
public ChatMessageDTO createMessage(final String fromUserName,
final String toUserName, final MessageCipherDTO messageCipherDTO) {
final Optional<ChatUser> fromUser = userRepository
.findByUserName(fromUserName);
final Optional<ChatUser> toUser = userRepository
.findByUserName(toUserName);
final Optional<ChatMessage> cm = fromUser.flatMap(fu -> {
return toUser.map(tu -> {
ChatMessage chatMessage = new ChatMessage();
MessageCipher messageCipher = myConversionService
.convertToMessageCipher(messageCipherDTO);
final ChatUser fromUser = userRepository.findByUserName(fromUserName);
final ChatUser toUser = userRepository.findByUserName(toUserName);
ChatMessage chatMessage = new ChatMessage();
messageCipher = messageCipherRepository.save(messageCipher);
chatMessage.setMessageCipher(messageCipher);
chatMessage.setFromUser(fromUser);
chatMessage.setToUser(toUser);
chatMessage.setFromUser(fu);
chatMessage.setToUser(tu);
chatMessage = chatMessageRepository.save(chatMessage);
return myConversionService.convertToChatMessageDTO(chatMessage);
return chatMessage;
});
});
return modelMapper.map(cm, ChatMessageDTO.class);
}
@Override

View File

@ -1,6 +1,7 @@
package org.ros.chatto.service;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.ros.chatto.dto.ActiveUserDTO;
@ -18,7 +19,7 @@ public interface UserService {
public List<String> getAllRegularUsers();
public ChatUser getUser(String userName);
public Optional<ChatUser> getUser(String userName);
public Set<Role> getRoles(ChatUser user);
@ -26,7 +27,7 @@ public interface UserService {
public ChatUser getUserWithRole(String userName);
public UserSession incrementUserSession(String userName);
public void incrementUserSession(String userName);
public UserSession decrementUserSession(String userName);
}

View File

@ -6,6 +6,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@ -49,7 +50,8 @@ public class UserServiceImpl implements UserService {
public ChatUser createUser(final UserRegistrationDTO userRegistrationDTO) {
final ChatUser user = new ChatUser();
user.setUserName(userRegistrationDTO.getUserName());
user.setPassword(passwordEncoder.encode(userRegistrationDTO.getPassword()));
user.setPassword(
passwordEncoder.encode(userRegistrationDTO.getPassword()));
final ChatUser changedUser = userRepository.save(user);
final UserRole userRole = new UserRole();
final Role role = roleRepository.findByName("USER");
@ -74,8 +76,10 @@ public class UserServiceImpl implements UserService {
public List<ActiveUserDTO> getOtherActiveUsers(final String userName) {
final List<String> userList = findAllOtherUsers(userName);
final List<UserSession> userSessionsList = userSessionRepository.findAllUserSessions();
final Map<String, UserSession> lastActiveMap = convertToMap(userSessionsList);
final List<UserSession> userSessionsList = userSessionRepository
.findAllUserSessions();
final Map<String, UserSession> lastActiveMap = convertToMap(
userSessionsList);
final List<ActiveUserDTO> activeUserDTOs = new ArrayList<ActiveUserDTO>();
userList.forEach(u -> {
@ -98,11 +102,12 @@ public class UserServiceImpl implements UserService {
@Transactional(readOnly = true)
@Override
public ChatUser getUser(final String userName) {
public Optional<ChatUser> getUser(final String userName) {
return userRepository.findByUserName(userName);
}
private Map<String, UserSession> convertToMap(final List<UserSession> userSessionList) {
private Map<String, UserSession> convertToMap(
final List<UserSession> userSessionList) {
final Map<String, UserSession> userMap = new HashMap<>();
userSessionList.forEach(us -> {
userMap.put(us.getUser().getUserName(), us);
@ -117,34 +122,21 @@ public class UserServiceImpl implements UserService {
final long hours = duration.toHours();
final long minutes = duration.toMinutes();
final long days = duration.toDays();
// @formatter:off
if(minutes < 60)
{
if (minutes < 60) {
return String.format("%d minutes ago", minutes);
}
else
{
if(hours < 24)
{
} else {
if (hours < 24) {
return String.format("%d hours ago", hours);
}
else
{
if(days < 30)
{
} else {
if (days < 30) {
return String.format("%d days ago", days);
}
else if(days < 366)
{
return String.format("%d months ago", days/30);
}
else {
return String.format("%d years ago", days/365);
} else if (days < 366) {
return String.format("%d months ago", days / 30);
} else {
return String.format("%d years ago", days / 365);
}
}
}
// @formatter:on
}
@Override
@ -154,40 +146,45 @@ public class UserServiceImpl implements UserService {
}
@Override
public UserSession incrementUserSession(String userName) {
ChatUser chatUser = getUser(userName);
Instant instant = Instant.now();
public void incrementUserSession(final String userName) {
final Optional<ChatUser> chatUser = getUser(userName);
final Instant instant = Instant.now();
UserSession userSession = userSessionRepository.findByUserName(userName);
chatUser.ifPresent(cu -> {
UserSession userSession = userSessionRepository
.findByUserName(userName);
if (userSession == null) {
userSession = new UserSession();
}
userSession.setUser(chatUser);
userSession.setUser(cu);
userSession.setTimeStamp(instant);
userSession.setOnline(true);
userSession.setNumSessions(userSession.getNumSessions() + 1);
return userSessionRepository.save(userSession);
userSessionRepository.save(userSession);
});
}
@Override
public UserSession decrementUserSession(String userName) {
UserSession userSession = userSessionRepository.findByUserName(userName);
Instant instant = Instant.now();
public UserSession decrementUserSession(final String userName) {
final UserSession userSession = userSessionRepository
.findByUserName(userName);
final Instant instant = Instant.now();
if (userSession == null) {
log.error("User session is somehow null for user: " + userName);
throw new InternalAuthenticationServiceException("User session not found");
throw new InternalAuthenticationServiceException(
"User session not found");
}
ChatUser chatUser = userSession.getUser();
final ChatUser chatUser = userSession.getUser();
int numSessions = userSession.getNumSessions();
if (--numSessions == 0) {
log.info("Num sessions is 0 so setting user to offline");
log.info("Deleting token and evicting cache for user: " + chatUser.getUserName());
log.info("Deleting token and evicting cache for user: "
+ chatUser.getUserName());
userSession.setOnline(false);
userTokenService.deleteToken(chatUser.getUserName());
TokenCacheUtil.evictSingleTokenValue(chatUser.getUserName());
@ -199,7 +196,8 @@ public class UserServiceImpl implements UserService {
}
@Override
public Set<Role> getRoles(ChatUser user) {
return user.getUserRoles().stream().map(ur -> ur.getRole()).collect(Collectors.toSet());
public Set<Role> getRoles(final ChatUser user) {
return user.getUserRoles().stream().map(ur -> ur.getRole())
.collect(Collectors.toSet());
}
}

View File

@ -8,15 +8,16 @@ import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Service
@Transactional
@Slf4j
@CacheConfig(cacheNames = "userTokenCache")
@RequiredArgsConstructor
public class UserTokenService {
@Autowired
private TokenRepository tokenRepository;
private final TokenRepository tokenRepository;
@Transactional(readOnly = true)
@Cacheable(value = "userTokenCache", key = "#userName", unless = "#result == null")

View File

@ -1,8 +1,7 @@
export namespace JsonAPI {
// @ts-ignore: Cannot find name 'hostAddress'.
export let principleName: string | null = localStorage.getItem('username');
export let contactName: string | null;
export let authToken: string | null = localStorage.getItem('authToken');
export let principleName: string = localStorage.getItem("username") || "";
export let contactName: string = "";
export let authToken: string = localStorage.getItem("authToken") || "";
export const ACTIVE_USERS_GET = `/api/chat/get/active-users`;
/**
* Json API URL for retrieving all messages between two users
@ -18,7 +17,7 @@ export namespace JsonAPI {
* The user whose messages we wish to retrieve.
*/
export const CHAT_MESSAGES_GET = `/api/chat/get/messages/%s`;
export const MESSAGE_POST = '/api/chat/post/message';
export const MESSAGE_POST = "/api/chat/post/message";
/**
* Json API URL for retrieving paginated messages between two users
* Page index starts with 0
@ -35,5 +34,4 @@ export namespace JsonAPI {
* @param size denotes the size of each page
*/
export const CHAT_MESSAGE_PAGE_GET = `/api/chat/get/messages/%s?page=%d&size=%d`;
}

View File

@ -1,8 +1,6 @@
export class ChatMessageViewModel {
public toUser: string | undefined;
public fromUser: string | undefined;
public message!: string;
public messageTime!: Date;
public toUser: string = "";
public fromUser: string = "";
public message: string = "";
public messageTime: Date = new Date();
}

View File

@ -1,23 +1,7 @@
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/chatto_db?useSSL=false
spring.datasource.username = chatto_user
spring.datasource.password = password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = validate
logging.level.org.springframework.web=DEBUG
logging.level.web=DEBUG
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
spring.http.log-request-details=true
#spring.jackson.date-format=yyyy-MM-d
spring.jackson.serialization.write-dates-as-timestamps=false
#spring.mvc.static-path-pattern=/static/**
## chatto DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
chatto.datasource.url = jdbc:mysql://localhost:3306/chatto_db2?useSSL=false
chatto.datasource.username = chatto_user
chatto.datasource.password = password
chatto.datasource.database-name = chatto_db2
website-url = 192.168.1.13
test.bindAddress=192.168.1.106