Test using Optional in repository
Trying out fetching values from repository as Optional. Plus set line length to 80
This commit is contained in:
parent
4c64dfd2b1
commit
5978eaebaa
7
chatto/application.properties
Normal file
7
chatto/application.properties
Normal 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
|
@ -34,8 +34,8 @@ public class AdminRESTController {
|
|||||||
private UserService userService;
|
private UserService userService;
|
||||||
|
|
||||||
@PostMapping(value = "/post/re-encrypt", consumes = { "application/json" })
|
@PostMapping(value = "/post/re-encrypt", consumes = { "application/json" })
|
||||||
@ResponseBody
|
public ResponseEntity<ReencryptionDTO> reencryptMessages(
|
||||||
public ResponseEntity<ReencryptionDTO> reencryptMessages(@RequestBody @Valid List<ReencryptionDTO> reencryptionDTOs,
|
@RequestBody @Valid List<ReencryptionDTO> reencryptionDTOs,
|
||||||
Principal principal) {
|
Principal principal) {
|
||||||
if (reencryptionDTOs.size() > 0) {
|
if (reencryptionDTOs.size() > 0) {
|
||||||
chatService.reencryptMessages(reencryptionDTOs);
|
chatService.reencryptMessages(reencryptionDTOs);
|
||||||
@ -44,16 +44,16 @@ public class AdminRESTController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping(value = "/get/messages/{userName}")
|
@GetMapping(value = "/get/messages/{userName}")
|
||||||
@ResponseBody
|
public List<ReencryptionDTO> sendAllMessages(@PathVariable String userName,
|
||||||
public List<ReencryptionDTO> sendAllMessages(@PathVariable String userName, Principal principal) {
|
Principal principal) {
|
||||||
List<ReencryptionDTO> reencryptionDTOs = chatService.getAllMessagesForReencryption(principal.getName(), userName);
|
List<ReencryptionDTO> reencryptionDTOs = chatService
|
||||||
|
.getAllMessagesForReencryption(principal.getName(), userName);
|
||||||
return reencryptionDTOs;
|
return reencryptionDTOs;
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping(value = "/get/messages/{userName}/{lastMessageTime}")
|
@GetMapping(value = "/get/messages/{userName}/{lastMessageTime}")
|
||||||
@ResponseBody
|
public List<ChatMessageDTO> sendNewMessages(@PathVariable String userName,
|
||||||
public List<ChatMessageDTO> sendNewMessages(@PathVariable String userName, @PathVariable String lastMessageTime,
|
@PathVariable String lastMessageTime, Principal principal) {
|
||||||
Principal principal) {
|
|
||||||
System.out.println("Last message time = " + lastMessageTime);
|
System.out.println("Last message time = " + lastMessageTime);
|
||||||
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
|
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
|
||||||
// date/time
|
// date/time
|
||||||
@ -66,9 +66,11 @@ public class AdminRESTController {
|
|||||||
.optionalStart().appendOffset("+HH", "Z").optionalEnd()
|
.optionalStart().appendOffset("+HH", "Z").optionalEnd()
|
||||||
// create formatter
|
// create formatter
|
||||||
.toFormatter();
|
.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;
|
return chatMessageDTOs;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -78,11 +80,13 @@ public class AdminRESTController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//public ResponseEntity<List<ChatMessage>> getMessages(@PathVariable String userName, Principal principal) {
|
// public ResponseEntity<List<ChatMessage>> getMessages(@PathVariable String
|
||||||
////List<ChatMessage> chatMessages = chatMessageRepository.getAllMessages(principal.getName(), userName);
|
// userName, Principal principal) {
|
||||||
|
//// List<ChatMessage> chatMessages =
|
||||||
|
// chatMessageRepository.getAllMessages(principal.getName(), userName);
|
||||||
//
|
//
|
||||||
//// return posts.stream()
|
//// return posts.stream()
|
||||||
//// .map(post -> convertToDto(post))
|
//// .map(post -> convertToDto(post))
|
||||||
//// .collect(Collectors.toList());
|
//// .collect(Collectors.toList());
|
||||||
//return new ResponseEntity<List<ChatMessage>>(chatMessages, HttpStatus.OK);
|
// return new ResponseEntity<List<ChatMessage>>(chatMessages, HttpStatus.OK);
|
||||||
//}
|
// }
|
||||||
|
@ -2,6 +2,7 @@ package org.ros.chatto.controller;
|
|||||||
|
|
||||||
import java.security.Principal;
|
import java.security.Principal;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
import javax.servlet.http.HttpServletRequest;
|
||||||
import javax.servlet.http.HttpServletResponse;
|
import javax.servlet.http.HttpServletResponse;
|
||||||
@ -34,7 +35,7 @@ import org.springframework.web.servlet.ModelAndView;
|
|||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/demo")
|
@RequestMapping("/api/demo")
|
||||||
//@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")
|
// @CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")
|
||||||
public class DemoRestController {
|
public class DemoRestController {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@ -51,6 +52,7 @@ public class DemoRestController {
|
|||||||
ChatMessageRepository chatMessageRepository;
|
ChatMessageRepository chatMessageRepository;
|
||||||
@Autowired
|
@Autowired
|
||||||
private UserService userService;
|
private UserService userService;
|
||||||
|
|
||||||
@GetMapping("/users")
|
@GetMapping("/users")
|
||||||
public List<ChatUser> getAllUsers() {
|
public List<ChatUser> getAllUsers() {
|
||||||
return userRepository.findAll();
|
return userRepository.findAll();
|
||||||
@ -62,13 +64,14 @@ public class DemoRestController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/user_old")
|
@GetMapping("/user_old")
|
||||||
public ChatUser getUser() {
|
public Optional<ChatUser> getUser() {
|
||||||
return userRepository.findByUserName("hmm");
|
return userRepository.findByUserName("hmm");
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/user")
|
@GetMapping("/user")
|
||||||
public ChatUser currentUserName(Principal principal) {
|
public Optional<ChatUser> currentUserName(Principal principal) {
|
||||||
ChatUser user = userRepository.findByUserName(principal.getName());
|
Optional<ChatUser> user = userRepository
|
||||||
|
.findByUserName(principal.getName());
|
||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -86,14 +89,15 @@ public class DemoRestController {
|
|||||||
public List<ChatMessage> getAllMessages() {
|
public List<ChatMessage> getAllMessages() {
|
||||||
return chatMessageRepository.findAll();
|
return chatMessageRepository.findAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/regular-users")
|
@GetMapping("/regular-users")
|
||||||
public List<String> getAllRegularUsers() {
|
public List<String> getAllRegularUsers() {
|
||||||
return userRoleRepository.getAllRegularUser();
|
return userRoleRepository.getAllRegularUser();
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping(value = "/post-message", consumes = { "application/json" })
|
@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);
|
System.out.println("Message cipher = " + messageCipher);
|
||||||
messageCipherRepository.save(messageCipher);
|
messageCipherRepository.save(messageCipher);
|
||||||
return new ResponseEntity<MessageCipher>(HttpStatus.OK);
|
return new ResponseEntity<MessageCipher>(HttpStatus.OK);
|
||||||
@ -106,17 +110,18 @@ public class DemoRestController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@RequestMapping(value = "perform_logout", method = RequestMethod.POST)
|
@RequestMapping(value = "perform_logout", method = RequestMethod.POST)
|
||||||
public String performLogout(HttpServletRequest request, HttpServletResponse response) {
|
public String performLogout(HttpServletRequest request,
|
||||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
HttpServletResponse response) {
|
||||||
|
Authentication auth = SecurityContextHolder.getContext()
|
||||||
|
.getAuthentication();
|
||||||
if (auth != null) {
|
if (auth != null) {
|
||||||
new SecurityContextLogoutHandler().logout(request, response, auth);
|
new SecurityContextLogoutHandler().logout(request, response, auth);
|
||||||
}
|
}
|
||||||
return "redirect:/users";
|
return "redirect:/users";
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping(value = "/loggedUsers2")
|
@GetMapping(value = "/loggedUsers2")
|
||||||
public List<ActiveUserDTO> getOtherActiveUsers(Principal principal)
|
public List<ActiveUserDTO> getOtherActiveUsers(Principal principal) {
|
||||||
{
|
|
||||||
return userService.getOtherActiveUsers(principal.getName());
|
return userService.getOtherActiveUsers(principal.getName());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -30,9 +30,10 @@ public class LoggedUser implements HttpSessionBindingListener {
|
|||||||
|
|
||||||
log.debug("Incrementing session count for user {}", user.getUsername());
|
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
|
@Override
|
||||||
@ -41,9 +42,11 @@ public class LoggedUser implements HttpSessionBindingListener {
|
|||||||
|
|
||||||
log.debug("Decrementing session count for user {}", user.getUsername());
|
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());
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,6 +1,7 @@
|
|||||||
package org.ros.chatto.repository;
|
package org.ros.chatto.repository;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
import org.ros.chatto.model.ChatUser;
|
import org.ros.chatto.model.ChatUser;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
@ -8,13 +9,13 @@ import org.springframework.data.jpa.repository.Query;
|
|||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
@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")
|
@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")
|
@Query("select cu from ChatUser cu join fetch cu.userRoles where cu.userName = ?1")
|
||||||
public ChatUser findByUserNameWithRole(String userName);
|
public ChatUser findByUserNameWithRole(String userName);
|
||||||
|
|
||||||
@Query("select cu.userName from ChatUser cu where cu.userName != ?1")
|
@Query("select cu.userName from ChatUser cu where cu.userName != ?1")
|
||||||
public List<String> findAllOtherUserNames(String userName);
|
public List<String> findAllOtherUserNames(String userName);
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,8 @@
|
|||||||
package org.ros.chatto.security;
|
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.model.UserToken;
|
||||||
import org.ros.chatto.service.UserTokenService;
|
import org.ros.chatto.service.UserTokenService;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
@ -19,24 +22,27 @@ public class CustomBasicAuthenticationFilter extends BasicAuthenticationFilter {
|
|||||||
private UserTokenService userTokenService;
|
private UserTokenService userTokenService;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public CustomBasicAuthenticationFilter(final AuthenticationManager authenticationManager) {
|
public CustomBasicAuthenticationFilter(
|
||||||
|
final AuthenticationManager authenticationManager) {
|
||||||
super(authenticationManager);
|
super(authenticationManager);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
protected void onSuccessfulAuthentication(final javax.servlet.http.HttpServletRequest request,
|
protected void onSuccessfulAuthentication(final HttpServletRequest request,
|
||||||
final javax.servlet.http.HttpServletResponse response, final Authentication authResult) {
|
final HttpServletResponse response,
|
||||||
|
final Authentication authResult) {
|
||||||
// Generate Token
|
// Generate Token
|
||||||
// Save the token for the logged in user
|
// Save the token for the logged in user
|
||||||
// send token in the response
|
// send token in the response
|
||||||
UserToken userToken = userTokenService.getTokenByUserName(authResult.getName());
|
UserToken userToken = userTokenService
|
||||||
Token token;
|
.getTokenByUserName(authResult.getName());
|
||||||
if (userToken == null) {
|
if (userToken == null) {
|
||||||
token = tokenService.allocateToken("");
|
final Token token = tokenService.allocateToken("");
|
||||||
userToken = new UserToken();
|
userToken = new UserToken();
|
||||||
userToken.setTokenContent(token.getKey());
|
userToken.setTokenContent(token.getKey());
|
||||||
userToken.setUserName(authResult.getName());
|
userToken.setUserName(authResult.getName());
|
||||||
userToken.setRole(authResult.getAuthorities().iterator().next().getAuthority());
|
userToken.setRole(authResult.getAuthorities().iterator().next()
|
||||||
|
.getAuthority());
|
||||||
userTokenService.saveToken(userToken);
|
userTokenService.saveToken(userToken);
|
||||||
response.setHeader("X-AUTH-TOKEN", token.getKey());
|
response.setHeader("X-AUTH-TOKEN", token.getKey());
|
||||||
} else {
|
} else {
|
||||||
|
@ -2,8 +2,10 @@ package org.ros.chatto.service;
|
|||||||
|
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import org.modelmapper.ModelMapper;
|
||||||
import org.ros.chatto.dto.ChatMessageDTO;
|
import org.ros.chatto.dto.ChatMessageDTO;
|
||||||
import org.ros.chatto.dto.MessageCipherDTO;
|
import org.ros.chatto.dto.MessageCipherDTO;
|
||||||
import org.ros.chatto.dto.ReencryptionDTO;
|
import org.ros.chatto.dto.ReencryptionDTO;
|
||||||
@ -24,6 +26,7 @@ import lombok.RequiredArgsConstructor;
|
|||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class ChatServiceImpl implements ChatService {
|
public class ChatServiceImpl implements ChatService {
|
||||||
|
|
||||||
|
private final ModelMapper modelMapper;
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
private final MessageCipherRepository messageCipherRepository;
|
private final MessageCipherRepository messageCipherRepository;
|
||||||
private final ChatMessageRepository chatMessageRepository;
|
private final ChatMessageRepository chatMessageRepository;
|
||||||
@ -32,20 +35,25 @@ public class ChatServiceImpl implements ChatService {
|
|||||||
public ChatMessageDTO createMessage(final String fromUserName,
|
public ChatMessageDTO createMessage(final String fromUserName,
|
||||||
final String toUserName, final MessageCipherDTO messageCipherDTO) {
|
final String toUserName, final MessageCipherDTO messageCipherDTO) {
|
||||||
|
|
||||||
MessageCipher messageCipher = myConversionService
|
final Optional<ChatUser> fromUser = userRepository
|
||||||
.convertToMessageCipher(messageCipherDTO);
|
.findByUserName(fromUserName);
|
||||||
final ChatUser fromUser = userRepository.findByUserName(fromUserName);
|
final Optional<ChatUser> toUser = userRepository
|
||||||
final ChatUser toUser = userRepository.findByUserName(toUserName);
|
.findByUserName(toUserName);
|
||||||
|
|
||||||
ChatMessage chatMessage = new ChatMessage();
|
|
||||||
messageCipher = messageCipherRepository.save(messageCipher);
|
|
||||||
chatMessage.setMessageCipher(messageCipher);
|
|
||||||
chatMessage.setFromUser(fromUser);
|
|
||||||
chatMessage.setToUser(toUser);
|
|
||||||
|
|
||||||
chatMessage = chatMessageRepository.save(chatMessage);
|
|
||||||
return myConversionService.convertToChatMessageDTO(chatMessage);
|
|
||||||
|
|
||||||
|
final Optional<ChatMessage> cm = fromUser.flatMap(fu -> {
|
||||||
|
return toUser.map(tu -> {
|
||||||
|
ChatMessage chatMessage = new ChatMessage();
|
||||||
|
MessageCipher messageCipher = myConversionService
|
||||||
|
.convertToMessageCipher(messageCipherDTO);
|
||||||
|
messageCipher = messageCipherRepository.save(messageCipher);
|
||||||
|
chatMessage.setMessageCipher(messageCipher);
|
||||||
|
chatMessage.setFromUser(fu);
|
||||||
|
chatMessage.setToUser(tu);
|
||||||
|
chatMessage = chatMessageRepository.save(chatMessage);
|
||||||
|
return chatMessage;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return modelMapper.map(cm, ChatMessageDTO.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
package org.ros.chatto.service;
|
package org.ros.chatto.service;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import org.ros.chatto.dto.ActiveUserDTO;
|
import org.ros.chatto.dto.ActiveUserDTO;
|
||||||
@ -18,7 +19,7 @@ public interface UserService {
|
|||||||
|
|
||||||
public List<String> getAllRegularUsers();
|
public List<String> getAllRegularUsers();
|
||||||
|
|
||||||
public ChatUser getUser(String userName);
|
public Optional<ChatUser> getUser(String userName);
|
||||||
|
|
||||||
public Set<Role> getRoles(ChatUser user);
|
public Set<Role> getRoles(ChatUser user);
|
||||||
|
|
||||||
@ -26,7 +27,7 @@ public interface UserService {
|
|||||||
|
|
||||||
public ChatUser getUserWithRole(String userName);
|
public ChatUser getUserWithRole(String userName);
|
||||||
|
|
||||||
public UserSession incrementUserSession(String userName);
|
public void incrementUserSession(String userName);
|
||||||
|
|
||||||
public UserSession decrementUserSession(String userName);
|
public UserSession decrementUserSession(String userName);
|
||||||
}
|
}
|
||||||
|
@ -6,6 +6,7 @@ import java.util.ArrayList;
|
|||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@ -49,7 +50,8 @@ public class UserServiceImpl implements UserService {
|
|||||||
public ChatUser createUser(final UserRegistrationDTO userRegistrationDTO) {
|
public ChatUser createUser(final UserRegistrationDTO userRegistrationDTO) {
|
||||||
final ChatUser user = new ChatUser();
|
final ChatUser user = new ChatUser();
|
||||||
user.setUserName(userRegistrationDTO.getUserName());
|
user.setUserName(userRegistrationDTO.getUserName());
|
||||||
user.setPassword(passwordEncoder.encode(userRegistrationDTO.getPassword()));
|
user.setPassword(
|
||||||
|
passwordEncoder.encode(userRegistrationDTO.getPassword()));
|
||||||
final ChatUser changedUser = userRepository.save(user);
|
final ChatUser changedUser = userRepository.save(user);
|
||||||
final UserRole userRole = new UserRole();
|
final UserRole userRole = new UserRole();
|
||||||
final Role role = roleRepository.findByName("USER");
|
final Role role = roleRepository.findByName("USER");
|
||||||
@ -74,8 +76,10 @@ public class UserServiceImpl implements UserService {
|
|||||||
public List<ActiveUserDTO> getOtherActiveUsers(final String userName) {
|
public List<ActiveUserDTO> getOtherActiveUsers(final String userName) {
|
||||||
final List<String> userList = findAllOtherUsers(userName);
|
final List<String> userList = findAllOtherUsers(userName);
|
||||||
|
|
||||||
final List<UserSession> userSessionsList = userSessionRepository.findAllUserSessions();
|
final List<UserSession> userSessionsList = userSessionRepository
|
||||||
final Map<String, UserSession> lastActiveMap = convertToMap(userSessionsList);
|
.findAllUserSessions();
|
||||||
|
final Map<String, UserSession> lastActiveMap = convertToMap(
|
||||||
|
userSessionsList);
|
||||||
|
|
||||||
final List<ActiveUserDTO> activeUserDTOs = new ArrayList<ActiveUserDTO>();
|
final List<ActiveUserDTO> activeUserDTOs = new ArrayList<ActiveUserDTO>();
|
||||||
userList.forEach(u -> {
|
userList.forEach(u -> {
|
||||||
@ -98,11 +102,12 @@ public class UserServiceImpl implements UserService {
|
|||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
@Override
|
@Override
|
||||||
public ChatUser getUser(final String userName) {
|
public Optional<ChatUser> getUser(final String userName) {
|
||||||
return userRepository.findByUserName(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<>();
|
final Map<String, UserSession> userMap = new HashMap<>();
|
||||||
userSessionList.forEach(us -> {
|
userSessionList.forEach(us -> {
|
||||||
userMap.put(us.getUser().getUserName(), us);
|
userMap.put(us.getUser().getUserName(), us);
|
||||||
@ -117,34 +122,21 @@ public class UserServiceImpl implements UserService {
|
|||||||
final long hours = duration.toHours();
|
final long hours = duration.toHours();
|
||||||
final long minutes = duration.toMinutes();
|
final long minutes = duration.toMinutes();
|
||||||
final long days = duration.toDays();
|
final long days = duration.toDays();
|
||||||
// @formatter:off
|
if (minutes < 60) {
|
||||||
if(minutes < 60)
|
|
||||||
{
|
|
||||||
return String.format("%d minutes ago", minutes);
|
return String.format("%d minutes ago", minutes);
|
||||||
}
|
} else {
|
||||||
else
|
if (hours < 24) {
|
||||||
{
|
|
||||||
if(hours < 24)
|
|
||||||
{
|
|
||||||
return String.format("%d hours ago", hours);
|
return String.format("%d hours ago", hours);
|
||||||
}
|
} else {
|
||||||
else
|
if (days < 30) {
|
||||||
{
|
|
||||||
if(days < 30)
|
|
||||||
{
|
|
||||||
return String.format("%d days ago", days);
|
return String.format("%d days ago", days);
|
||||||
}
|
} else if (days < 366) {
|
||||||
else if(days < 366)
|
return String.format("%d months ago", days / 30);
|
||||||
{
|
} else {
|
||||||
return String.format("%d months ago", days/30);
|
return String.format("%d years ago", days / 365);
|
||||||
}
|
|
||||||
else {
|
|
||||||
return String.format("%d years ago", days/365);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// @formatter:on
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -154,40 +146,45 @@ public class UserServiceImpl implements UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public UserSession incrementUserSession(String userName) {
|
public void incrementUserSession(final String userName) {
|
||||||
ChatUser chatUser = getUser(userName);
|
final Optional<ChatUser> chatUser = getUser(userName);
|
||||||
Instant instant = Instant.now();
|
final Instant instant = Instant.now();
|
||||||
|
|
||||||
UserSession userSession = userSessionRepository.findByUserName(userName);
|
chatUser.ifPresent(cu -> {
|
||||||
|
UserSession userSession = userSessionRepository
|
||||||
|
.findByUserName(userName);
|
||||||
|
|
||||||
if (userSession == null) {
|
if (userSession == null) {
|
||||||
userSession = new UserSession();
|
userSession = new UserSession();
|
||||||
}
|
}
|
||||||
|
userSession.setUser(cu);
|
||||||
userSession.setUser(chatUser);
|
userSession.setTimeStamp(instant);
|
||||||
userSession.setTimeStamp(instant);
|
userSession.setOnline(true);
|
||||||
userSession.setOnline(true);
|
userSession.setNumSessions(userSession.getNumSessions() + 1);
|
||||||
userSession.setNumSessions(userSession.getNumSessions() + 1);
|
userSessionRepository.save(userSession);
|
||||||
return userSessionRepository.save(userSession);
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public UserSession decrementUserSession(String userName) {
|
public UserSession decrementUserSession(final String userName) {
|
||||||
UserSession userSession = userSessionRepository.findByUserName(userName);
|
final UserSession userSession = userSessionRepository
|
||||||
Instant instant = Instant.now();
|
.findByUserName(userName);
|
||||||
|
final Instant instant = Instant.now();
|
||||||
|
|
||||||
if (userSession == null) {
|
if (userSession == null) {
|
||||||
log.error("User session is somehow null for user: " + userName);
|
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();
|
int numSessions = userSession.getNumSessions();
|
||||||
|
|
||||||
if (--numSessions == 0) {
|
if (--numSessions == 0) {
|
||||||
log.info("Num sessions is 0 so setting user to offline");
|
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);
|
userSession.setOnline(false);
|
||||||
userTokenService.deleteToken(chatUser.getUserName());
|
userTokenService.deleteToken(chatUser.getUserName());
|
||||||
TokenCacheUtil.evictSingleTokenValue(chatUser.getUserName());
|
TokenCacheUtil.evictSingleTokenValue(chatUser.getUserName());
|
||||||
@ -199,7 +196,8 @@ public class UserServiceImpl implements UserService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Set<Role> getRoles(ChatUser user) {
|
public Set<Role> getRoles(final ChatUser user) {
|
||||||
return user.getUserRoles().stream().map(ur -> ur.getRole()).collect(Collectors.toSet());
|
return user.getUserRoles().stream().map(ur -> ur.getRole())
|
||||||
|
.collect(Collectors.toSet());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,15 +8,16 @@ import org.springframework.cache.annotation.Cacheable;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Transactional
|
@Transactional
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@CacheConfig(cacheNames = "userTokenCache")
|
@CacheConfig(cacheNames = "userTokenCache")
|
||||||
|
@RequiredArgsConstructor
|
||||||
public class UserTokenService {
|
public class UserTokenService {
|
||||||
@Autowired
|
private final TokenRepository tokenRepository;
|
||||||
private TokenRepository tokenRepository;
|
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
@Cacheable(value = "userTokenCache", key = "#userName", unless = "#result == null")
|
@Cacheable(value = "userTokenCache", key = "#userName", unless = "#result == null")
|
||||||
|
@ -1,39 +1,37 @@
|
|||||||
export namespace JsonAPI {
|
export namespace JsonAPI {
|
||||||
// @ts-ignore: Cannot find name 'hostAddress'.
|
export let principleName: string = localStorage.getItem("username") || "";
|
||||||
export let principleName: string | null = localStorage.getItem('username');
|
export let contactName: string = "";
|
||||||
export let contactName: string | null;
|
export let authToken: string = localStorage.getItem("authToken") || "";
|
||||||
export let authToken: string | null = localStorage.getItem('authToken');
|
export const ACTIVE_USERS_GET = `/api/chat/get/active-users`;
|
||||||
export const ACTIVE_USERS_GET = `/api/chat/get/active-users`;
|
/**
|
||||||
/**
|
* Json API URL for retrieving all messages between two users
|
||||||
* Json API URL for retrieving all messages between two users
|
*
|
||||||
*
|
* ### With sprintf
|
||||||
* ### With sprintf
|
* const url = Sprintf(JsonAPI.CHAT_MESSAGES_GET, contactName);
|
||||||
* const url = Sprintf(JsonAPI.CHAT_MESSAGES_GET, contactName);
|
*
|
||||||
*
|
* @format /api/chat/get/messages/{contactName}
|
||||||
* @format /api/chat/get/messages/{contactName}
|
* @example /api/chat/get/messages/some-user
|
||||||
* @example /api/chat/get/messages/some-user
|
*
|
||||||
*
|
*
|
||||||
*
|
* @param contactName
|
||||||
* @param contactName
|
* The user whose messages we wish to retrieve.
|
||||||
* The user whose messages we wish to retrieve.
|
*/
|
||||||
*/
|
export const CHAT_MESSAGES_GET = `/api/chat/get/messages/%s`;
|
||||||
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
|
||||||
* Json API URL for retrieving paginated messages between two users
|
* Page index starts with 0
|
||||||
* Page index starts with 0
|
*
|
||||||
*
|
* ### With sprintf
|
||||||
* ### With sprintf
|
* const url = Sprintf(JsonAPI.CHAT_MESSAGES_GET, contactName);
|
||||||
* const url = Sprintf(JsonAPI.CHAT_MESSAGES_GET, contactName);
|
*
|
||||||
*
|
* @example /api/chat/get/messages/some-user?page=0&size=5 will give the first page where each page has size 5
|
||||||
* @example /api/chat/get/messages/some-user?page=0&size=5 will give the first page where each page has size 5
|
*
|
||||||
*
|
*
|
||||||
*
|
*
|
||||||
*
|
* @param contactName the user whose messages we wish to retrieve
|
||||||
* @param contactName the user whose messages we wish to retrieve
|
* @param page denotes the page required
|
||||||
* @param page denotes the page required
|
* @param size denotes the size of each page
|
||||||
* @param size denotes the size of each page
|
*/
|
||||||
*/
|
export const CHAT_MESSAGE_PAGE_GET = `/api/chat/get/messages/%s?page=%d&size=%d`;
|
||||||
export const CHAT_MESSAGE_PAGE_GET = `/api/chat/get/messages/%s?page=%d&size=%d`;
|
}
|
||||||
|
|
||||||
}
|
|
||||||
|
@ -1,8 +1,6 @@
|
|||||||
export class ChatMessageViewModel {
|
export class ChatMessageViewModel {
|
||||||
public toUser: string | undefined;
|
public toUser: string = "";
|
||||||
public fromUser: string | undefined;
|
public fromUser: string = "";
|
||||||
public message!: string;
|
public message: string = "";
|
||||||
public messageTime!: Date;
|
public messageTime: Date = new Date();
|
||||||
|
}
|
||||||
|
|
||||||
}
|
|
||||||
|
@ -1,23 +1,7 @@
|
|||||||
|
## chatto DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
|
||||||
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
|
chatto.datasource.url = jdbc:mysql://localhost:3306/chatto_db2?useSSL=false
|
||||||
spring.datasource.url = jdbc:mysql://localhost:3306/chatto_db?useSSL=false
|
chatto.datasource.username = chatto_user
|
||||||
spring.datasource.username = chatto_user
|
chatto.datasource.password = password
|
||||||
spring.datasource.password = password
|
chatto.datasource.database-name = chatto_db2
|
||||||
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
|
website-url = 192.168.1.13
|
||||||
|
test.bindAddress=192.168.1.106
|
||||||
## 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/**
|
|
||||||
|
Loading…
Reference in New Issue
Block a user