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}
* @see com.aroussi.util.validation.ErrorResponse
*/
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleException(MethodArgumentNotValidException exception) {
List<ErrorModel> errorMessages = exception.getBindingResult().getFieldErrors().stream()
.map(err -> new ErrorModel(err.getField(), err.getRejectedValue(), err.getDefaultMessage())).distinct()
.collect(Collectors.toList());
return ErrorResponse.builder().errorMessage(errorMessages).build();
}
@ExceptionHandler(value = MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
// @ExceptionHandler(value = MethodArgumentNotValidException.class)
// @ResponseStatus(HttpStatus.BAD_REQUEST)
// public ErrorResponse handleException(MethodArgumentNotValidException exception) {
//
// List<ErrorModel> errorMessages = exception.getBindingResult().getFieldErrors().stream()
// .map(err -> new ErrorModel(err.getField(), err.getRejectedValue(), err.getDefaultMessage())).distinct()
// .collect(Collectors.toList());
// return ErrorResponse.builder().errorMessage(errorMessages).build();
// }
//
// @ExceptionHandler(value = MethodArgumentNotValidException.class)
// @ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleException(BindingResult bindingResult) {
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 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")
@Query("select m from ChatMessage m join fetch m.messageCipher where (m.toUser.userName = ?1 or m.toUser.userName = ?2) and "
+ "(m.fromUser.userName = ?1 or m.fromUser.userName = ?2) order by m.messageTime asc")
@Query("select m from ChatMessage m join fetch m.messageCipher mc join fetch m.toUser tu join fetch m.fromUser fu "
+ "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);
@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;
import java.util.List;
import org.ros.chatto.model.ChatUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
@ -9,4 +11,7 @@ import org.springframework.stereotype.Repository;
public interface UserRepository extends JpaRepository<ChatUser, Long>{
@Query("select cu from ChatUser cu where cu.userName = ?1")
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;
import java.util.List;
import org.ros.chatto.model.UserSession;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
@ -9,4 +11,7 @@ import org.springframework.stereotype.Repository;
public interface UserSessionRepository extends JpaRepository<UserSession, Long> {
@Query("select us from UserSession us join fetch us.user where us.user.userName = ?1 ")
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.getWriter().write("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;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.transaction.Transactional;
import org.ros.chatto.dto.ChatMessageDTO;
import org.ros.chatto.dto.MessageCipherDTO;
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.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class ChatServiceImpl implements ChatService {
// @Autowired
@ -35,7 +33,6 @@ public class ChatServiceImpl implements ChatService {
@Autowired
MyConversionService myConversionService;
@Transactional
public ChatMessageDTO saveNewMessage(String fromUserName, String toUserName, MessageCipherDTO messageCipherDTO) {
MessageCipher messageCipher = myConversionService.convertToMessageCipher(messageCipherDTO);
@ -59,6 +56,7 @@ public class ChatServiceImpl implements ChatService {
}
@Override
@Transactional(readOnly = true)
public List<ChatMessageDTO> getAllMessages(String fromUser, String toUser) {
List<ChatMessage> chatMessages = chatMessageRepository.getAllMessages(fromUser, toUser);
List<ChatMessageDTO> chatMessageDTOs = myConversionService.convertToChatMessageDTOs(chatMessages);
@ -66,11 +64,13 @@ public class ChatServiceImpl implements ChatService {
}
@Override
@Transactional(readOnly = true)
public List<ReencryptionDTO> getAllMessagesForReencryption(String fromUser, String toUser) {
return myConversionService.convertToReencryptionDTOs(chatMessageRepository.getAllMessages(fromUser, toUser));
}
@Override
@Transactional(readOnly = true)
public List<ChatMessageDTO> getMessagePage(String fromUser, String toUser, int page, int size) {
// Sort sort = Sort
// Page<ChatMessage> chatMessages = chatMessageRepository.getAllMessages(fromUser, toUser,PageRequest.of(page, size));
@ -80,8 +80,8 @@ public class ChatServiceImpl implements ChatService {
}
@Override
@Transactional(readOnly = true)
public List<ChatMessageDTO> getNewMessages(String fromUser, String toUser, Date lastMessageTime) {
// TODO Auto-generated method stub
List<ChatMessage> chatMessages = chatMessageRepository.getNewMessages(fromUser, toUser, lastMessageTime);
// List<ChatMessageDTO> chatMessageDTOs
return myConversionService.convertToChatMessageDTOs(chatMessages);
@ -89,10 +89,7 @@ public class ChatServiceImpl implements ChatService {
@Override
@Transactional
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());
messageCipherRepository.saveAll(messageCiphers);
}

View File

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

View File

@ -7,8 +7,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.transaction.Transactional;
import org.ros.chatto.dto.ActiveUserDTO;
import org.ros.chatto.dto.UserRegistrationDTO;
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.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserRepository userRepository;
private UserRepository userRepository;
@Autowired
UserRoleRepository userRoleRepository;
private UserRoleRepository userRoleRepository;
@Autowired
PasswordEncoder passwordEncoder;
private PasswordEncoder passwordEncoder;
@Autowired
RoleService roleService;
private RoleService roleService;
@Autowired
UserRepositoryCustom userRepositoryCustom;
private UserRepositoryCustom userRepositoryCustom;
@Autowired
private UserSessionRepository userSessionRepository;
@Override
@Transactional
public void saveChatUser(ChatUser user) {
// TODO Auto-generated method stub
ChatUser changedUser = userRepository.save(user);
UserRole userRole = new UserRole();
userRole.setRole(roleService.getRole("USER"));
@ -56,9 +54,7 @@ public class UserServiceImpl implements UserService {
}
@Override
@Transactional
public void registerUser(UserRegistrationDTO userRegistrationDTO) {
// TODO Auto-generated method stub
ChatUser user = new ChatUser();
user.setUserName(userRegistrationDTO.getUserName());
user.setPassword(passwordEncoder.encode(userRegistrationDTO.getPassword()));
@ -73,33 +69,23 @@ public class UserServiceImpl implements UserService {
}
@Override
@Transactional(readOnly = true)
public List<String> findAllOtherUsers(String userName) {
// TODO Auto-generated method stub
return userRepositoryCustom.getAllUserNames(userName);
return userRepository.findAllOtherUserNames(userName);
}
@Transactional(readOnly = true)
@Override
public List<String> getAllRegularUsers() {
// TODO Auto-generated method stub
return userRoleRepository.getAllRegularUser();
}
@Transactional(readOnly = true)
public List<ActiveUserDTO> getOtherActiveUsers(String 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);
// 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>();
userList.forEach(u -> {
@ -121,20 +107,12 @@ public class UserServiceImpl implements UserService {
return activeUserDTOs;
}
@Transactional(readOnly = true)
@Override
public ChatUser findByUserName(String userName) {
// TODO Auto-generated method stub
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) {
Map<String, UserSession> userMap = new HashMap<>();
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)
spring.jpa.hibernate.ddl-auto = none
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.stat=debug
@ -26,6 +27,7 @@ spring.jackson.serialization.write-dates-as-timestamps=false
#spring.cache.type=ehcache3
spring.cache.jcache.config=classpath:ehcache.xml
logging.level.org.springframework.cache = DEBUG
#test.bindAddress=192.168.1.106
chatto.token.timeout-duration=30

View File

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