Made optimizations to service and repo layers

-disabled open session in view
-added transactional to service classes and transactional read only
where necessary
-changed chatmessage query a bit
This commit is contained in:
Rohan Sircar 2019-11-28 11:08:50 +05:30
parent 49f765737e
commit 62a7e192e6
10 changed files with 62 additions and 65 deletions

View File

@ -67,18 +67,18 @@ public class ChatMessageController {
* @return a {@code ErrorResponse} * @return a {@code ErrorResponse}
* @see com.aroussi.util.validation.ErrorResponse * @see com.aroussi.util.validation.ErrorResponse
*/ */
@ExceptionHandler(value = MethodArgumentNotValidException.class) // @ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST) // @ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleException(MethodArgumentNotValidException exception) { // public ErrorResponse handleException(MethodArgumentNotValidException exception) {
//
List<ErrorModel> errorMessages = exception.getBindingResult().getFieldErrors().stream() // List<ErrorModel> errorMessages = exception.getBindingResult().getFieldErrors().stream()
.map(err -> new ErrorModel(err.getField(), err.getRejectedValue(), err.getDefaultMessage())).distinct() // .map(err -> new ErrorModel(err.getField(), err.getRejectedValue(), err.getDefaultMessage())).distinct()
.collect(Collectors.toList()); // .collect(Collectors.toList());
return ErrorResponse.builder().errorMessage(errorMessages).build(); // return ErrorResponse.builder().errorMessage(errorMessages).build();
} // }
//
@ExceptionHandler(value = MethodArgumentNotValidException.class) // @ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST) // @ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleException(BindingResult bindingResult) { public ErrorResponse handleException(BindingResult bindingResult) {
List<ErrorModel> errorMessages = bindingResult.getFieldErrors().stream() List<ErrorModel> errorMessages = bindingResult.getFieldErrors().stream()

View File

@ -15,8 +15,9 @@ public interface ChatMessageRepository extends JpaRepository<ChatMessage, Long>
// @Query("select ur from UserRole ur where ur.user.userID = ?1") // @Query("select ur from UserRole ur where ur.user.userID = ?1")
// @Query("select m from ChatMessage m where m.toUser.userID = ?1 or m.toUser.userID = ?2 and " // @Query("select m from ChatMessage m where m.toUser.userID = ?1 or m.toUser.userID = ?2 and "
// + "m.fromUser.userID = ?1 or m.fromUser.userID = ?2 order by m.messageTime asc") // + "m.fromUser.userID = ?1 or m.fromUser.userID = ?2 order by m.messageTime asc")
@Query("select m from ChatMessage m join fetch m.messageCipher where (m.toUser.userName = ?1 or m.toUser.userName = ?2) and " @Query("select m from ChatMessage m join fetch m.messageCipher mc join fetch m.toUser tu join fetch m.fromUser fu "
+ "(m.fromUser.userName = ?1 or m.fromUser.userName = ?2) order by m.messageTime asc") + "where (tu.userName = ?1 or tu.userName = ?2) and "
+ "(fu.userName = ?1 or fu.userName = ?2) order by m.messageTime asc")
public List<ChatMessage> getAllMessages(String fromUser, String toUser); public List<ChatMessage> getAllMessages(String fromUser, String toUser);
@Query("select m from ChatMessage m join fetch m.messageCipher where (m.toUser.userName = ?1 or m.toUser.userName = ?2) and " @Query("select m from ChatMessage m join fetch m.messageCipher where (m.toUser.userName = ?1 or m.toUser.userName = ?2) and "

View File

@ -1,5 +1,7 @@
package org.ros.chatto.repository; package org.ros.chatto.repository;
import java.util.List;
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;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
@ -9,4 +11,7 @@ import org.springframework.stereotype.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 ChatUser findByUserName(String userName);
@Query("select cu.userName from ChatUser cu where cu.userName != ?1")
public List<String> findAllOtherUserNames(String userName);
} }

View File

@ -1,5 +1,7 @@
package org.ros.chatto.repository; package org.ros.chatto.repository;
import java.util.List;
import org.ros.chatto.model.UserSession; import org.ros.chatto.model.UserSession;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
@ -9,4 +11,7 @@ import org.springframework.stereotype.Repository;
public interface UserSessionRepository extends JpaRepository<UserSession, Long> { public interface UserSessionRepository extends JpaRepository<UserSession, Long> {
@Query("select us from UserSession us join fetch us.user where us.user.userName = ?1 ") @Query("select us from UserSession us join fetch us.user where us.user.userName = ?1 ")
public UserSession findByUserName(String userName); public UserSession findByUserName(String userName);
@Query("select us from UserSession us join fetch us.user")
public List<UserSession> findAllUserSessions();
} }

View File

@ -102,7 +102,7 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
// response.sendError(440, "Token authentication error: Token has expired"); // response.sendError(440, "Token authentication error: Token has expired");
response.getWriter().write("Token authentication error: Token has expired"); response.getWriter().write("Token authentication error: Token has expired");
logger.warn("Token authentication error: Token has expired"); logger.warn("Token authentication error: Token has expired");
return; // return;
} }
} }

View File

@ -1,12 +1,9 @@
package org.ros.chatto.service; package org.ros.chatto.service;
import java.sql.SQLException;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.transaction.Transactional;
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;
@ -17,11 +14,12 @@ import org.ros.chatto.repository.ChatMessageRepository;
import org.ros.chatto.repository.MessageCipherRepository; import org.ros.chatto.repository.MessageCipherRepository;
import org.ros.chatto.repository.UserRepository; import org.ros.chatto.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service @Service
@Transactional
public class ChatServiceImpl implements ChatService { public class ChatServiceImpl implements ChatService {
// @Autowired // @Autowired
@ -35,7 +33,6 @@ public class ChatServiceImpl implements ChatService {
@Autowired @Autowired
MyConversionService myConversionService; MyConversionService myConversionService;
@Transactional
public ChatMessageDTO saveNewMessage(String fromUserName, String toUserName, MessageCipherDTO messageCipherDTO) { public ChatMessageDTO saveNewMessage(String fromUserName, String toUserName, MessageCipherDTO messageCipherDTO) {
MessageCipher messageCipher = myConversionService.convertToMessageCipher(messageCipherDTO); MessageCipher messageCipher = myConversionService.convertToMessageCipher(messageCipherDTO);
@ -59,6 +56,7 @@ public class ChatServiceImpl implements ChatService {
} }
@Override @Override
@Transactional(readOnly = true)
public List<ChatMessageDTO> getAllMessages(String fromUser, String toUser) { public List<ChatMessageDTO> getAllMessages(String fromUser, String toUser) {
List<ChatMessage> chatMessages = chatMessageRepository.getAllMessages(fromUser, toUser); List<ChatMessage> chatMessages = chatMessageRepository.getAllMessages(fromUser, toUser);
List<ChatMessageDTO> chatMessageDTOs = myConversionService.convertToChatMessageDTOs(chatMessages); List<ChatMessageDTO> chatMessageDTOs = myConversionService.convertToChatMessageDTOs(chatMessages);
@ -66,11 +64,13 @@ public class ChatServiceImpl implements ChatService {
} }
@Override @Override
@Transactional(readOnly = true)
public List<ReencryptionDTO> getAllMessagesForReencryption(String fromUser, String toUser) { public List<ReencryptionDTO> getAllMessagesForReencryption(String fromUser, String toUser) {
return myConversionService.convertToReencryptionDTOs(chatMessageRepository.getAllMessages(fromUser, toUser)); return myConversionService.convertToReencryptionDTOs(chatMessageRepository.getAllMessages(fromUser, toUser));
} }
@Override @Override
@Transactional(readOnly = true)
public List<ChatMessageDTO> getMessagePage(String fromUser, String toUser, int page, int size) { public List<ChatMessageDTO> getMessagePage(String fromUser, String toUser, int page, int size) {
// Sort sort = Sort // Sort sort = Sort
// Page<ChatMessage> chatMessages = chatMessageRepository.getAllMessages(fromUser, toUser,PageRequest.of(page, size)); // Page<ChatMessage> chatMessages = chatMessageRepository.getAllMessages(fromUser, toUser,PageRequest.of(page, size));
@ -80,8 +80,8 @@ public class ChatServiceImpl implements ChatService {
} }
@Override @Override
@Transactional(readOnly = true)
public List<ChatMessageDTO> getNewMessages(String fromUser, String toUser, Date lastMessageTime) { public List<ChatMessageDTO> getNewMessages(String fromUser, String toUser, Date lastMessageTime) {
// TODO Auto-generated method stub
List<ChatMessage> chatMessages = chatMessageRepository.getNewMessages(fromUser, toUser, lastMessageTime); List<ChatMessage> chatMessages = chatMessageRepository.getNewMessages(fromUser, toUser, lastMessageTime);
// List<ChatMessageDTO> chatMessageDTOs // List<ChatMessageDTO> chatMessageDTOs
return myConversionService.convertToChatMessageDTOs(chatMessages); return myConversionService.convertToChatMessageDTOs(chatMessages);
@ -89,10 +89,7 @@ public class ChatServiceImpl implements ChatService {
@Override @Override
@Transactional
public void reencryptMessages(List<ReencryptionDTO> reencryptionDTOs) { public void reencryptMessages(List<ReencryptionDTO> reencryptionDTOs) {
// TODO Auto-generated method stub
// chatMessageRepository.saveAll(chatMessages);
List<MessageCipher> messageCiphers = reencryptionDTOs.stream().map(reencryptionDTO -> reencryptionDTO.getMessageCipher()).collect(Collectors.toList()); List<MessageCipher> messageCiphers = reencryptionDTOs.stream().map(reencryptionDTO -> reencryptionDTO.getMessageCipher()).collect(Collectors.toList());
messageCipherRepository.saveAll(messageCiphers); messageCipherRepository.saveAll(messageCiphers);
} }

View File

@ -4,14 +4,17 @@ import org.ros.chatto.model.Role;
import org.ros.chatto.repository.RoleRepository; import org.ros.chatto.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service @Service
@Transactional
public class RoleServiceImpl implements RoleService { public class RoleServiceImpl implements RoleService {
@Autowired @Autowired
private RoleRepository roleRepository; private RoleRepository roleRepository;
@Override @Override
@Transactional(readOnly = true)
public Role getRole(String roleName) { public Role getRole(String roleName) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
// Role role = new Role(); // Role role = new Role();

View File

@ -7,8 +7,6 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.transaction.Transactional;
import org.ros.chatto.dto.ActiveUserDTO; import org.ros.chatto.dto.ActiveUserDTO;
import org.ros.chatto.dto.UserRegistrationDTO; import org.ros.chatto.dto.UserRegistrationDTO;
import org.ros.chatto.model.ChatUser; import org.ros.chatto.model.ChatUser;
@ -22,32 +20,32 @@ import org.ros.chatto.repository.UserSessionRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Service @Service
public class UserServiceImpl implements UserService { public class UserServiceImpl implements UserService {
@Autowired @Autowired
UserRepository userRepository; private UserRepository userRepository;
@Autowired @Autowired
UserRoleRepository userRoleRepository; private UserRoleRepository userRoleRepository;
@Autowired @Autowired
PasswordEncoder passwordEncoder; private PasswordEncoder passwordEncoder;
@Autowired @Autowired
RoleService roleService; private RoleService roleService;
@Autowired @Autowired
UserRepositoryCustom userRepositoryCustom; private UserRepositoryCustom userRepositoryCustom;
@Autowired @Autowired
private UserSessionRepository userSessionRepository; private UserSessionRepository userSessionRepository;
@Override @Override
@Transactional
public void saveChatUser(ChatUser user) { public void saveChatUser(ChatUser user) {
// TODO Auto-generated method stub
ChatUser changedUser = userRepository.save(user); ChatUser changedUser = userRepository.save(user);
UserRole userRole = new UserRole(); UserRole userRole = new UserRole();
userRole.setRole(roleService.getRole("USER")); userRole.setRole(roleService.getRole("USER"));
@ -56,9 +54,7 @@ public class UserServiceImpl implements UserService {
} }
@Override @Override
@Transactional
public void registerUser(UserRegistrationDTO userRegistrationDTO) { public void registerUser(UserRegistrationDTO userRegistrationDTO) {
// TODO Auto-generated method stub
ChatUser user = new ChatUser(); ChatUser user = new ChatUser();
user.setUserName(userRegistrationDTO.getUserName()); user.setUserName(userRegistrationDTO.getUserName());
user.setPassword(passwordEncoder.encode(userRegistrationDTO.getPassword())); user.setPassword(passwordEncoder.encode(userRegistrationDTO.getPassword()));
@ -73,33 +69,23 @@ public class UserServiceImpl implements UserService {
} }
@Override @Override
@Transactional(readOnly = true)
public List<String> findAllOtherUsers(String userName) { public List<String> findAllOtherUsers(String userName) {
// TODO Auto-generated method stub return userRepository.findAllOtherUserNames(userName);
return userRepositoryCustom.getAllUserNames(userName);
} }
@Transactional(readOnly = true)
@Override @Override
public List<String> getAllRegularUsers() { public List<String> getAllRegularUsers() {
// TODO Auto-generated method stub
return userRoleRepository.getAllRegularUser(); return userRoleRepository.getAllRegularUser();
} }
@Transactional(readOnly = true)
public List<ActiveUserDTO> getOtherActiveUsers(String userName) { public List<ActiveUserDTO> getOtherActiveUsers(String userName) {
List<String> userList = findAllOtherUsers(userName); List<String> userList = findAllOtherUsers(userName);
// List<String> onlineUsers = activeUserStore.getUsers();
List<UserSession> userSessionsList = userSessionRepository.findAll(); List<UserSession> userSessionsList = userSessionRepository.findAllUserSessions();
Map<String, UserSession> lastActiveMap = convertToMap(userSessionsList); Map<String, UserSession> lastActiveMap = convertToMap(userSessionsList);
// userList.forEach(u -> {
// ActiveUserDTO activeUserDTO = new ActiveUserDTO();
// activeUserDTO.setUserName(u);
// activeUserDTO.setOnline(false);
// activeUserDTO.setLastActive(toLastActiveString(lastActiveMap.get(u)));
// if (onlineUsers.contains(u)) {
// activeUserDTO.setOnline(true);
// }
// activeUserDTOs.add(activeUserDTO);
// });
List<ActiveUserDTO> activeUserDTOs = new ArrayList<ActiveUserDTO>(); List<ActiveUserDTO> activeUserDTOs = new ArrayList<ActiveUserDTO>();
userList.forEach(u -> { userList.forEach(u -> {
@ -121,20 +107,12 @@ public class UserServiceImpl implements UserService {
return activeUserDTOs; return activeUserDTOs;
} }
@Transactional(readOnly = true)
@Override @Override
public ChatUser findByUserName(String userName) { public ChatUser findByUserName(String userName) {
// TODO Auto-generated method stub
return userRepository.findByUserName(userName); return userRepository.findByUserName(userName);
} }
// private Map<String, Instant> convertToMap(List<UserSession> userSessionList) {
// Map<String, Instant> userMap = new HashMap<>();
// userSessionList.forEach(us -> {
// userMap.put(us.getUser().getUserName(), us.getTimeStamp());
// });
// return userMap;
// }
private Map<String, UserSession> convertToMap(List<UserSession> userSessionList) { private Map<String, UserSession> convertToMap(List<UserSession> userSessionList) {
Map<String, UserSession> userMap = new HashMap<>(); Map<String, UserSession> userMap = new HashMap<>();
userSessionList.forEach(us -> { userSessionList.forEach(us -> {

View File

@ -12,6 +12,7 @@ spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDial
# Hibernate ddl auto (create, create-drop, validate, update) # Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = none spring.jpa.hibernate.ddl-auto = none
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.generate_statistics=true spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.stat=debug logging.level.org.hibernate.stat=debug
@ -26,6 +27,7 @@ spring.jackson.serialization.write-dates-as-timestamps=false
#spring.cache.type=ehcache3 #spring.cache.type=ehcache3
spring.cache.jcache.config=classpath:ehcache.xml spring.cache.jcache.config=classpath:ehcache.xml
logging.level.org.springframework.cache = DEBUG logging.level.org.springframework.cache = DEBUG
#test.bindAddress=192.168.1.106 #test.bindAddress=192.168.1.106
chatto.token.timeout-duration=30 chatto.token.timeout-duration=30

View File

@ -1,7 +1,10 @@
package org.ros.chatto; package org.ros.chatto;
import java.util.List;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.ros.chatto.repository.UserRepository;
import org.ros.chatto.repository.UserRoleRepository; import org.ros.chatto.repository.UserRoleRepository;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -9,8 +12,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest @SpringBootTest
public class ChattoApplicationTests { public class ChattoApplicationTests {
@ -21,11 +22,11 @@ public class ChattoApplicationTests {
// @Mock // @Mock
// ChatMessageRepository mockChatMessageRepository; // ChatMessageRepository mockChatMessageRepository;
// //
// @Autowired @Autowired
// UserRepository userRepository; private UserRepository userRepository;
@Autowired @Autowired
UserRoleRepository userRoleRepository; private UserRoleRepository userRoleRepository;
private final Logger logger = LoggerFactory.getLogger(ChattoApplicationTests.class); private final Logger logger = LoggerFactory.getLogger(ChattoApplicationTests.class);
// //
@ -39,11 +40,16 @@ public class ChattoApplicationTests {
// } // }
@Test @Test
public void testRepo() { public void testRoleRepo() {
List<String> list = userRoleRepository.getAllRegularUser(); List<String> list = userRoleRepository.getAllRegularUser();
logger.info("List = {} ", list); logger.info("List = {} ", list);
} }
@Test
public void findAllOtherUsers() {
logger.info("Usernames = {}",userRepository.findAllOtherUserNames("hmm").toString());
}
// @Test // @Test
// public void testSave() { // public void testSave() {
// ChatUser fromUser = new ChatUser(); // ChatUser fromUser = new ChatUser();