From 8a0fbbd35c13054a947ea0d27ca117542bc452b9 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 18 May 2018 15:33:38 +0300 Subject: JPA WIP --- .../java/com/juick/service/UserServiceImpl.java | 245 +++++---------------- 1 file changed, 61 insertions(+), 184 deletions(-) (limited to 'juick-server/src/main/java/com/juick/service/UserServiceImpl.java') diff --git a/juick-server/src/main/java/com/juick/service/UserServiceImpl.java b/juick-server/src/main/java/com/juick/service/UserServiceImpl.java index 2de3dfc6..ad6be9aa 100644 --- a/juick-server/src/main/java/com/juick/service/UserServiceImpl.java +++ b/juick-server/src/main/java/com/juick/service/UserServiceImpl.java @@ -19,31 +19,35 @@ package com.juick.service; import com.juick.Message; import com.juick.User; +import com.juick.service.data.UsersRepository; +import com.juick.service.data.entities.EmailEntity; +import com.juick.service.data.entities.LoginEntity; +import com.juick.service.data.entities.UserEntity; import com.juick.server.helpers.AnonymousUser; import com.juick.server.helpers.Auth; import com.juick.server.helpers.UserInfo; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; -import org.springframework.dao.DuplicateKeyException; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; -import org.springframework.jdbc.support.GeneratedKeyHolder; -import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.interceptor.TransactionAspectSupport; -import java.sql.PreparedStatement; +import javax.inject.Inject; import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.Statement; import java.util.*; +import java.util.stream.Collectors; /** * Created by aalexeev on 11/13/16. */ @Repository public class UserServiceImpl extends BaseJdbcService implements UserService { + @Inject + private UsersRepository usersRepository; private class UserMapper implements RowMapper { @Override @@ -90,104 +94,55 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { return list.get(0); } - @Transactional + @Transactional(rollbackFor = Exception.class) @Override - public int createUser(final String username, final String password) { - KeyHolder holder = new GeneratedKeyHolder(); + public User createUser(final String username, final String password) { + UserEntity newUser = new UserEntity(); + newUser.setName(username); + newUser.setPassword(password); try { - getJdbcTemplate().update( - con -> { - PreparedStatement stmt = con.prepareStatement( - "INSERT INTO users(nick,passw) VALUES (?,?)", - Statement.RETURN_GENERATED_KEYS); - stmt.setString(1, username); - stmt.setString(2, password); - return stmt; - }, - holder); - } catch (DuplicateKeyException e) { - return -1; + UserEntity created = usersRepository.save(newUser); + getJdbcTemplate().update("INSERT INTO useroptions(user_id) VALUES (?)", created.getId()); + getJdbcTemplate().update("INSERT INTO subscr_users(user_id, suser_id) VALUES (2, ?)", created.getId()); + return EntityUtils.entityToUser(created); + } catch (Exception e) { + TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); + return AnonymousUser.INSTANCE; } - - int uid = holder.getKey().intValue(); - - getJdbcTemplate().update("INSERT INTO useroptions(user_id) VALUES (?)", uid); - getJdbcTemplate().update("INSERT INTO subscr_users(user_id, suser_id) VALUES (2, ?)", uid); - - return uid; } @Transactional(readOnly = true) @Override public Optional getUserByUID(final int uid) { - List list = getJdbcTemplate().query( - "SELECT id, nick, banned, lang FROM users WHERE id = ?", new UserMapper(), uid); - - return list.isEmpty() ? Optional.empty() : Optional.of(list.get(0)); + return usersRepository.findById(uid).map(EntityUtils::entityToUser); } @Transactional(readOnly = true) @Override public User getUserByName(final String username) { - if (StringUtils.isNotBlank(username)) { - List list = getJdbcTemplate().query( - "SELECT id, nick, banned, lang FROM users WHERE nick = ?", new UserMapper(), username); - - if (!list.isEmpty()) - return list.get(0); + Optional e = usersRepository.findByName(username); + if (e.isPresent()) { + return EntityUtils.entityToUser(e.get()); } - // TODO: @NonNullable ? return AnonymousUser.INSTANCE; } @Override - // No need marks with @Transactional annotation + @Transactional(readOnly = true) public User getFullyUserByName(final String username) { - if (StringUtils.isNotBlank(username)) { - List list = getFullyUsersByNames(Collections.singletonList(username)); - if (!list.isEmpty()) - return list.get(0); - } - return null; + return usersRepository.findByName(username).map(EntityUtils::entityToSecurityUser).orElse(AnonymousUser.INSTANCE); } @Override @Transactional(readOnly = true) public User getUserByEmail(String email) { - if (StringUtils.isNotBlank(email)) { - List list = getJdbcTemplate().query( - "SELECT id, nick, banned, lang FROM users WHERE id = (SELECT DISTINCT user_id FROM emails WHERE email = ?)", - new UserMapper(), - email); - - if (!list.isEmpty()) - return list.get(0); + Optional e = usersRepository.findByEmailsEmail(email); + if (e.isPresent()) { + return EntityUtils.entityToUser(e.get()); } return AnonymousUser.INSTANCE; } - @Transactional(readOnly = true) - @Override - public List getFullyUsersByNames(final Collection usernames) { - if (CollectionUtils.isEmpty(usernames)) - return Collections.emptyList(); - - return getNamedParameterJdbcTemplate().query( - "SELECT id, nick, passw, lang, banned FROM users WHERE nick in (:names)", - new MapSqlParameterSource("names", usernames), - (rs, rowNum) -> { - User user = new User(); - - user.setUid(rs.getInt(1)); - user.setName(rs.getString(2)); - user.setCredentials(rs.getString(3)); - user.setLang(rs.getString(4)); - user.setBanned(rs.getBoolean(5)); - - return user; - }); - } - @Transactional(readOnly = true) @Override public User getUserByJID(final String jid) { @@ -208,25 +163,13 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { @Transactional(readOnly = true) @Override public List getUsersByName(final Collection unames) { - if (CollectionUtils.isEmpty(unames)) - return Collections.emptyList(); - - return getNamedParameterJdbcTemplate().query( - "SELECT id, nick, banned, lang FROM users WHERE nick IN (:unames)", - new MapSqlParameterSource("unames", unames), - new UserMapper()); + return usersRepository.findAllByNameIn(unames).map(EntityUtils::entityToUser).collect(Collectors.toList()); } @Transactional(readOnly = true) @Override public List getUsersByID(final Collection uids) { - if (CollectionUtils.isEmpty(uids)) - return Collections.emptyList(); - - return getNamedParameterJdbcTemplate().query( - "SELECT id, nick, banned, lang FROM users WHERE id IN (:ids)", - new MapSqlParameterSource("ids", uids), - new UserMapper()); + return usersRepository.findAllByIdIn(uids).map(EntityUtils::entityToUser).collect(Collectors.toList()); } @Transactional(readOnly = true) @@ -235,59 +178,13 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { return getJdbcTemplate().queryForList("SELECT jid FROM jids WHERE user_id = ? AND active = 1", String.class, uid); } - @Transactional(readOnly = true) - @Override - public int getUIDbyJID(final String jid) { - if (StringUtils.isNotBlank(jid)) { - List list = getJdbcTemplate().queryForList( - "SELECT user_id FROM jids WHERE jid = ?", Integer.class, jid); - - if (!list.isEmpty()) - return list.get(0); - } - return 0; - } - - @Transactional(readOnly = true) - @Override - public int getUIDbyName(final String uname) { - if (StringUtils.isNotBlank(uname)) { - List list = getJdbcTemplate().queryForList( - "SELECT id FROM users WHERE nick = ?", Integer.class, uname); - - if (!list.isEmpty()) - return list.get(0); - } - return 0; - } - - @Transactional(readOnly = true) - @Override - public int getUIDbyHash(final String hash) { - if (StringUtils.isNotBlank(hash)) { - List list = getJdbcTemplate().queryForList( - "SELECT user_id FROM logins WHERE hash = ?", Integer.class, hash); - - if (!list.isEmpty()) - return list.get(0); - } - return 0; - } - @Transactional(readOnly = true) @Override public com.juick.User getUserByHash(final String hash) { if (StringUtils.isNotBlank(hash)) { - List list = getJdbcTemplate().query( - "SELECT logins.user_id, users.nick, users.banned, users.lang FROM logins " + - "INNER JOIN users ON logins.user_id = users.id WHERE logins.hash = ?", - new UserMapper(), - hash); - - if (!list.isEmpty()) { - User user = list.get(0); - user.setAuthHash(hash); - return user; + Optional entityUser = usersRepository.findByLogins_Hash(hash); + if (entityUser.isPresent()) { + return EntityUtils.entityToUser(entityUser.get()); } } return AnonymousUser.INSTANCE; @@ -295,49 +192,36 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { @Transactional @Override - public String getHashByUID(final int uid) { - List list = getJdbcTemplate().queryForList( - "SELECT hash FROM logins WHERE user_id = ?", String.class, uid); - - if (list.isEmpty()) { - String hash = RandomStringUtils.randomAlphanumeric(16).toUpperCase(); - getJdbcTemplate().update("INSERT INTO logins(user_id, hash) VALUES (?, ?)", uid, hash); - return hash; + public String getHashForUser(final User user) { + UserEntity entityUser = usersRepository.findById(user.getUid()).orElseThrow(IllegalStateException::new); + if (entityUser.getLogins().size() > 0) { + return entityUser.getLogins().stream().findFirst().orElseThrow(IllegalStateException::new).getHash(); } - return list.get(0); + + LoginEntity newHash = new LoginEntity(); + newHash.setUser(entityUser); + newHash.setHash(RandomStringUtils.randomAlphanumeric(16).toUpperCase()); + entityUser.getLogins().add(newHash); + return getHashForUser(EntityUtils.entityToUser(usersRepository.save(entityUser))); } @Transactional(readOnly = true) @Override - public int checkPassword(final String username, final String password) { - if (StringUtils.isNotBlank(username)) { - List list = getJdbcTemplate().query( - "SELECT id, nick, banned, passw FROM users WHERE nick = ?", - (rs, rowNum) -> { - User user = new User(); - user.setUid(rs.getInt(1)); - user.setName(rs.getString(2)); - user.setBanned(rs.getBoolean(3)); - user.setCredentials(rs.getString(4)); - return user; - }, - username); - - if (!list.isEmpty()) { - User user = list.get(0); - if (Objects.equals(password, user.getCredentials())) - return user.getUid(); - } - } - return -1; + public User checkPassword(final String username, final String password) { + Optional userEntity = usersRepository.findByNameAndPassword(username, password); + if (userEntity.isPresent()) { + return EntityUtils.entityToUser(userEntity.get()); + }; + return AnonymousUser.INSTANCE; } @Transactional @Override public boolean updatePassword(final User user, final String newPassword) { - return user != null && - user.getUid() > 0 && - getJdbcTemplate().update("UPDATE users SET passw = ? WHERE id = ?", newPassword, user.getUid()) > 0; + UserEntity entityUser = usersRepository.findById(user.getUid()).orElseThrow(IllegalStateException::new); + entityUser.setPassword(newPassword); + usersRepository.save(entityUser); + return true; } @Transactional(readOnly = true) @@ -396,17 +280,6 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { info.getDescription()) > 0; } - @Transactional(readOnly = true) - @Override - public boolean getCanMedia(final int uid) { - List list = getJdbcTemplate().queryForList( - "SELECT users.lastphoto - UNIX_TIMESTAMP() FROM users WHERE id = ?", - Integer.class, - uid); - - return !list.isEmpty() && list.get(0) < 3600; - } - @Transactional(readOnly = true) @Override public boolean isInWL(final int uid, final int check) { @@ -617,8 +490,12 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { @Transactional(readOnly = true) @Override - public List getEmails(final User user) { - return getJdbcTemplate().queryForList("SELECT email FROM emails WHERE user_id=?", String.class, user.getUid()); + public Collection getEmails(final User user) { + Optional entityUser = usersRepository.findById(user.getUid()); + if (entityUser.isPresent()) { + return entityUser.get().getEmails().stream().map(EmailEntity::getEmail).collect(Collectors.toList()); + } + return Collections.emptyList(); } @Transactional(readOnly = true) -- cgit v1.2.3