diff options
author | Alexander Alexeev | 2016-11-17 23:45:13 +0700 |
---|---|---|
committer | Vitaly Takmazov | 2016-11-23 13:02:55 +0300 |
commit | 19709fa2ade17433b9a76ad4459e1e09d27b88bf (patch) | |
tree | 188ba9d24f4fc5bdf7707c57d61cd9c7212b45cf /juick-server/src/main/java/com/juick/service | |
parent | 78a1a68e5555648a07588873b08d59a094391709 (diff) |
repository improvenments: using Collection in params, forse using exists in some query, force using Lists as query result
Diffstat (limited to 'juick-server/src/main/java/com/juick/service')
14 files changed, 950 insertions, 979 deletions
diff --git a/juick-server/src/main/java/com/juick/service/AdsServiceImpl.java b/juick-server/src/main/java/com/juick/service/AdsServiceImpl.java index a6a5c85d..f515e437 100644 --- a/juick-server/src/main/java/com/juick/service/AdsServiceImpl.java +++ b/juick-server/src/main/java/com/juick/service/AdsServiceImpl.java @@ -12,7 +12,6 @@ import java.util.List; * Created by aalexeev on 11/13/16. */ @Repository -@Transactional public class AdsServiceImpl extends BaseJdbcService implements AdsService { @Inject @@ -42,6 +41,7 @@ public class AdsServiceImpl extends BaseJdbcService implements AdsService { 0 : list.get(0); } + @Transactional @Override public int logAdMid(final int uid, final int mid) { return getJdbcTemplate().update( diff --git a/juick-server/src/main/java/com/juick/service/MessagesService.java b/juick-server/src/main/java/com/juick/service/MessagesService.java index 00f97b75..83ab0dce 100644 --- a/juick-server/src/main/java/com/juick/service/MessagesService.java +++ b/juick-server/src/main/java/com/juick/service/MessagesService.java @@ -3,13 +3,14 @@ package com.juick.service; import com.juick.User; import org.springframework.jdbc.core.JdbcTemplate; +import java.util.Collection; import java.util.List; /** * Created by aalexeev on 11/13/16. */ public interface MessagesService { - int createMessage(int uid, String txt, String attachment, List<com.juick.Tag> tags); + int createMessage(int uid, String txt, String attachment, Collection<com.juick.Tag> tags); int createReply(int mid, int rid, int uid, String txt, String attachment); @@ -37,13 +38,13 @@ public interface MessagesService { List<String> getMessageRecommendations(int mid); - List<Integer> getAll(int visitor_uid, int before); + List<Integer> getAll(int visitorUid, int before); - List<Integer> getTag(int tid, int visitor_uid, int before, int cnt); + List<Integer> getTag(int tid, int visitorUid, int before, int cnt); - List<Integer> getTags(String tids, int visitor_uid, int before, int cnt); + List<Integer> getTags(String tids, int visitorUid, int before, int cnt); - List<Integer> getPlace(int place_id, int visitor_uid, int before); + List<Integer> getPlace(int placeId, int visitorUid, int before); List<Integer> getMyFeed(int uid, int before); @@ -53,23 +54,23 @@ public interface MessagesService { List<Integer> getRecommended(int uid, int before); - List<Integer> getPopular(int visitor_uid, int before); + List<Integer> getPopular(int visitorUid, int before); - List<Integer> getPhotos(int visitor_uid, int before); + List<Integer> getPhotos(int visitorUid, int before); List<Integer> getSearch(JdbcTemplate sqlSearch, String search, int before); - List<Integer> getUserBlog(int UID, int privacy, int before); + List<Integer> getUserBlog(int uid, int privacy, int before); - List<Integer> getUserTag(int UID, int TID, int privacy, int before); + List<Integer> getUserTag(int uid, int tid, int privacy, int before); - List<Integer> getUserRecommendations(int UID, int before); + List<Integer> getUserRecommendations(int uid, int before); - List<Integer> getUserPhotos(int UID, int privacy, int before); + List<Integer> getUserPhotos(int uid, int privacy, int before); List<Integer> getUserSearch(JdbcTemplate sqlSearch, int UID, String search, int privacy, int before); - List<com.juick.Message> getMessages(List<Integer> mids); + List<com.juick.Message> getMessages(Collection<Integer> mids); List<com.juick.Message> getReplies(int mid); diff --git a/juick-server/src/main/java/com/juick/service/MessagesServiceImpl.java b/juick-server/src/main/java/com/juick/service/MessagesServiceImpl.java index bb030ed4..6fc71ac3 100644 --- a/juick-server/src/main/java/com/juick/service/MessagesServiceImpl.java +++ b/juick-server/src/main/java/com/juick/service/MessagesServiceImpl.java @@ -5,24 +5,24 @@ import com.juick.Tag; import com.juick.User; import com.juick.server.helpers.PrivacyOpts; import com.juick.util.MessageUtils; +import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringEscapeUtils; -import org.springframework.dao.EmptyResultDataAccessException; +import org.apache.commons.lang3.StringUtils; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.ConnectionCallback; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; +import org.springframework.jdbc.core.namedparam.SqlParameterSource; 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.util.Assert; -import org.springframework.util.StringUtils; import javax.inject.Inject; import java.sql.*; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; +import java.util.*; /** * Created by aalexeev on 11/13/16. @@ -77,85 +77,92 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ } } + /** + * @param uid + * @param txt + * @param attachment + * @param tags + * @return + * @see <a href="https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-type-conversions.html">Java, JDBC and MySQL Types</a> + */ @Transactional @Override - public int createMessage(final int uid, final String txt, final String attachment, final List<com.juick.Tag> tags) { + public int createMessage(final int uid, final String txt, final String attachment, final Collection<com.juick.Tag> tags) { KeyHolder holder = new GeneratedKeyHolder(); - getJdbcTemplate().update(con -> { - PreparedStatement stmt = con.prepareStatement( - "INSERT INTO messages(user_id,attach) VALUES (?,?)", - Statement.RETURN_GENERATED_KEYS); - stmt.setInt(1, uid); - if (attachment != null) { - stmt.setString(2, attachment); - } else { - stmt.setNull(2, Types.VARCHAR); - } - return stmt; - }, holder); + getJdbcTemplate().update( + con -> { + PreparedStatement stmt = con.prepareStatement( + "INSERT INTO messages(user_id, attach) VALUES (?, ?)", + Statement.RETURN_GENERATED_KEYS); + stmt.setInt(1, uid); + if (attachment != null) + stmt.setString(2, attachment); + else + stmt.setNull(2, Types.CHAR); + + return stmt; + }, + holder); int mid = holder.getKey().intValue(); if (mid > 0) { String tagsNames = ""; - String tagsIDs = ""; - for (int i = 0; i < tags.size(); i++) { - if (i > 0) { - tagsNames += " "; - tagsIDs += ","; + if (CollectionUtils.isNotEmpty(tags)) { + StringBuilder tasNamesBuilder = new StringBuilder(); + List<Object[]> params = new ArrayList<>(tags.size()); + + boolean next = false; + + for (Tag tag : tags) { + if (next) { + tasNamesBuilder.append(" "); + } else + next = true; + + tasNamesBuilder.append(tag.getName()); + params.add(new Object[]{mid, tag.TID}); } - tagsNames += tags.get(i).getName(); - tagsIDs += "(" + mid + "," + tags.get(i).TID + ")"; - } - if (tags.size() > 0) { - getJdbcTemplate().execute( - "INSERT INTO messages_tags(message_id,tag_id) VALUES " + tagsIDs); + + tagsNames = tasNamesBuilder.toString(); + + getJdbcTemplate().batchUpdate( + "INSERT INTO messages_tags(message_id, tag_id) VALUES (?, ?)", + params, new int[]{Types.INTEGER, Types.INTEGER}); } - final String finalTagsNames = tagsNames; - getJdbcTemplate().update(con -> { - PreparedStatement stmt = con.prepareStatement( - "INSERT INTO messages_txt(message_id,tags,txt) " + - "VALUES (?,?,?)", Statement.NO_GENERATED_KEYS); - stmt.setInt(1, mid); - if (finalTagsNames.isEmpty()) { - stmt.setNull(2, Types.VARCHAR); - } else { - stmt.setString(2, finalTagsNames); - } - stmt.setString(3, txt); - return stmt; - }); + + getJdbcTemplate().update( + "INSERT INTO messages_txt(message_id, tags, txt) VALUES (?, ?, ?)", + new Object[]{mid, tagsNames, txt}, + new int[]{Types.INTEGER, Types.VARCHAR, Types.VARCHAR}); } return mid; } + /** + * @param mid + * @param rid + * @param uid + * @param txt + * @param attachment + * @return + * @see <a href="https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-type-conversions.html">Java, JDBC and MySQL Types</a> + */ @Transactional @Override public int createReply(final int mid, final int rid, final int uid, final String txt, final String attachment) { int ridnew = getReplyIDIncrement(mid); - getJdbcTemplate().update(con -> { - PreparedStatement stmt = con.prepareStatement( - "INSERT INTO replies(message_id,reply_id,user_id,replyto,attach,txt) VALUES (?,?,?,?,?,?)", - Statement.NO_GENERATED_KEYS); - stmt.setInt(1, mid); - stmt.setInt(2, ridnew); - stmt.setInt(3, uid); - stmt.setInt(4, rid); - if (attachment != null) { - stmt.setString(5, attachment); - } else { - stmt.setNull(5, Types.VARCHAR); - } - stmt.setString(6, txt); - return stmt; - }); + getJdbcTemplate().update( + "INSERT INTO replies(message_id, reply_id, user_id, replyto, attach, txt) VALUES (?, ?, ?, ?, ?, ?)", + new Object[]{mid, ridnew, uid, rid, attachment, txt}, + new int[]{Types.INTEGER, Types.SMALLINT, Types.INTEGER, Types.SMALLINT, Types.CHAR, Types.VARCHAR}); if (ridnew > 0) getJdbcTemplate().update( - "UPDATE messages SET replies=replies+1 WHERE message_id=?", + "UPDATE messages SET replies = replies + 1 WHERE message_id = ?", mid); return ridnew; @@ -196,10 +203,12 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ @Override public boolean recommendMessage(final int mid, final int vuid) { boolean res = getJdbcTemplate().update( - "INSERT IGNORE INTO favorites(user_id,message_id) VALUES (" + vuid + "," + mid + ")") == 1; + "INSERT IGNORE INTO favorites(user_id, message_id) VALUES (?, ?)", + vuid, mid) == 1; + if (res) { getJdbcTemplate().update( - "UPDATE messages SET likes=likes+1 WHERE message_id=?", + "UPDATE messages SET likes = likes + 1 WHERE message_id = ?", mid); } return res; @@ -208,140 +217,138 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ @Transactional(readOnly = true) @Override public boolean canViewThread(final int mid, final int uid) { - PrivacyOpts privacyOpts; - try { - privacyOpts = getJdbcTemplate().queryForObject( - "SELECT user_id,privacy FROM messages WHERE messages.message_id=?", - (rs, rowNum) -> { - PrivacyOpts res = new PrivacyOpts(); - res.setUid(rs.getInt(1)); - res.setPrivacy(rs.getInt(2)); - return res; - }, mid); - } catch (EmptyResultDataAccessException e) { - return true; - } - return privacyOpts.getPrivacy() >= 0 - || uid == privacyOpts.getUid() - || ((privacyOpts.getPrivacy() == -1 || privacyOpts.getPrivacy() == -2) && uid > 0 - && userService.isInWL(privacyOpts.getUid(), uid)); + List<PrivacyOpts> list = getJdbcTemplate().query( + "SELECT user_id, privacy FROM messages WHERE message_id = ?", + (rs, rowNum) -> { + PrivacyOpts res = new PrivacyOpts(); + + res.setUid(rs.getInt(1)); + res.setPrivacy(rs.getInt(2)); + + return res; + }, + mid); + + PrivacyOpts privacyOpts = list.isEmpty() ? + null : list.get(0); + + return privacyOpts == null || + privacyOpts.getPrivacy() >= 0 || + uid == privacyOpts.getUid() || + ((privacyOpts.getPrivacy() == -1 || privacyOpts.getPrivacy() == -2) && + uid > 0 && userService.isInWL(privacyOpts.getUid(), uid)); } @Transactional(readOnly = true) @Override public boolean isReadOnly(final int mid) { - try { - return getJdbcTemplate().queryForObject( - "SELECT readonly FROM messages WHERE message_id=?", - new Object[]{mid}, - Integer.class) == 1; - } catch (EmptyResultDataAccessException e) { - return false; - } + List<Integer> list = getJdbcTemplate().queryForList( + "SELECT readonly FROM messages WHERE message_id = ?", + new Object[]{mid}, + Integer.class); + + return !list.isEmpty() || list.get(0) == 1; } @Transactional(readOnly = true) @Override public boolean isSubscribed(final int uid, final int mid) { - try { - return getJdbcTemplate().queryForObject( - "SELECT 1 FROM subscr_messages WHERE suser_id=? AND message_id=?", - new Object[]{uid, mid}, - Integer.class) == 1; - } catch (EmptyResultDataAccessException e) { - return false; - } + List<Integer> list = getJdbcTemplate().queryForList( + "SELECT 1 FROM subscr_messages WHERE suser_id = ? AND message_id = ?", + new Object[]{uid, mid}, + Integer.class); + + return !list.isEmpty() || list.get(0) == 1; } @Transactional(readOnly = true) @Override public int getMessagePrivacy(final int mid) { - try { - return getJdbcTemplate().queryForObject( - "SELECT privacy FROM messages WHERE message_id=?", - new Object[]{mid}, - Integer.class); - } catch (EmptyResultDataAccessException e) { - return -4; - } + List<Integer> list = getJdbcTemplate().queryForList( + "SELECT privacy FROM messages WHERE message_id = ?", + new Object[]{mid}, + Integer.class); + + return list.isEmpty() ? + -4 : list.get(0); } @Transactional(readOnly = true) @Override public com.juick.Message getMessage(final int mid) { - try { - return getJdbcTemplate().queryForObject( - "SELECT messages.message_id, 0 as rid, 0 as replyto, " - + "messages.user_id,users.nick, 0 as banned, " - + "TIMESTAMPDIFF(MINUTE,messages.ts,NOW())," - + "messages.ts," - + "messages.readonly,messages.privacy,messages.replies," - + "messages.attach,messages.place_id,messages.lat," - + "messages.lon,messages.likes,messages.hidden," - + "txt.tags,txt.repliesby,txt.txt, '' as q FROM messages " - + "INNER JOIN users ON messages.user_id=users.id " - + "INNER JOIN messages_txt AS txt " - + "ON messages.message_id=txt.message_id " - + "WHERE messages.message_id=?", - new MessageMapper(), - mid); - } catch (EmptyResultDataAccessException e) { - return null; - } + List<com.juick.Message> list = getJdbcTemplate().query( + "SELECT messages.message_id, 0 as rid, 0 as replyto, " + + "messages.user_id, users.nick, 0 as banned, " + + "TIMESTAMPDIFF(MINUTE, messages.ts, NOW())," + + "messages.ts," + + "messages.readonly, messages.privacy, messages.replies," + + "messages.attach, messages.place_id, messages.lat," + + "messages.lon, messages.likes, messages.hidden," + + "txt.tags, txt.repliesby, txt.txt, '' as q FROM messages " + + "INNER JOIN users ON messages.user_id = users.id " + + "INNER JOIN messages_txt AS txt " + + "ON messages.message_id = txt.message_id " + + "WHERE messages.message_id = ?", + new MessageMapper(), + mid); + + return list.isEmpty() ? + null : list.get(0); } @Transactional(readOnly = true) @Override public com.juick.Message getReply(final int mid, final int rid) { - try { - return getJdbcTemplate().queryForObject( - "SELECT replies.user_id,users.nick," - + "replies.replyto,replies.ts," - + "replies.attach,replies.txt, IFNULL(q.txt,t.txt) as quote FROM replies INNER JOIN users " - + "ON replies.user_id=users.id " - + "LEFT JOIN replies q " - + "ON replies.message_id=q.message_id and replies.replyto=q.reply_id " - + "LEFT JOIN messages_txt t ON replies.message_id=t.message_id " - + "WHERE replies.message_id=? AND replies.reply_id=?", - (rs, num) -> { - Message msg = new Message(); - msg.setMid(mid); - msg.setRid(rid); - msg.setUser(new User()); - msg.getUser().setUid(rs.getInt(1)); - msg.getUser().setName(rs.getString(2)); - msg.setReplyto(rs.getInt(3)); - msg.setDate(rs.getTimestamp(4)); - msg.AttachmentType = rs.getString(5); - msg.setText(rs.getString(6)); - String quote = rs.getString(7); - if (!StringUtils.isEmpty(quote)) { - msg.setReplyQuote(MessageUtils.formatQuote(quote)); - } - return msg; - }, mid, rid); - } catch (EmptyResultDataAccessException e) { - return null; - } + List<com.juick.Message> list = getJdbcTemplate().query( + "SELECT replies.user_id, users.nick," + + "replies.replyto, replies.ts," + + "replies.attach, replies.txt, IFNULL(q.txt,t.txt) as quote " + + "FROM replies INNER JOIN users ON replies.user_id = users.id " + + "LEFT JOIN replies q ON replies.message_id = q.message_id and replies.replyto = q.reply_id " + + "LEFT JOIN messages_txt t ON replies.message_id = t.message_id " + + "WHERE replies.message_id = ? AND replies.reply_id = ?", + (rs, num) -> { + Message msg = new Message(); + + msg.setMid(mid); + msg.setRid(rid); + msg.setUser(new User()); + msg.getUser().setUid(rs.getInt(1)); + msg.getUser().setName(rs.getString(2)); + msg.setReplyto(rs.getInt(3)); + msg.setDate(rs.getTimestamp(4)); + msg.AttachmentType = rs.getString(5); + msg.setText(rs.getString(6)); + String quote = rs.getString(7); + + if (!StringUtils.isEmpty(quote)) { + msg.setReplyQuote(MessageUtils.formatQuote(quote)); + } + + return msg; + }, + mid, rid); + + return list.isEmpty() ? + null : list.get(0); } @Transactional(readOnly = true) @Override public User getMessageAuthor(final int mid) { - try { - return getJdbcTemplate().queryForObject( - "SELECT messages.user_id,users.nick " - + "FROM messages INNER JOIN users " - + "ON messages.user_id=users.id WHERE messages.message_id=?", - new Object[]{mid}, (rs, num) -> { - User res = new com.juick.User(); - res.setUid(rs.getInt(1)); - res.setName(rs.getString(2)); - return res; - }); - } catch (EmptyResultDataAccessException e) { - return null; - } + List<User> list = getJdbcTemplate().query( + "SELECT messages.user_id, users.nick " + + "FROM messages INNER JOIN users ON messages.user_id = users.id WHERE messages.message_id = ?", + new Object[]{mid}, + (rs, num) -> { + User res = new com.juick.User(); + res.setUid(rs.getInt(1)); + res.setName(rs.getString(2)); + return res; + }); + + return list.isEmpty() ? + null : list.get(0); } @Transactional(readOnly = true) @@ -349,8 +356,9 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ public List<com.juick.Tag> getMessageTags(final int mid) { return getJdbcTemplate().query( "SELECT tags.tag_id,synonym_id,name,stat_messages FROM tags " + - "INNER JOIN messages_tags ON (messages_tags.message_id=? AND messages_tags.tag_id=tags.tag_id)", - new Object[]{mid}, (rs, num) -> { + "INNER JOIN messages_tags ON (messages_tags.message_id = ? AND messages_tags.tag_id = tags.tag_id)", + new Object[]{mid}, + (rs, num) -> { com.juick.Tag t = new com.juick.Tag(StringEscapeUtils.unescapeHtml4(rs.getString(3))); t.TID = rs.getInt(1); t.SynonymID = rs.getInt(2); @@ -363,7 +371,7 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ @Override public List<Integer> getMessageTagsIDs(final int mid) { return getJdbcTemplate().queryForList( - "SELECT tag_id FROM messages_tags WHERE message_id=?", + "SELECT tag_id FROM messages_tags WHERE message_id = ?", new Object[]{mid}, Integer.class); } @@ -373,155 +381,110 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ public List<String> getMessageRecommendations(final int mid) { return getJdbcTemplate().queryForList( "SELECT users.nick FROM favorites INNER JOIN users " + - "ON (favorites.message_id=? AND favorites.user_id=users.id)", + "ON (favorites.message_id = ? AND favorites.user_id = users.id)", new Object[]{mid}, String.class); } @Transactional(readOnly = true) @Override - public List<Integer> getAll(final int visitor_uid, final int before) { - if (visitor_uid > 1) { - if (before > 0) { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE message_id<? AND hidden=0" + - " AND (privacy>0 OR user_id=?) AND user_id NOT IN (SELECT bl_user_id FROM bl_users WHERE user_id=?)" + - " AND user_id NOT IN (SELECT id from users WHERE banned=1) ORDER BY message_id DESC LIMIT 20", - new Object[]{before, visitor_uid, visitor_uid}, - Integer.class); - } else { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE hidden=0" + - " AND (privacy>0 OR user_id=?)" + - " AND user_id NOT IN (SELECT bl_user_id FROM bl_users WHERE user_id=?)" + - " AND user_id NOT IN (SELECT id from users WHERE banned=1) ORDER BY message_id DESC LIMIT 20", - new Object[]{visitor_uid, visitor_uid}, - Integer.class); - } - } else { - if (before > 0) { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE message_id<?" + - " AND hidden=0 AND privacy>0 AND user_id NOT IN (SELECT id from users WHERE banned=1) " + - " ORDER BY message_id DESC LIMIT 20", - new Object[]{before}, - Integer.class); - } else { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE hidden=0 AND privacy>0" + - " AND user_id NOT IN (SELECT id from users WHERE banned=1) ORDER BY message_id DESC LIMIT 20", - Integer.class); - } - } + public List<Integer> getAll(final int visitorUid, final int before) { + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("before", before) + .addValue("visitorUid", visitorUid); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT m.message_id FROM messages m WHERE " + + (before > 0 ? + " m.message_id < :before AND " : "") + + " m.hidden = 0 AND (m.privacy > 0" + + (visitorUid > 1 ? + " OR m.user_id = :visitorUid) AND NOT EXISTS (" + + " SELECT 1 FROM bl_users b WHERE b.user_id = :visitorUid AND b.bl_user_id = m.user_id)" : + ")") + + " AND NOT EXISTS (SELECT 1 from users u WHERE u.banned = 1 and u.id = m.user_id) ORDER BY m.message_id DESC LIMIT 20", + sqlParameterSource, + Integer.class); } @Transactional(readOnly = true) @Override - public List<Integer> getTag(final int tid, final int visitor_uid, final int before, final int cnt) { - if (before > 0) { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM (tags INNER JOIN messages_tags " + - "ON ((tags.synonym_id=? OR tags.tag_id=?) AND tags.tag_id=messages_tags.tag_id)) " + - "INNER JOIN messages USING(message_id) WHERE messages.message_id<? " + - "AND (messages.privacy>0 OR messages.user_id=?) ORDER BY message_id DESC LIMIT ?", - new Object[]{tid, tid, before, visitor_uid, cnt}, - Integer.class); - } else { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM (tags INNER JOIN messages_tags " + - "ON ((tags.synonym_id=? OR tags.tag_id=?) AND tags.tag_id=messages_tags.tag_id)) " + - "INNER JOIN messages USING(message_id) WHERE messages.privacy>0 OR messages.user_id=? " + - "ORDER BY message_id DESC LIMIT ?", - new Object[]{tid, tid, visitor_uid, cnt}, - Integer.class); - } + public List<Integer> getTag(final int tid, final int visitorUid, final int before, final int cnt) { + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("tid", tid) + .addValue("cnt", cnt) + .addValue("before", before) + .addValue("visitorUid", visitorUid); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT message_id FROM (tags INNER JOIN messages_tags " + + "ON ((tags.synonym_id = :tid OR tags.tag_id = :tid) AND tags.tag_id = messages_tags.tag_id)) " + + "INNER JOIN messages USING(message_id) WHERE " + + (before > 0 ? + " messages.message_id < :before AND " : "") + + " 1 = 1 AND (messages.privacy > 0 OR messages.user_id = :visitorUid) ORDER BY message_id DESC LIMIT :cnt", + sqlParameterSource, + Integer.class); } @Transactional(readOnly = true) @Override - public List<Integer> getTags(final String tids, final int visitor_uid, final int before, final int cnt) { - if (before > 0) { - return getJdbcTemplate().queryForList( - "SELECT messages.message_id FROM messages_tags " + - "INNER JOIN messages USING(message_id) WHERE messages_tags.tag_id IN (" + tids + ") " + - "AND messages.message_id<? AND (messages.privacy>0 OR messages.user_id=?) " + - "ORDER BY messages.message_id DESC LIMIT ?", - new Object[]{before, visitor_uid, cnt}, - Integer.class); - } else { - return getJdbcTemplate().queryForList( - "SELECT messages.message_id FROM messages_tags " + - "INNER JOIN messages USING(message_id) WHERE messages_tags.tag_id IN (" + tids + ") " + - "AND (messages.privacy>0 OR messages.user_id=?) " + - "ORDER BY messages.message_id DESC LIMIT ?", - new Object[]{visitor_uid, cnt}, Integer.class); - } + public List<Integer> getTags(final String tids, final int visitorUid, final int before, final int cnt) { + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("cnt", cnt) + .addValue("before", before) + .addValue("visitorUid", visitorUid); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT messages.message_id FROM messages_tags " + + "INNER JOIN messages USING(message_id) WHERE messages_tags.tag_id IN (" + tids + ") " + + (before > 0 ? + " AND messages.message_id < :before " : "") + + " AND (messages.privacy > 0 OR messages.user_id = :visitorUid) " + + "ORDER BY messages.message_id DESC LIMIT :cnt", + sqlParameterSource, + Integer.class); } @Transactional(readOnly = true) @Override - public List<Integer> getPlace(final int place_id, final int visitor_uid, final int before) { - if (before > 0) { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE place_id=? AND message_id<? " + - "AND (privacy>0 OR user_id=?) ORDER BY message_id DESC LIMIT 20", - new Object[]{place_id, before, visitor_uid}, - Integer.class); - } else { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE place_id=? AND (privacy>0 OR user_id=?) " + - "ORDER BY message_id DESC LIMIT 20", - new Object[]{place_id, visitor_uid}, - Integer.class); - } + public List<Integer> getPlace(final int placeId, final int visitorUid, final int before) { + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("placeId", placeId) + .addValue("before", before) + .addValue("visitorUid", visitorUid); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT message_id FROM messages WHERE place_id = :placeId " + + (before > 0 ? + " AND message_id < :before " : "") + + " AND (privacy > 0 OR user_id = :visitorUid) ORDER BY message_id DESC LIMIT 20", + sqlParameterSource, + Integer.class); } @Transactional(readOnly = true) @Override public List<Integer> getMyFeed(final int uid, final int before) { - List<Integer> mids; - if (before > 0) { - mids = getJdbcTemplate().queryForList( - "SELECT message_id FROM messages " + - "INNER JOIN subscr_users ON (subscr_users.suser_id=? AND subscr_users.user_id=messages.user_id) " + - "WHERE message_id<? AND (privacy>=0 OR (privacy>=-2 AND privacy<=-1 AND messages.user_id " + - "IN (SELECT user_id FROM wl_users WHERE wl_user_id=?))) ORDER BY message_id DESC LIMIT 20", - Integer.class, - uid, - before, - uid); - } else { - mids = getJdbcTemplate().queryForList( - "SELECT message_id FROM messages " + - "INNER JOIN subscr_users ON (subscr_users.suser_id=? " + - "AND subscr_users.user_id=messages.user_id) " + - "WHERE (privacy>=0 OR (privacy>=-2 AND privacy<=-1 AND messages.user_id " + - "IN (SELECT user_id FROM wl_users WHERE wl_user_id=?))) ORDER BY message_id DESC LIMIT 20", - Integer.class, - uid, - uid); - } - - if (before > 0) { - mids.addAll(getJdbcTemplate().queryForList( - "SELECT message_id FROM messages " + - "WHERE user_id=? AND message_id<? ORDER BY message_id DESC LIMIT 20", - Integer.class, - uid, - before)); - } else { - mids.addAll(getJdbcTemplate().queryForList( - "SELECT message_id FROM messages " + - "WHERE user_id=? ORDER BY message_id DESC LIMIT 20", - Integer.class, - uid)); - } - - Collections.sort(mids, Collections.reverseOrder()); - int remove = mids.size() - 20; - for (int i = 0; i < remove; i++) { - mids.remove(20); - } + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("uid", uid) + .addValue("before", before); + + List<Integer> mids = getNamedParameterJdbcTemplate().queryForList( + "(SELECT message_id FROM messages " + + " INNER JOIN subscr_users ON (subscr_users.suser_id = :uid AND subscr_users.user_id = messages.user_id) " + + " WHERE " + + (before > 0 ? + " message_id < :before AND " : "") + + " (privacy >= 0 OR (privacy >= -2 AND privacy <= -1" + + " AND EXISTS (SELECT 1 FROM wl_users w WHERE w.wl_user_id = :uid and w.user_id = messages.user_id)))) " + + " UNION " + + " (SELECT message_id FROM messages WHERE user_id=:uid " + + (before > 0 ? + " AND message_id < :before " : "") + + " ORDER BY message_id ASC LIMIT 20", + sqlParameterSource, + Integer.class); return mids; } @@ -529,105 +492,86 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ @Transactional(readOnly = true) @Override public List<Integer> getPrivate(final int uid, final int before) { - if (before > 0) { - return getJdbcTemplate().queryForList - ("SELECT message_id FROM messages WHERE user_id=? AND privacy<0 AND message_id<? " + - "ORDER BY message_id DESC LIMIT 20", - new Object[]{uid, before}, - Integer.class); - } else { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE user_id=? AND privacy<0 " + - "ORDER BY message_id DESC LIMIT 20", - new Object[]{uid}, - Integer.class); - } + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("uid", uid) + .addValue("before", before); + + return getNamedParameterJdbcTemplate().queryForList + ("SELECT message_id FROM messages WHERE user_id = :uid AND privacy < 0" + + (before > 0 ? + " AND message_id < :before " : "") + + "ORDER BY message_id DESC LIMIT 20", + sqlParameterSource, + Integer.class); } @Transactional(readOnly = true) @Override public List<Integer> getDiscussions(final int uid, final int before) { - if (before > 0) { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM subscr_messages WHERE suser_id=? AND message_id<? " + - "ORDER BY message_id DESC LIMIT 20", - Integer.class, - uid, - before); - } else { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM subscr_messages WHERE suser_id=? " + - "ORDER BY message_id DESC LIMIT 20", - Integer.class, - uid); - } + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("uid", uid) + .addValue("before", before); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT message_id FROM subscr_messages WHERE suser_id = :uid" + + (before > 0 ? + " AND message_id < :before " : "") + + "ORDER BY message_id DESC LIMIT 20", + sqlParameterSource, + Integer.class); } @Transactional(readOnly = true) @Override public List<Integer> getRecommended(final int uid, final int before) { - if (before > 0) { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM favorites WHERE user_id " + - "IN (SELECT user_id FROM subscr_users WHERE suser_id=?) AND message_id<? " + - "ORDER BY message_id DESC LIMIT 20", - Integer.class, - uid, - before); - } else { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM favorites WHERE user_id " + - "IN (SELECT user_id FROM subscr_users WHERE suser_id=?) " + - "ORDER BY message_id DESC LIMIT 20", - Integer.class, - uid); - } + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("uid", uid) + .addValue("before", before); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT f.message_id FROM favorites f WHERE " + + "EXISTS (SELECT 1 FROM subscr_users s WHERE s.suser_id = :uid and f.user_id = s.user_id)" + + (before > 0 ? + " AND f.message_id < :before " : "") + + "ORDER BY f.message_id DESC LIMIT 20", + sqlParameterSource, + Integer.class); } @Transactional(readOnly = true) @Override - public List<Integer> getPopular(final int visitor_uid, final int before) { - if (before > 0) { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE message_id<? AND privacy>0 " + - "AND popular>0 AND user_id NOT IN (SELECT bl_user_id FROM bl_users WHERE user_id=?) " + - "ORDER BY message_id DESC LIMIT 20", - Integer.class, - before, - visitor_uid); - } else { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE privacy>0 " + - "AND popular>0 AND user_id NOT IN (SELECT bl_user_id FROM bl_users WHERE user_id=?) " + - "ORDER BY message_id DESC LIMIT 20", - Integer.class, - visitor_uid); - } + public List<Integer> getPopular(final int visitorUid, final int before) { + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("vid", visitorUid) + .addValue("before", before); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT m.message_id FROM m.messages WHERE m.privacy > 0 " + + (before > 0 ? + " AND m.message_id < :before " : "") + + " AND m.popular > 0 AND NOT EXISTS (SELECT 1 FROM bl_users b WHERE b.user_id = :vid and b.bl_user_id = m.user_id) " + + " ORDER BY m.message_id DESC LIMIT 20", + sqlParameterSource, + Integer.class); } @Transactional(readOnly = true) @Override - public List<Integer> getPhotos(final int visitor_uid, final int before) { - if (before > 0) { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE message_id<? AND (privacy>0 OR user_id=?) " + - "AND attach IS NOT NULL AND user_id NOT IN (SELECT id from users WHERE banned=1) " + - "AND user_id NOT IN (SELECT bl_user_id FROM bl_users WHERE user_id=?) " + - "ORDER BY message_id DESC LIMIT 20", - Integer.class, - before, - visitor_uid, - visitor_uid); - } else { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE (privacy>0 OR user_id=?) " + - "AND attach IS NOT NULL AND user_id NOT IN (SELECT id from users WHERE banned=1) " + - "AND user_id NOT IN (SELECT bl_user_id FROM bl_users WHERE user_id=?) " + - "ORDER BY message_id DESC LIMIT 20", - Integer.class, - visitor_uid, - visitor_uid); - } + public List<Integer> getPhotos(final int visitorUid, final int before) { + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("vid", visitorUid) + .addValue("before", before); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT m.message_id FROM messages m WHERE (m.privacy > 0 OR m.user_id = :vid) " + + (before > 0 ? + " AND m.message_id < :before " : "") + + " AND m.attach IS NOT NULL " + + " AND NOT EXISTS (SELECT 1 from users u WHERE u.banned = 1 and u.id = m.user_id) " + + " AND NOT EXISTS (SELECT 1 FROM bl_users b WHERE b.user_id = :vid and b.bl_user_id = m.user_id) " + + " ORDER BY m.message_id DESC LIMIT 20", + sqlParameterSource, + Integer.class); } @Transactional(readOnly = true) @@ -637,22 +581,19 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ if (before > 0) { mids = sqlSearch.queryForList( - "SELECT id AS message_id FROM messages WHERE MATCH(?) AND id<? " + - "ORDER BY id DESC LIMIT 25", + "SELECT id AS message_id FROM messages WHERE MATCH(?) AND id < ? ORDER BY id DESC LIMIT 25", Integer.class, - search, - before); + search, before); } else { mids = sqlSearch.queryForList( - "SELECT id AS message_id FROM messages WHERE MATCH(?) " + - "ORDER BY id DESC LIMIT 25", + "SELECT id AS message_id FROM messages WHERE MATCH(?) ORDER BY id DESC LIMIT 25", Integer.class, search); } if (mids.size() > 0) { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE message_id " + - "IN (" + StringUtils.arrayToCommaDelimitedString(mids.toArray()) + ") AND privacy>0 ORDER BY message_id DESC LIMIT 20", + return getNamedParameterJdbcTemplate().queryForList( + "SELECT message_id FROM messages WHERE message_id IN (:ids) AND privacy > 0 ORDER BY message_id DESC LIMIT 20", + new MapSqlParameterSource("ids", mids), Integer.class); } return mids; @@ -660,83 +601,72 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ @Transactional(readOnly = true) @Override - public List<Integer> getUserBlog(final int UID, final int privacy, final int before) { - if (before > 0) { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE user_id=? AND message_id<? AND privacy>=" + - privacy + " ORDER BY message_id DESC LIMIT 20", - Integer.class, - UID, - before); - } else { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE user_id=? AND privacy>=" + privacy + - " ORDER BY message_id DESC LIMIT 20", - Integer.class, - UID); - } + public List<Integer> getUserBlog(final int uid, final int privacy, final int before) { + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("uid", uid) + .addValue("privacy", privacy) + .addValue("before", before); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT message_id FROM messages WHERE user_id = :uid" + + (before > 0 ? + " AND message_id < :before" : "") + + " AND privacy >= :privacy ORDER BY message_id DESC LIMIT 20", + sqlParameterSource, + Integer.class); } @Transactional(readOnly = true) @Override - public List<Integer> getUserTag(final int UID, final int TID, final int privacy, final int before) { - if (before > 0) { - return getJdbcTemplate().queryForList( - "SELECT messages.message_id FROM messages_tags INNER JOIN messages " + - "USING(message_id) WHERE messages.user_id=? AND messages_tags.tag_id=? " + - "AND messages.message_id<? AND messages.privacy>=" + privacy + - " ORDER BY messages.message_id DESC LIMIT 20", - Integer.class, - UID, - TID, - before); - } else { - return getJdbcTemplate().queryForList( - "SELECT messages.message_id FROM messages_tags INNER JOIN messages " + - "USING(message_id) WHERE messages.user_id=? AND messages_tags.tag_id=? " + - "AND messages.privacy>=" + privacy + " ORDER BY messages.message_id DESC LIMIT 20", - Integer.class, - UID, - TID); - } + public List<Integer> getUserTag(final int uid, final int tid, final int privacy, final int before) { + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("uid", uid) + .addValue("tid", tid) + .addValue("privacy", privacy) + .addValue("before", before); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT messages.message_id FROM messages_tags INNER JOIN messages " + + " USING (message_id) WHERE messages.user_id = :uid AND messages_tags.tag_id = :tid " + + (before > 0 ? + " AND messages.message_id < :before " : "") + + " AND messages.privacy >= :privacy ORDER BY messages.message_id DESC LIMIT 20", + sqlParameterSource, + Integer.class); } @Transactional(readOnly = true) @Override - public List<Integer> getUserRecommendations(final int UID, final int before) { - if (before > 0) { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM favorites " - + "WHERE user_id=? AND message_id<? " - + "ORDER BY message_id DESC LIMIT 20", - Integer.class, - UID, - before); - } else { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM favorites " - + "WHERE user_id=? ORDER BY message_id DESC LIMIT 20", - Integer.class, - UID); - } + public List<Integer> getUserRecommendations(final int uid, final int before) { + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("uid", uid) + .addValue("before", before); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT message_id FROM favorites " + + " WHERE user_id = :uid " + + (before > 0 ? + " AND message_id < :before " : "") + + " ORDER BY message_id DESC LIMIT 20", + sqlParameterSource, + Integer.class); } @Transactional(readOnly = true) @Override - public List<Integer> getUserPhotos(final int UID, final int privacy, final int before) { - if (before > 0) { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE user_id=? AND message_id<? AND privacy>=" + - privacy + " AND attach IS NOT NULL ORDER BY message_id DESC LIMIT 20", - new Object[]{UID, before}, - Integer.class); - } else { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE user_id=? AND privacy>=" + privacy + - " AND attach IS NOT NULL ORDER BY message_id DESC LIMIT 20", - new Object[]{UID}, - Integer.class); - } + public List<Integer> getUserPhotos(final int uid, final int privacy, final int before) { + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("uid", uid) + .addValue("privacy", privacy) + .addValue("before", before); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT message_id FROM messages WHERE user_id = :uid " + + (before > 0 ? + " AND message_id < :before " : "") + + " AND privacy >= :privacy AND attach IS NOT NULL ORDER BY message_id DESC LIMIT 20", + sqlParameterSource, + Integer.class); } @Transactional(readOnly = true) @@ -759,9 +689,10 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ } if (mids.size() > 0) { - return getJdbcTemplate().queryForList( - "SELECT message_id FROM messages WHERE message_id IN (" + - StringUtils.arrayToCommaDelimitedString(mids.toArray()) + ") AND privacy>=" + privacy + " ORDER BY message_id DESC", + return getNamedParameterJdbcTemplate().queryForList( + "SELECT message_id FROM messages WHERE message_id IN (:ids) AND privacy >= :privacy ORDER BY message_id DESC", + new MapSqlParameterSource("ids", mids) + .addValue("privacy", privacy), Integer.class); } return mids; @@ -769,9 +700,9 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ @Transactional(readOnly = true) @Override - public List<com.juick.Message> getMessages(final List<Integer> mids) { - if (!mids.isEmpty()) { - return getJdbcTemplate().query( + public List<com.juick.Message> getMessages(final Collection<Integer> mids) { + if (CollectionUtils.isNotEmpty(mids)) { + return getNamedParameterJdbcTemplate().query( "SELECT messages.message_id, 0 as rid, 0 as replyto, " + "messages.user_id,users.nick, 0 as banned, " + "TIMESTAMPDIFF(MINUTE,messages.ts,NOW())," @@ -783,9 +714,8 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ + "FROM (messages INNER JOIN messages_txt " + "ON messages.message_id=messages_txt.message_id) " + "INNER JOIN users ON messages.user_id=users.id " - + "WHERE messages.message_id " - + "IN (" + StringUtils.arrayToCommaDelimitedString(mids.toArray()) + ") " - + "ORDER BY messages.message_id DESC", + + "WHERE messages.message_id IN (:ids) ORDER BY messages.message_id DESC", + new MapSqlParameterSource("ids", mids), new MessageMapper()); } return Collections.emptyList(); @@ -794,62 +724,76 @@ public class MessagesServiceImpl extends BaseJdbcService implements MessagesServ @Transactional(readOnly = true) @Override public List<com.juick.Message> getReplies(final int mid) { - return getJdbcTemplate().query( - "SELECT ? as mid, replies.reply_id,replies.replyto, " + - "replies.user_id,users.nick,users.banned, " + - "TIMESTAMPDIFF(MINUTE,replies.ts,NOW()),replies.ts," + - "0 as readonly, 0 as privacy, 0 as replies," + - "replies.attach, 0 as place_id, 0 as lat," + - "0 as lon, 0 as likes, 0 as hidden," + - "NULL as tags,NULL as repliesby, replies.txt, " + + return getNamedParameterJdbcTemplate().query( + "SELECT replies.message_id as mid, replies.reply_id, replies.replyto, " + + "replies.user_id, users.nick, users.banned, " + + "TIMESTAMPDIFF(MINUTE, replies.ts, NOW()), replies.ts, " + + "0 as readonly, 0 as privacy, 0 as replies, " + + "replies.attach, 0 as place_id, 0 as lat, " + + "0 as lon, 0 as likes, 0 as hidden, " + + "NULL as tags, NULL as repliesby, replies.txt, " + "IFNULL(qw.txt, t.txt) as q " + "FROM replies INNER JOIN users " + - "ON replies.user_id=users.id " + - "LEFT JOIN replies qw ON replies.message_id=qw.message_id and replies.replyto=qw.reply_id " + - "LEFT JOIN messages_txt t on replies.message_id=t.message_id " + - "WHERE replies.message_id=? " + - "ORDER BY replies.reply_id ASC", - new MessageMapper(), - mid, - mid); + "ON replies.user_id = users.id " + + "LEFT JOIN replies qw ON replies.message_id = qw.message_id and replies.replyto = qw.reply_id " + + "LEFT JOIN messages_txt t on replies.message_id = t.message_id " + + "WHERE replies.message_id = :mid ORDER BY replies.reply_id ASC", + new MapSqlParameterSource("mid", mid), + new MessageMapper()); } @Transactional @Override public boolean setMessagePopular(final int mid, final int popular) { - boolean ret; + int ret; + MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("mid", mid) + .addValue("popular", popular); + switch (popular) { case -2: - ret = getJdbcTemplate().update("UPDATE messages SET hidden=1 WHERE message_id=?", mid) > 0; + ret = getNamedParameterJdbcTemplate().update( + "UPDATE messages SET hidden = 1 WHERE message_id = :mid", + sqlParameterSource); break; case -1: - ret = getJdbcTemplate().update("UPDATE messages SET popular=0 WHERE message_id=?", mid) > 0; - break; + sqlParameterSource.addValue("popular", 0); default: - ret = getJdbcTemplate().update("UPDATE messages SET popular=? WHERE message_id=?", popular, mid) > 0; + ret = getNamedParameterJdbcTemplate().update( + "UPDATE messages SET popular = :popular WHERE message_id = :mid", + sqlParameterSource); break; } - if (popular == -1) { - ret = getJdbcTemplate().update("INSERT INTO top_ignore_messages VALUES (?)", mid) > 0; - } - return ret; + + if (popular == -1) + ret = getNamedParameterJdbcTemplate().update( + "INSERT INTO top_ignore_messages VALUES (:mid)", + sqlParameterSource); + + return ret > 0; } @Transactional @Override public boolean setMessagePrivacy(final int mid) { - return getJdbcTemplate().update("UPDATE messages SET privacy=1 WHERE message_id=?", - mid) > 0; + return getJdbcTemplate().update("UPDATE messages SET privacy=1 WHERE message_id=?", mid) > 0; } @Transactional @Override public boolean deleteMessage(final int uid, final int mid) { - if (getJdbcTemplate().update("DELETE FROM messages WHERE message_id=? AND user_id=?", mid, uid) > 0) { - getJdbcTemplate().update("DELETE FROM messages_txt WHERE message_id=?", mid); - getJdbcTemplate().update("DELETE FROM replies WHERE message_id=?", mid); - getJdbcTemplate().update("DELETE FROM subscr_messages WHERE message_id=?", mid); - getJdbcTemplate().update("DELETE FROM messages_tags WHERE message_id=?", mid); + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("mid", mid) + .addValue("uid", uid); + + if (getNamedParameterJdbcTemplate().update( + "DELETE FROM messages WHERE message_id = :mid AND user_id = :uid", sqlParameterSource) > 0) { + + getNamedParameterJdbcTemplate().update("DELETE FROM messages_txt WHERE message_id = :mid", sqlParameterSource); + getNamedParameterJdbcTemplate().update("DELETE FROM replies WHERE message_id = :mid", sqlParameterSource); + getNamedParameterJdbcTemplate().update("DELETE FROM subscr_messages WHERE message_id = :mid", sqlParameterSource); + getNamedParameterJdbcTemplate().update("DELETE FROM messages_tags WHERE message_id = :mid", sqlParameterSource); + return true; } return false; diff --git a/juick-server/src/main/java/com/juick/service/PMQueriesService.java b/juick-server/src/main/java/com/juick/service/PMQueriesService.java index df332870..e20bb3a5 100644 --- a/juick-server/src/main/java/com/juick/service/PMQueriesService.java +++ b/juick-server/src/main/java/com/juick/service/PMQueriesService.java @@ -8,7 +8,7 @@ import java.util.List; * Created by aalexeev on 11/13/16. */ public interface PMQueriesService { - boolean createPM(int uid_from, int uid_to, String body); + boolean createPM(int uidFrom, int uid_to, String body); boolean addPMinRoster(int uid, String jid); @@ -16,11 +16,11 @@ public interface PMQueriesService { boolean havePMinRoster(int uid, String jid); - String getLastView(int uid_from, int uid_to); + String getLastView(int uidFrom, int uidTo); List<User> getPMLastConversationsUsers(int uid, int cnt); - List<com.juick.Message> getPMMessages(int uid, int uid_to); + List<com.juick.Message> getPMMessages(int uid, int uidTo); List<com.juick.Message> getLastPMInbox(int uid); diff --git a/juick-server/src/main/java/com/juick/service/PMQueriesServiceImpl.java b/juick-server/src/main/java/com/juick/service/PMQueriesServiceImpl.java index 5c28c2ba..e6a8617d 100644 --- a/juick-server/src/main/java/com/juick/service/PMQueriesServiceImpl.java +++ b/juick-server/src/main/java/com/juick/service/PMQueriesServiceImpl.java @@ -1,8 +1,9 @@ package com.juick.service; import com.juick.User; -import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; +import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @@ -22,17 +23,16 @@ public class PMQueriesServiceImpl extends BaseJdbcService implements PMQueriesSe @Transactional @Override - public boolean createPM(final int uid_from, final int uid_to, final String body) { + public boolean createPM(final int uidFrom, final int uid_to, final String body) { boolean ret = getJdbcTemplate().update( - "INSERT INTO pm(user_id,user_id_to,txt) VALUES (?,?,?)", - uid_from, uid_to, body) > 0; + "INSERT INTO pm(user_id, user_id_to, txt) VALUES (?, ?, ?)", + uidFrom, uid_to, body) > 0; if (ret) { getJdbcTemplate().update( - "INSERT INTO pm_streams(user_id,user_id_to,lastmessage,unread) " - + "VALUES (?,?,NOW(),1) " - + "ON DUPLICATE KEY UPDATE lastmessage=NOW(),unread=unread+1", - uid_from, uid_to); + "INSERT INTO pm_streams(user_id, user_id_to, lastmessage, unread) VALUES (?, ?, NOW(), 1) " + + "ON DUPLICATE KEY UPDATE lastmessage = NOW(), unread = unread + 1", + uidFrom, uid_to); } return ret; } @@ -41,40 +41,36 @@ public class PMQueriesServiceImpl extends BaseJdbcService implements PMQueriesSe @Override public boolean addPMinRoster(final int uid, final String jid) { return getJdbcTemplate().update( - "INSERT INTO pm_inroster(user_id,jid) VALUES (?,?)", - uid, jid) > 0; + "INSERT INTO pm_inroster(user_id, jid) VALUES (?, ?)", uid, jid) > 0; } @Transactional @Override public boolean removePMinRoster(final int uid, final String jid) { return getJdbcTemplate().update( - "DELETE FROM pm_inroster WHERE user_id=? AND jid=?", uid, jid) > 0; + "DELETE FROM pm_inroster WHERE user_id = ? AND jid = ?", uid, jid) > 0; } @Transactional @Override public boolean havePMinRoster(final int uid, final String jid) { List<Integer> res = getJdbcTemplate().queryForList( - "SELECT 1 FROM pm_inroster WHERE user_id=? AND jid=?", + "SELECT 1 FROM pm_inroster WHERE user_id = ? AND jid = ?", Integer.class, - uid, - jid); + uid, jid); return res.size() > 0; } @Transactional(readOnly = true) @Override - public String getLastView(final int uid_from, final int uid_to) { - try { - return getJdbcTemplate().queryForObject( - "SELECT lastview FROM pm_streams WHERE user_id=? AND user_id_to=?", - String.class, - uid_from, - uid_to); - } catch (EmptyResultDataAccessException e) { - return null; - } + public String getLastView(final int uidFrom, final int uidTo) { + List<String> list = getJdbcTemplate().queryForList( + "SELECT lastview FROM pm_streams WHERE user_id = ? AND user_id_to = ?", + String.class, + uidFrom, uidTo); + + return list.isEmpty() ? + null : list.get(0); } @Transactional(readOnly = true) @@ -84,7 +80,7 @@ public class PMQueriesServiceImpl extends BaseJdbcService implements PMQueriesSe "SELECT pm_streams.user_id, users.nick, pm_streams.unread FROM pm_streams " + "INNER JOIN users ON users.id = pm_streams.user_id " + "WHERE pm_streams.user_id_to=? " - + "ORDER BY pm_streams.unread DESC, pm_streams.lastmessage DESC LIMIT " + cnt, + + "ORDER BY pm_streams.unread DESC, pm_streams.lastmessage DESC LIMIT ?", (rs, rowNum) -> { com.juick.User u = new com.juick.User(); u.setUid(rs.getInt(1)); @@ -92,16 +88,20 @@ public class PMQueriesServiceImpl extends BaseJdbcService implements PMQueriesSe u.setUnreadCount(rs.getInt(3)); return u; }, - uid); + uid, cnt); } @Transactional @Override - public List<com.juick.Message> getPMMessages(final int uid, final int uid_to) { - List<com.juick.Message> msgs = getJdbcTemplate().query( - "SELECT user_id,txt,ts FROM pm " - + "WHERE (user_id=? AND user_id_to=?) " - + "OR (user_id_to=? AND user_id=?) ORDER BY ts DESC LIMIT 20", + public List<com.juick.Message> getPMMessages(final int uid, final int uidTo) { + SqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("uid", uid) + .addValue("uidTo", uidTo); + + List<com.juick.Message> msgs = getNamedParameterJdbcTemplate().query( + "SELECT user_id, txt,ts FROM pm WHERE (user_id = :uid AND user_id_to = :uidTo) " + + "OR (user_id_to = :uid AND user_id = :uidTo) ORDER BY ts DESC LIMIT 20", + sqlParameterSource, (rs, rowNum) -> { com.juick.Message msg = new com.juick.Message(); int uuid = rs.getInt(1); @@ -110,16 +110,11 @@ public class PMQueriesServiceImpl extends BaseJdbcService implements PMQueriesSe msg.setText(rs.getString(2)); msg.setDate(rs.getTimestamp(3)); return msg; - }, - uid, - uid_to, - uid, - uid_to); - - getJdbcTemplate().update( - "UPDATE pm_streams SET lastview=NOW(),unread=0 WHERE user_id_to=? AND user_id=?", - uid, - uid_to); + }); + + getNamedParameterJdbcTemplate().update( + "UPDATE pm_streams SET lastview = NOW(), unread = 0 WHERE user_id_to = :uid AND user_id = :uidTo", + sqlParameterSource); return msgs; } diff --git a/juick-server/src/main/java/com/juick/service/PrivacyQueriesServiceImpl.java b/juick-server/src/main/java/com/juick/service/PrivacyQueriesServiceImpl.java index 7dac4073..4f19c70f 100644 --- a/juick-server/src/main/java/com/juick/service/PrivacyQueriesServiceImpl.java +++ b/juick-server/src/main/java/com/juick/service/PrivacyQueriesServiceImpl.java @@ -23,34 +23,32 @@ public class PrivacyQueriesServiceImpl extends BaseJdbcService implements Privac @Override public PrivacyResult blacklistUser(final User user, final User target) { int result = getJdbcTemplate().update( - "DELETE FROM bl_users WHERE user_id=? AND bl_user_id=?", - user.getUid(), - target.getUid()); - if (result > 0) { + "DELETE FROM bl_users WHERE user_id = ? AND bl_user_id = ?", + user.getUid(), target.getUid()); + + if (result > 0) return PrivacyResult.Removed; - } else { - getJdbcTemplate().update( - "INSERT INTO bl_users(user_id,bl_user_id) VALUES (?,?)", - user.getUid(), - target.getUid()); - return PrivacyResult.Added; - } + + getJdbcTemplate().update( + "INSERT INTO bl_users(user_id, bl_user_id) VALUES (?, ?)", + user.getUid(), target.getUid()); + + return PrivacyResult.Added; } @Override public PrivacyResult blacklistTag(final User user, final Tag tag) { int result = getJdbcTemplate().update( - "DELETE FROM bl_tags WHERE user_id=? AND tag_id=?", - user.getUid(), - tag.TID); - if (result > 0) { + "DELETE FROM bl_tags WHERE user_id = ? AND tag_id = ?", + user.getUid(), tag.TID); + + if (result > 0) return PrivacyResult.Removed; - } else { - getJdbcTemplate().update( - "INSERT INTO bl_tags(user_id,tag_id) VALUES (?,?)", - user.getUid(), - tag.TID); - return PrivacyResult.Added; - } + + getJdbcTemplate().update( + "INSERT INTO bl_tags(user_id, tag_id) VALUES (?, ?)", + user.getUid(), tag.TID); + + return PrivacyResult.Added; } } diff --git a/juick-server/src/main/java/com/juick/service/PushQueriesService.java b/juick-server/src/main/java/com/juick/service/PushQueriesService.java index fe956c3a..2e2ac390 100644 --- a/juick-server/src/main/java/com/juick/service/PushQueriesService.java +++ b/juick-server/src/main/java/com/juick/service/PushQueriesService.java @@ -1,5 +1,6 @@ package com.juick.service; +import java.util.Collection; import java.util.List; /** @@ -8,15 +9,15 @@ import java.util.List; public interface PushQueriesService { List<String> getAndroidRegID(int uid); - List<String> getAndroidTokens(List<Integer> uids); + List<String> getAndroidTokens(Collection<Integer> uids); List<String> getWinPhoneURL(int uid); - List<String> getWindowsTokens(List<Integer> uids); + List<String> getWindowsTokens(Collection<Integer> uids); List<String> getAPNSToken(int uid); - List<String> getAPNSTokens(List<Integer> uids); + List<String> getAPNSTokens(Collection<Integer> uids); boolean deleteAPNSToken(String token); } diff --git a/juick-server/src/main/java/com/juick/service/PushQueriesServiceImpl.java b/juick-server/src/main/java/com/juick/service/PushQueriesServiceImpl.java index 9bbadef6..b11f0a79 100644 --- a/juick-server/src/main/java/com/juick/service/PushQueriesServiceImpl.java +++ b/juick-server/src/main/java/com/juick/service/PushQueriesServiceImpl.java @@ -1,11 +1,14 @@ package com.juick.service; +import org.apache.commons.collections4.CollectionUtils; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; -import org.springframework.util.StringUtils; import javax.inject.Inject; +import java.util.Collection; +import java.util.Collections; import java.util.List; /** @@ -29,10 +32,13 @@ public class PushQueriesServiceImpl extends BaseJdbcService implements PushQueri } @Override - public List<String> getAndroidTokens(final List<Integer> uids) { - return getJdbcTemplate().queryForList( - "SELECT regid FROM android INNER JOIN users " + - "ON (users.id=android.user_id) WHERE users.id IN (" + StringUtils.collectionToCommaDelimitedString(uids) + ")", + public List<String> getAndroidTokens(final Collection<Integer> uids) { + if (CollectionUtils.isEmpty(uids)) + return Collections.emptyList(); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT regid FROM android INNER JOIN users ON (users.id = android.user_id) WHERE users.id IN (:ids)", + new MapSqlParameterSource("ids", uids), String.class); } @@ -45,10 +51,13 @@ public class PushQueriesServiceImpl extends BaseJdbcService implements PushQueri } @Override - public List<String> getWindowsTokens(final List<Integer> uids) { - return getJdbcTemplate().queryForList( - "SELECT url FROM winphone INNER JOIN users " + - "ON (users.id=winphone.user_id) WHERE users.id IN (" + StringUtils.collectionToCommaDelimitedString(uids) + ")", + public List<String> getWindowsTokens(final Collection<Integer> uids) { + if (CollectionUtils.isEmpty(uids)) + return Collections.emptyList(); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT url FROM winphone INNER JOIN users ON (users.id=winphone.user_id) WHERE users.id IN (:ids)", + new MapSqlParameterSource("ids", uids), String.class); } @@ -66,10 +75,13 @@ public class PushQueriesServiceImpl extends BaseJdbcService implements PushQueri } @Override - public List<String> getAPNSTokens(final List<Integer> uids) { - return getJdbcTemplate().queryForList( - "SELECT token FROM ios INNER JOIN users " + - "ON (users.id=ios.user_id) WHERE users.id IN (" + StringUtils.collectionToCommaDelimitedString(uids) + ")", + public List<String> getAPNSTokens(final Collection<Integer> uids) { + if (CollectionUtils.isEmpty(uids)) + return Collections.emptyList(); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT token FROM ios INNER JOIN users ON (users.id = ios.user_id) WHERE users.id IN (:ids)", + new MapSqlParameterSource("ids", uids), String.class); } } diff --git a/juick-server/src/main/java/com/juick/service/ShowQueriesServiceImpl.java b/juick-server/src/main/java/com/juick/service/ShowQueriesServiceImpl.java index 2ddfeb84..50e0d243 100644 --- a/juick-server/src/main/java/com/juick/service/ShowQueriesServiceImpl.java +++ b/juick-server/src/main/java/com/juick/service/ShowQueriesServiceImpl.java @@ -2,10 +2,12 @@ package com.juick.service; import com.juick.User; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; +import java.util.Collections; import java.util.List; /** @@ -22,19 +24,19 @@ public class ShowQueriesServiceImpl extends BaseJdbcService implements ShowQueri @Override public List<String> getRecommendedUsers(final User forUser) { - return getJdbcTemplate().queryForList( - "SELECT users.nick FROM subscr_users INNER JOIN users " + - "ON subscr_users.user_id=users.id " + - "WHERE subscr_users.user_id NOT IN (SELECT user_id FROM subscr_users WHERE suser_id=?) " + - "AND subscr_users.suser_id IN (SELECT user_id FROM subscr_users WHERE suser_id=?) " + - "AND subscr_users.user_id NOT IN (SELECT bl_user_id FROM bl_users WHERE user_id=?) " + - "AND subscr_users.user_id!=? AND users.lastmessage>UNIX_TIMESTAMP()-259200 " + - "GROUP BY subscr_users.user_id ORDER BY count(*) DESC LIMIT 10", - String.class, - forUser.getUid(), - forUser.getUid(), - forUser.getUid(), - forUser.getUid()); + if (forUser == null) + return Collections.emptyList(); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT users.nick FROM subscr_users su1 INNER JOIN users u " + + "ON su1.user_id = u.id " + + "WHERE NOT EXISTS (SELECT 1 FROM subscr_users su2 WHERE su2.suser_id = :uid and su1.user_id = su2.user_id) " + + "AND EXISTS (SELECT 1 FROM subscr_users su3 WHERE su3.suser_id = :uid and su3.user_id = su1.suser_id ) " + + "AND NOT EXISTS (SELECT 1 FROM bl_users b WHERE b.user_id = :uid and su1.user_id = b.bl_user_id) " + + "AND su1.user_id != :uid AND u.lastmessage > UNIX_TIMESTAMP() - 259200 " + + "GROUP BY su1.user_id ORDER BY count(*) DESC LIMIT 10", + new MapSqlParameterSource("uid", forUser.getUid()), + String.class); } @Override diff --git a/juick-server/src/main/java/com/juick/service/SubscriptionServiceImpl.java b/juick-server/src/main/java/com/juick/service/SubscriptionServiceImpl.java index 7e6b9d0a..fc7c239d 100644 --- a/juick-server/src/main/java/com/juick/service/SubscriptionServiceImpl.java +++ b/juick-server/src/main/java/com/juick/service/SubscriptionServiceImpl.java @@ -3,15 +3,18 @@ package com.juick.service; import com.juick.Tag; import com.juick.User; import com.juick.server.helpers.NotifyOpts; -import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import javax.inject.Inject; -import java.util.*; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import java.util.stream.Collectors; /** @@ -36,21 +39,13 @@ public class SubscriptionServiceImpl extends BaseJdbcService implements Subscrip @Transactional(readOnly = true) @Override public List<String> getJIDSubscribedToUser(final int uid, final boolean friendsonly) { - if (friendsonly == false) { - return getJdbcTemplate().queryForList( - "SELECT jids.jid FROM subscr_users INNER JOIN jids " + - "ON (subscr_users.user_id=? AND subscr_users.suser_id=jids.user_id) WHERE jids.active=1", - String.class, - uid); - } else { - return getJdbcTemplate().queryForList( - "SELECT jids.jid FROM subscr_users INNER JOIN jids " + - "ON (subscr_users.user_id=? AND subscr_users.suser_id=jids.user_id) WHERE jids.active=1 " + - "AND jids.user_id IN (SELECT wl_user_id FROM wl_users WHERE user_id=?)", - String.class, - uid, - uid); - } + return getNamedParameterJdbcTemplate().queryForList( + "SELECT jids.jid FROM subscr_users INNER JOIN jids " + + "ON (subscr_users.user_id = :uid AND subscr_users.suser_id = jids.user_id) WHERE jids.active = 1 " + + (friendsonly ? + " AND EXISTS (SELECT 1 FROM wl_users w WHERE w.user_id = :uid and jids.user_id = w.wl_user_id)" : ""), + new MapSqlParameterSource("uid", uid), + String.class); } @Transactional(readOnly = true) @@ -61,7 +56,11 @@ public class SubscriptionServiceImpl extends BaseJdbcService implements Subscrip List<User> userids = userService.getUserReaders(uid); Set<Integer> set = new HashSet<>(); - set.addAll(userids.stream().map(User::getUid).collect(Collectors.toList())); + set.addAll( + userids.stream() + .map(User::getUid) + .collect(Collectors.toList())); + List<Integer> tags = messagesService.getMessageTagsIDs(mid); if (tags.size() > 0) { String tagsStr = StringUtils.arrayToCommaDelimitedString(tags.toArray()); @@ -71,7 +70,7 @@ public class SubscriptionServiceImpl extends BaseJdbcService implements Subscrip " AND suser_id NOT IN (SELECT user_id FROM bl_tags WHERE tag_id IN (" + tagsStr + "))", Integer.class, uid, author.getUid()); set.addAll(tagUsers); } - return userService.getUsersByID(new ArrayList<>(set)); + return userService.getUsersByID(set); } @Transactional(readOnly = true) @@ -80,13 +79,12 @@ public class SubscriptionServiceImpl extends BaseJdbcService implements Subscrip List<Integer> userids = getJdbcTemplate().queryForList( "SELECT suser_id FROM subscr_messages WHERE message_id=? AND suser_id!=?", Integer.class, - mid, - ignore_uid); - if (userids.size() > 0) { + mid, ignore_uid); + + if (!userids.isEmpty()) return userService.getUsersByID(userids); - } else { - return Collections.emptyList(); - } + + return Collections.emptyList(); } @Transactional(readOnly = true) @@ -94,20 +92,27 @@ public class SubscriptionServiceImpl extends BaseJdbcService implements Subscrip public List<User> getUsersSubscribedToUserRecommendations(final int uid, final int mid, final int muid) { List<Integer> tags = messagesService.getMessageTagsIDs(mid); - String query = "SELECT suser_id FROM subscr_users WHERE user_id=" + uid; - query += " AND user_id NOT IN (SELECT user_id FROM bl_users WHERE bl_user_id=" + muid + ")"; - query += " AND user_id NOT IN (SELECT suser_id FROM subscr_users WHERE user_id=" + muid + ")"; - query += " AND user_id NOT IN (SELECT suser_id FROM subscr_messages WHERE message_id=" + mid + ")"; - query += " AND user_id NOT IN (SELECT user_id FROM favorites WHERE message_id=" + mid + ")"; - query += " AND user_id NOT IN (SELECT subscr_users.suser_id FROM subscr_users INNER JOIN favorites ON (favorites.message_id=" + mid + " AND subscr_users.user_id=favorites.user_id AND favorites.user_id!=" + uid + "))"; + String query = "SELECT s.suser_id FROM subscr_users s WHERE s.user_id = :uid " + + " AND NOT EXISTS (SELECT 1 FROM bl_users b WHERE b.bl_user_id = :muid and b.user_id = s.user_id) " + + " AND NOT EXISTS (SELECT 1 FROM subscr_users s1 WHERE s1.user_id = :muid AND s.user_id = s1.suser_id) " + + " AND NOT EXISTS (SELECT 1 FROM subscr_messages sm WHERE sm.message_id = :mid AND s.user_id = sm.suser_id) " + + " AND NOT EXISTS (SELECT 1 FROM favorites WHERE f.message_id = :mid AND f.user_id = s.user_id) " + + " AND s.user_id NOT IN (SELECT s2.suser_id FROM subscr_users s2 " + + " INNER JOIN favorites f ON (f.message_id = :mid AND s2.user_id = f.user_id AND f.user_id != :uid))"; + + MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource() + .addValue("uid", uid) + .addValue("muid", muid) + .addValue("mid", mid); if (!tags.isEmpty()) { - String tagsStr = StringUtils.arrayToCommaDelimitedString(tags.toArray()); - query += " AND user_id NOT IN (SELECT suser_id FROM subscr_tags WHERE tag_id IN (" + tagsStr + "))"; - query += " AND user_id NOT IN (SELECT user_id FROM bl_tags WHERE tag_id IN (" + tagsStr + "))"; + sqlParameterSource.addValue("ids", tags); + query += " AND NOT EXISTS (SELECT 1 FROM subscr_tags st WHERE st.tag_id IN (:ids) AND s.user_id = st.suser_id) " + + " AND NOT EXISTS (SELECT 1 FROM bl_tags b WHERE b.tag_id IN (:ids) AND s.user_id = b.user_id)"; } - List<Integer> userids = getJdbcTemplate().queryForList(query, Integer.class); + List<Integer> userids = getNamedParameterJdbcTemplate().queryForList( + query, sqlParameterSource, Integer.class); return userService.getUsersByID(userids); } @@ -116,79 +121,80 @@ public class SubscriptionServiceImpl extends BaseJdbcService implements Subscrip @Override public boolean subscribeMessage(final int mid, final int vuid) { return getJdbcTemplate().update( - "INSERT IGNORE INTO subscr_messages(suser_id,message_id) VALUES (" + vuid + "," + mid + ")") == 1; + "INSERT IGNORE INTO subscr_messages(suser_id, message_id) VALUES (?, ?)", vuid, mid) == 1; } @Transactional @Override public boolean unSubscribeMessage(final int mid, final int vuid) { return getJdbcTemplate().update( - "DELETE FROM subscr_messages WHERE message_id=? AND suser_id=?", - mid, vuid) > 0; + "DELETE FROM subscr_messages WHERE message_id=? AND suser_id=?", mid, vuid) > 0; } @Transactional @Override public boolean subscribeUser(final User user, final User toUser) { return getJdbcTemplate().update( - "INSERT IGNORE INTO subscr_users(user_id,suser_id) VALUES (?,?)", - toUser.getUid(), user.getUid()) == 1; + "INSERT IGNORE INTO subscr_users(user_id,suser_id) VALUES (?,?)", toUser.getUid(), user.getUid()) == 1; } @Transactional @Override public boolean unSubscribeUser(final User user, final User fromUser) { return getJdbcTemplate().update( - "DELETE FROM subscr_users WHERE suser_id=? AND user_id=?", - user.getUid(), fromUser.getUid()) > 0; + "DELETE FROM subscr_users WHERE suser_id=? AND user_id=?", user.getUid(), fromUser.getUid()) > 0; } @Transactional @Override public boolean subscribeTag(final User user, final Tag toTag) { return getJdbcTemplate().update( - "INSERT IGNORE INTO subscr_tags(tag_id,suser_id) VALUES (?,?)", - toTag.TID, user.getUid()) == 1; + "INSERT IGNORE INTO subscr_tags(tag_id,suser_id) VALUES (?,?)", toTag.TID, user.getUid()) == 1; } @Transactional @Override public boolean unSubscribeTag(final User user, final Tag toTag) { return getJdbcTemplate().update( - "DELETE FROM subscr_tags WHERE tag_id=? AND suser_id=?", - toTag.TID, user.getUid()) > 0; + "DELETE FROM subscr_tags WHERE tag_id=? AND suser_id=?", toTag.TID, user.getUid()) > 0; } @Transactional(readOnly = true) @Override public NotifyOpts getNotifyOptions(final User user) { - try { - return getJdbcTemplate().queryForObject( - "SELECT jnotify,subscr_notify,recommendations FROM useroptions WHERE user_id=?", - (rs, num) -> { - NotifyOpts options = new NotifyOpts(); - options.setRepliesEnabled(rs.getInt(1) > 0); - options.setSubscriptionsEnabled(rs.getInt(2) > 0); - options.setRecommendationsEnabled(rs.getInt(3) > 0); - return options; - }, - user.getUid()); - } catch (EmptyResultDataAccessException e) { - return new NotifyOpts(); - } + List<NotifyOpts> list = getJdbcTemplate().query( + "SELECT jnotify,subscr_notify,recommendations FROM useroptions WHERE user_id=?", + (rs, num) -> { + NotifyOpts options = new NotifyOpts(); + options.setRepliesEnabled(rs.getInt(1) > 0); + options.setSubscriptionsEnabled(rs.getInt(2) > 0); + options.setRecommendationsEnabled(rs.getInt(3) > 0); + return options; + }, + user.getUid()); + + return list.isEmpty() ? + new NotifyOpts() : list.get(0); } @Transactional @Override public boolean setNotifyOptions(final User user, final NotifyOpts options) { - return getJdbcTemplate().update( - "UPDATE useroptions SET jnotify=? WHERE user_id=?", options.isRepliesEnabled() ? 1 : 0, - user.getUid()) > 0 && - getJdbcTemplate().update( - "UPDATE useroptions SET subscr_notify=? WHERE user_id=?", options.isSubscriptionsEnabled() ? 1 : 0, - user.getUid()) > 0 && - getJdbcTemplate().update( - "UPDATE useroptions SET recommendations=? WHERE user_id=?", options.isRecommendationsEnabled() ? 1 : 0, - user.getUid()) > 0; + int jnotify = getJdbcTemplate().update( + "UPDATE useroptions SET jnotify=? WHERE user_id=?", + options.isRepliesEnabled() ? 1 : 0, + user.getUid()); + + int subscr_notify = getJdbcTemplate().update( + "UPDATE useroptions SET subscr_notify=? WHERE user_id=?", + options.isSubscriptionsEnabled() ? 1 : 0, + user.getUid()); + + int recommendations = getJdbcTemplate().update( + "UPDATE useroptions SET recommendations=? WHERE user_id=?", + options.isRecommendationsEnabled() ? 1 : 0, + user.getUid()); + + return jnotify > 0 && subscr_notify > 0 && recommendations > 0; } } diff --git a/juick-server/src/main/java/com/juick/service/TagService.java b/juick-server/src/main/java/com/juick/service/TagService.java index d5f63e3a..03dcd842 100644 --- a/juick-server/src/main/java/com/juick/service/TagService.java +++ b/juick-server/src/main/java/com/juick/service/TagService.java @@ -2,6 +2,7 @@ package com.juick.service; import com.juick.Tag; +import java.util.Collection; import java.util.List; /** @@ -14,7 +15,7 @@ public interface TagService { List<Tag> getTags(String[] tags, boolean autoCreate); - boolean getTagNoIndex(int tag_id); + boolean getTagNoIndex(int tagId); int createTag(String name); @@ -24,7 +25,7 @@ public interface TagService { List<String> getPopularTags(); - List<Tag> updateTags(int mid, List<Tag> newTags); + List<Tag> updateTags(int mid, Collection<Tag> newTags); List<Tag> fromString(String txt, boolean tagsOnly); } diff --git a/juick-server/src/main/java/com/juick/service/TagServiceImpl.java b/juick-server/src/main/java/com/juick/service/TagServiceImpl.java index d63159cf..8f420ba9 100644 --- a/juick-server/src/main/java/com/juick/service/TagServiceImpl.java +++ b/juick-server/src/main/java/com/juick/service/TagServiceImpl.java @@ -1,9 +1,12 @@ package com.juick.service; import com.juick.Tag; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringEscapeUtils; -import org.springframework.dao.EmptyResultDataAccessException; +import org.apache.commons.lang3.StringUtils; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Repository; @@ -13,7 +16,9 @@ import org.springframework.util.Assert; import javax.inject.Inject; import java.sql.PreparedStatement; import java.sql.Statement; +import java.sql.Types; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; @@ -41,38 +46,39 @@ public class TagServiceImpl extends BaseJdbcService implements TagService { @Transactional(readOnly = true) @Override public com.juick.Tag getTag(final int tid) { - try { - return getJdbcTemplate().queryForObject( - "SELECT synonym_id,name FROM tags WHERE tag_id=?", - (rs, num) -> { - Tag ret = new Tag(StringEscapeUtils.unescapeHtml4(rs.getString(2))); - ret.TID = tid; - ret.SynonymID = rs.getInt(1); - return ret; - }, - tid); - } catch (EmptyResultDataAccessException e) { - return null; - } + List<Tag> list = getJdbcTemplate().query( + "SELECT synonym_id,name FROM tags WHERE tag_id=?", + (rs, num) -> { + Tag ret = new Tag(StringEscapeUtils.unescapeHtml4(rs.getString(2))); + ret.TID = tid; + ret.SynonymID = rs.getInt(1); + return ret; + }, + tid); + + return list.isEmpty() ? + null : list.get(0); } @Transactional(readOnly = true) @Override public com.juick.Tag getTag(final String tag, final boolean autoCreate) { - Tag ret = null; - try { - ret = getJdbcTemplate().queryForObject( - "SELECT tag_id,synonym_id,name FROM tags WHERE name=?", - (rs, rowNum) -> { - Tag ret1 = new Tag(StringEscapeUtils.unescapeHtml4(rs.getString(3))); - ret1.TID = rs.getInt(1); - ret1.SynonymID = rs.getInt(2); - return ret1; - }, - StringEscapeUtils.escapeHtml4(tag)); - } catch (EmptyResultDataAccessException e) { - // tag not found - } + if (StringUtils.isBlank(tag)) + return null; + + List<Tag> list = getJdbcTemplate().query( + "SELECT tag_id, synonym_id, name FROM tags WHERE name = ?", + (rs, rowNum) -> { + Tag ret1 = new Tag(StringEscapeUtils.unescapeHtml4(rs.getString(3))); + ret1.TID = rs.getInt(1); + ret1.SynonymID = rs.getInt(2); + return ret1; + }, + StringEscapeUtils.escapeHtml4(tag)); + + Tag ret = list.isEmpty() ? + null : list.get(0); + if (ret == null && autoCreate) { ret = new com.juick.Tag(tag); ret.TID = createTag(tag); @@ -83,14 +89,17 @@ public class TagServiceImpl extends BaseJdbcService implements TagService { @Override public List<Tag> getTags(final String[] tags, final boolean autoCreate) { + if (ArrayUtils.isEmpty(tags)) + return Collections.emptyList(); + List<Tag> ret = new ArrayList<>(); for (String tag : tags) { if (!tag.isEmpty()) { Tag t = getTag(tag, autoCreate); - if (t != null) { + + if (t != null) ret.add(t); - } } } @@ -99,26 +108,26 @@ public class TagServiceImpl extends BaseJdbcService implements TagService { @Transactional(readOnly = true) @Override - public boolean getTagNoIndex(final int tag_id) { - try { - return getJdbcTemplate().queryForObject( - "SELECT noindex FROM tags WHERE tag_id=?", Integer.class, tag_id) == 1; - } catch (EmptyResultDataAccessException e) { - return false; - } + public boolean getTagNoIndex(final int tagId) { + List<Integer> list = getJdbcTemplate().queryForList( + "SELECT noindex FROM tags WHERE tag_id=?", Integer.class, tagId); + + return !list.isEmpty() && list.get(0) == 1; } @Transactional @Override public int createTag(final String name) { KeyHolder holder = new GeneratedKeyHolder(); - getJdbcTemplate().update(con -> { - PreparedStatement stmt = con.prepareStatement( - "INSERT INTO tags(name) VALUES (?)", - Statement.RETURN_GENERATED_KEYS); - stmt.setString(1, StringEscapeUtils.escapeHtml4(name)); - return stmt; - }, holder); + getJdbcTemplate().update( + con -> { + PreparedStatement stmt = con.prepareStatement( + "INSERT INTO tags(name) VALUES (?)", + Statement.RETURN_GENERATED_KEYS); + stmt.setString(1, StringEscapeUtils.escapeHtml4(name)); + return stmt; + }, + holder); return holder.getKey().intValue(); } @@ -135,7 +144,8 @@ public class TagServiceImpl extends BaseJdbcService implements TagService { Tag t = new Tag(StringEscapeUtils.unescapeHtml4(rs.getString(1))); t.UsageCnt = rs.getInt(2); return t; - }, uid); + }, + uid); } @Transactional(readOnly = true) @@ -143,7 +153,7 @@ public class TagServiceImpl extends BaseJdbcService implements TagService { public List<String> getUserBLTags(final int uid) { return getJdbcTemplate().queryForList( "SELECT tags.name FROM tags INNER JOIN bl_tags " + - "ON (bl_tags.user_id=? AND bl_tags.tag_id=tags.tag_id) ORDER BY tags.name", + "ON (bl_tags.user_id = ? AND bl_tags.tag_id = tags.tag_id) ORDER BY tags.name", String.class, uid); } @@ -151,22 +161,43 @@ public class TagServiceImpl extends BaseJdbcService implements TagService { @Override public List<String> getPopularTags() { return getJdbcTemplate().queryForList( - "SELECT name FROM tags WHERE top=1 ORDER BY name ASC", String.class).stream() - .map(StringEscapeUtils::unescapeHtml4).collect(Collectors.toList()); + "SELECT name FROM tags WHERE top=1 ORDER BY name ASC", String.class) + .stream() + .map(StringEscapeUtils::unescapeHtml4) + .collect(Collectors.toList()); } @Transactional @Override - public List<Tag> updateTags(final int mid, final List<Tag> newTags) { + public List<Tag> updateTags(final int mid, final Collection<Tag> newTags) { List<Tag> currentTags = messagesService.getMessageTags(mid); - newTags.stream().filter(currentTags::contains) - .forEach(t -> getJdbcTemplate().update( - "DELETE FROM messages_tags WHERE message_id=? AND tag_id=?", - mid, - t.TID)); - newTags.stream().filter(t -> !currentTags.contains(t)) - .forEach(t -> getJdbcTemplate().update( - "INSERT INTO messages_tags(message_id,tag_id) VALUES (?,?)", mid, t.TID)); + + if (CollectionUtils.isEmpty(newTags)) + return currentTags; + + List<Integer> ids = new ArrayList<>(newTags.size()); + List<Object[]> params = new ArrayList<>(newTags.size()); + + newTags.stream().forEach(tag -> { + if (currentTags.contains(tag)) + ids.add(tag.TID); + else + params.add(new Object[]{mid, tag.TID}); + }); + + if (!params.isEmpty()) + getJdbcTemplate().batchUpdate( + "INSERT INTO messages_tags(message_id,tag_id) VALUES (?, ?)", + params, + new int[]{Types.INTEGER, Types.INTEGER}); + + if (!ids.isEmpty()) + getNamedParameterJdbcTemplate().update( + "DELETE FROM messages_tags WHERE message_id = :mid AND tag_id in (:ids)", + new MapSqlParameterSource() + .addValue("mid", mid) + .addValue("ids", ids)); + return messagesService.getMessageTags(mid); } @@ -176,12 +207,13 @@ public class TagServiceImpl extends BaseJdbcService implements TagService { if (tagsPattern.matcher(txt).matches()) { Matcher tagMatcher = TAG_PATTERN.matcher(txt); + List<Tag> tags = new ArrayList<>(); + // TODO: process readonly, private, friends, public while (tagMatcher.find()) { - for (int i = 1; i <= tagMatcher.groupCount(); i++) { + for (int i = 1; i <= tagMatcher.groupCount(); i++) tags.add(getTag(tagMatcher.group(i), true)); - } } return tags; } diff --git a/juick-server/src/main/java/com/juick/service/UserService.java b/juick-server/src/main/java/com/juick/service/UserService.java index e970afb7..bc7742cb 100644 --- a/juick-server/src/main/java/com/juick/service/UserService.java +++ b/juick-server/src/main/java/com/juick/service/UserService.java @@ -5,6 +5,7 @@ import com.juick.server.helpers.Auth; import com.juick.server.helpers.EmailOpts; import com.juick.server.helpers.UserInfo; +import java.util.Collection; import java.util.List; import java.util.Optional; @@ -29,11 +30,11 @@ public interface UserService { User getUserByJID(String jid); - List<User> getUsersByName(List<String> unames); + List<User> getUsersByName(Collection<String> unames); - List<User> getUsersByID(List<Integer> uids); + List<User> getUsersByID(Collection<Integer> uids); - List<com.juick.User> getUsersByJID(List<String> jids); + List<com.juick.User> getUsersByJID(Collection<String> jids); List<String> getJIDsbyUID(int uid); @@ -55,7 +56,7 @@ public interface UserService { int getUserOptionInt(int uid, String option, int defaultValue); - void setUserOptionInt(int uid, String option, int value); + int setUserOptionInt(int uid, String option, int value); UserInfo getUserInfo(User user); @@ -69,7 +70,7 @@ public interface UserService { boolean isInBLAny(int uid, int uid2); - List<Integer> checkBL(int visitor, List<Integer> uids); + List<Integer> checkBL(int visitor, Collection<Integer> uids); boolean isSubscribed(int uid, int check); 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 63785cff..2c52582d 100644 --- a/juick-server/src/main/java/com/juick/service/UserServiceImpl.java +++ b/juick-server/src/main/java/com/juick/service/UserServiceImpl.java @@ -5,15 +5,16 @@ import com.juick.server.helpers.Auth; import com.juick.server.helpers.EmailOpts; import com.juick.server.helpers.UserInfo; import com.juick.util.UserUtils; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; import org.springframework.dao.DuplicateKeyException; -import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; 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.util.StringUtils; import javax.inject.Inject; import java.sql.PreparedStatement; @@ -47,33 +48,32 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { @Transactional @Override public String getSignUpHashByJID(final String jid) { - String hash; - try { - hash = getJdbcTemplate().queryForObject( - "SELECT loginhash FROM jids WHERE jid=? AND user_id IS NULL", - String.class, - jid); - } catch (EmptyResultDataAccessException e) { - hash = UUID.randomUUID().toString(); - getJdbcTemplate().update("INSERT INTO jids(jid,loginhash) VALUES (?,?)", jid, hash); + List<String> list = getJdbcTemplate().queryForList( + "SELECT loginhash FROM jids WHERE jid = ? AND user_id IS NULL", String.class, jid); + + if (list.isEmpty()) { + String hash = UUID.randomUUID().toString(); + getJdbcTemplate().update("INSERT INTO jids(jid, loginhash) VALUES (?, ?)", jid, hash); + return hash; } - return hash; + return list.get(0); } @Transactional @Override public String getSignUpHashByTelegramID(final Long telegramId, final String username) { - try { - return getJdbcTemplate().queryForObject( - "SELECT loginhash FROM telegram WHERE tg_id=? AND user_id IS NULL", - String.class, - telegramId); - } catch (EmptyResultDataAccessException e) { + List<String> list = getJdbcTemplate().queryForList( + "SELECT loginhash FROM telegram WHERE tg_id = ? AND user_id IS NULL", + String.class, + telegramId); + + if (list.isEmpty()) { String hash = UUID.randomUUID().toString(); getJdbcTemplate().update( "INSERT INTO telegram(tg_id, loginhash, tg_name) VALUES (?, ?, ?)", telegramId, hash, username); return hash; } + return list.get(0); } @Transactional @@ -81,14 +81,16 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { public int createUser(final String username, final String password) { KeyHolder holder = new GeneratedKeyHolder(); 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); + 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; } @@ -96,7 +98,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { 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); + getJdbcTemplate().update("INSERT INTO subscr_users(user_id, suser_id) VALUES (2, ?)", uid); return uid; } @@ -104,190 +106,194 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { @Transactional(readOnly = true) @Override public Optional<User> getUserByUID(final int uid) { - try { - return Optional.of( - getJdbcTemplate().queryForObject("SELECT id, nick,banned FROM users WHERE id=?", - new UserMapper(), - uid)); - } catch (EmptyResultDataAccessException e) { - return Optional.empty(); - } + List<User> list = getJdbcTemplate().query( + "SELECT id, nick,banned FROM users WHERE id = ?", new UserMapper(), uid); + + return list.isEmpty() ? + Optional.empty() : Optional.of(list.get(0)); } @Transactional(readOnly = true) @Override public User getUserByName(final String username) { - try { - return getJdbcTemplate().queryForObject( - "SELECT id,nick,banned FROM users WHERE nick=?", - new UserMapper(), - username); - } catch (EmptyResultDataAccessException e) { - return null; - } + List<User> list = getJdbcTemplate().query( + "SELECT id, nick, banned FROM users WHERE nick = ?", new UserMapper(), username); + + return list.isEmpty() ? + null : list.get(0); } @Transactional(readOnly = true) @Override public User getUserByJID(final String jid) { - try { - return getJdbcTemplate().queryForObject( - "SELECT id,nick,banned FROM users WHERE id=(SELECT user_id FROM jids WHERE jid=?)", - new UserMapper(), - jid); - } catch (EmptyResultDataAccessException e) { - return null; - } + List<User> list = getJdbcTemplate().query( + "SELECT id, nick, banned FROM users WHERE id = (SELECT user_id FROM jids WHERE jid = ?)", + new UserMapper(), + jid); + + return list.isEmpty() ? + null : list.get(0); } @Transactional(readOnly = true) @Override - public List<User> getUsersByName(final List<String> unames) { - if (!unames.isEmpty()) { - return getJdbcTemplate().query( - "SELECT id,nick,banned FROM users WHERE nick IN (\"" + StringUtils.arrayToDelimitedString(unames.toArray(), "\",\"") + "\")", - new UserMapper()); - } - return Collections.emptyList(); + public List<User> getUsersByName(final Collection<String> unames) { + if (CollectionUtils.isEmpty(unames)) + return Collections.emptyList(); + + return getNamedParameterJdbcTemplate().query( + "SELECT id, nick, banned FROM users WHERE nick IN (:unames)", + new MapSqlParameterSource("unames", unames), + new UserMapper()); } @Transactional(readOnly = true) @Override - public List<User> getUsersByID(final List<Integer> uids) { - if (!uids.isEmpty()) { - return getJdbcTemplate().query( - "SELECT id,nick,banned FROM users WHERE id IN (" + StringUtils.arrayToCommaDelimitedString(uids.toArray()) + ")", - new UserMapper()); - } - return Collections.emptyList(); + public List<User> getUsersByID(final Collection<Integer> uids) { + if (CollectionUtils.isEmpty(uids)) + return Collections.emptyList(); + + return getNamedParameterJdbcTemplate().query( + "SELECT id, nick, banned FROM users WHERE id IN (:ids)", + new MapSqlParameterSource("ids", uids), + new UserMapper()); } @Transactional(readOnly = true) @Override - public List<com.juick.User> getUsersByJID(final List<String> jids) { - if (!jids.isEmpty()) { - return getJdbcTemplate().query( - "SELECT users.id,users.nick,jids.jid FROM users " - + "INNER JOIN jids ON jids.user_id=users.id " - + "WHERE jids.jid IN (\"" + StringUtils.arrayToDelimitedString(jids.toArray(), "\",\"") + "\")", - (rs, rowNum) -> { - com.juick.User user = new com.juick.User(); - user.setUid(rs.getInt(1)); - user.setName(rs.getString(2)); - user.setJID(rs.getString(3)); - return user; - }); - } - return Collections.emptyList(); + public List<com.juick.User> getUsersByJID(final Collection<String> jids) { + if (CollectionUtils.isEmpty(jids)) + return Collections.emptyList(); + + return getNamedParameterJdbcTemplate().query( + "SELECT users.id, users.nick, jids.jid FROM users " + + " INNER JOIN jids ON jids.user_id = users.id " + + " WHERE jids.jid IN (:jids)", + new MapSqlParameterSource("jids", jids), + (rs, rowNum) -> { + com.juick.User user = new com.juick.User(); + user.setUid(rs.getInt(1)); + user.setName(rs.getString(2)); + user.setJID(rs.getString(3)); + return user; + }); } @Transactional(readOnly = true) @Override public List<String> getJIDsbyUID(final int uid) { - return getJdbcTemplate().queryForList("SELECT jid FROM jids WHERE user_id=? AND active=1", String.class, uid); + 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) { - try { - return getJdbcTemplate().queryForObject("SELECT user_id FROM jids WHERE jid=?", Integer.class, jid); - } catch (EmptyResultDataAccessException e) { - return 0; + if (StringUtils.isNotBlank(jid)) { + List<Integer> 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) { - try { - return getJdbcTemplate().queryForObject("SELECT id FROM users WHERE nick=?", Integer.class, uname); - } catch (EmptyResultDataAccessException e) { - return 0; + if (StringUtils.isNotBlank(uname)) { + List<Integer> 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) { - try { - return getJdbcTemplate().queryForObject("SELECT user_id FROM logins WHERE hash=?", Integer.class, hash); - } catch (EmptyResultDataAccessException e) { - return 0; + if (StringUtils.isNotBlank(hash)) { + List<Integer> 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) { - try { - User user = getJdbcTemplate().queryForObject( - "SELECT logins.user_id,users.nick, users.banned FROM logins " + - "INNER JOIN users ON logins.user_id=users.id WHERE logins.hash=?", + if (StringUtils.isNotBlank(hash)) { + List<User> list = getJdbcTemplate().query( + "SELECT logins.user_id, users.nick, users.banned FROM logins " + + "INNER JOIN users ON logins.user_id = users.id WHERE logins.hash = ?", new UserMapper(), hash); - user.setAuthHash(hash); - return user; - } catch (EmptyResultDataAccessException e) { - return new User(); + + if (!list.isEmpty()) { + User user = list.get(0); + user.setAuthHash(hash); + return user; + } } + return new User(); } @Transactional @Override public String getHashByUID(final int uid) { - try { - return getJdbcTemplate().queryForObject( - "SELECT hash FROM logins WHERE user_id=?", String.class, uid); - } catch (EmptyResultDataAccessException e) { + List<String> list = getJdbcTemplate().queryForList( + "SELECT hash FROM logins WHERE user_id = ?", String.class, uid); + + if (list.isEmpty()) { String hash = UserUtils.generateHash(16); - getJdbcTemplate().update(con -> { - PreparedStatement stmt = con.prepareStatement("INSERT INTO logins(user_id,hash) VALUES (?,?)"); - stmt.setInt(1, uid); - stmt.setString(2, hash); - return stmt; - }); + getJdbcTemplate().update("INSERT INTO logins(user_id, hash) VALUES (?, ?)", uid, hash); return hash; } + return list.get(0); } @Transactional(readOnly = true) @Override public int checkPassword(final String username, final String password) { - try { - String realPassword = getJdbcTemplate().queryForObject( - "SELECT passw FROM users WHERE nick=?", String.class, username); - if (realPassword.equals(password)) { - User user = getUserByName(username); - if (user != null) { - return user.getUid(); - } else { - return -1; + if (StringUtils.isNotBlank(username)) { + List<String> list = getJdbcTemplate().queryForList( + "SELECT passw FROM users WHERE nick = ?", String.class, username); + + if (!list.isEmpty()) { + String realPassword = list.get(0); + if (realPassword.equals(password)) { + User user = getUserByName(username); + if (user != null) + return user.getUid(); } - } else { - return -1; } - } catch (EmptyResultDataAccessException e) { - return -1; } + return -1; } @Transactional @Override public boolean updatePassword(final User user, final String newPassword) { - return user.getUid() > 0 && getJdbcTemplate().update("UPDATE users SET passw=? WHERE id=?", newPassword, user.getUid()) > 0; + return user != null && + user.getUid() > 0 && + getJdbcTemplate().update("UPDATE users SET passw = ? WHERE id = ?", newPassword, user.getUid()) > 0; } @Transactional @Override public String updateSecretEmail(final User user) { - String newHash = UserUtils.generateHash(16); - if (getJdbcTemplate().update( - "INSERT INTO mail(user_id,hash) VALUES (?,?) ON DUPLICATE KEY UPDATE hash=?", - user.getUid(), - newHash, - newHash) > 0) { - return newHash; + if (user != null) { + String newHash = UserUtils.generateHash(16); + int ret = getJdbcTemplate().update( + "INSERT INTO mail(user_id, hash) VALUES (?, ?) ON DUPLICATE KEY UPDATE hash = ?", + user.getUid(), newHash, newHash); + if (ret > 0) + return newHash; } return ""; } @@ -295,43 +301,48 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { @Transactional(readOnly = true) @Override public int getUserOptionInt(final int uid, final String option, final int defaultValue) { - try { - return getJdbcTemplate().queryForObject("SELECT " + option + " FROM useroptions WHERE user_id=?", Integer.class, uid); - } catch (EmptyResultDataAccessException e) { + if (StringUtils.isBlank(option)) return defaultValue; - } + + List<Integer> list = getJdbcTemplate().queryForList( + "SELECT " + option + " FROM useroptions WHERE user_id = ?", Integer.class, uid); + + return list.isEmpty() ? defaultValue : list.get(0); } @Transactional(readOnly = true) @Override - public void setUserOptionInt(final int uid, final String option, final int value) { - getJdbcTemplate().update("UPDATE useroptions SET " + option + "=? WHERE user_id=?", value, uid); + public int setUserOptionInt(final int uid, final String option, final int value) { + if (StringUtils.isBlank(option)) + return 0; + + return getJdbcTemplate().update("UPDATE useroptions SET " + option + "= ? WHERE user_id = ?", value, uid); } @Transactional(readOnly = true) @Override public UserInfo getUserInfo(final User user) { - try { - return getJdbcTemplate().queryForObject("SELECT fullname,country,url,descr FROM usersinfo WHERE user_id=?", - ((rs, rowNum) -> { - UserInfo info = new UserInfo(); - info.setFullName(rs.getString(1)); - info.setCountry(rs.getString(2)); - info.setUrl(rs.getString(3)); - info.setDescription(rs.getString(4)); - return info; - }), user.getUid()); - } catch (EmptyResultDataAccessException e) { - return new UserInfo(); - } + List<UserInfo> list = getJdbcTemplate().query( + "SELECT fullname, country, url, descr FROM usersinfo WHERE user_id = ?", + ((rs, rowNum) -> { + UserInfo info = new UserInfo(); + info.setFullName(rs.getString(1)); + info.setCountry(rs.getString(2)); + info.setUrl(rs.getString(3)); + info.setDescription(rs.getString(4)); + return info; + }), + user.getUid()); + + return list.isEmpty() ? new UserInfo() : list.get(0); } @Transactional @Override public boolean updateUserInfo(final User user, final UserInfo info) { return getJdbcTemplate().update( - "INSERT INTO usersinfo(user_id,fullname,country,url,descr) VALUES (?,?,?,?,?) " + - "ON DUPLICATE KEY UPDATE fullname=?,country=?,url=?,descr=?", + "INSERT INTO usersinfo(user_id, fullname, country, url, descr) VALUES (?, ?, ?, ?, ?) " + + "ON DUPLICATE KEY UPDATE fullname = ?, country = ?, url = ?, descr = ?", user.getUid(), info.getFullName(), info.getCountry(), @@ -346,76 +357,67 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { @Transactional(readOnly = true) @Override public boolean getCanMedia(final int uid) { - try { - int res = getJdbcTemplate().queryForObject( - "SELECT users.lastphoto-UNIX_TIMESTAMP() FROM users WHERE id=?", - Integer.class, - uid); - return res < 3600; - } catch (EmptyResultDataAccessException e) { - return false; - } + List<Integer> 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) { - try { - return getJdbcTemplate().queryForObject( - "SELECT 1 FROM wl_users WHERE user_id=? AND wl_user_id=?", - Integer.class, uid, check) == 1; - } catch (EmptyResultDataAccessException e) { - return false; - } + List<Integer> list = getJdbcTemplate().queryForList( + "SELECT 1 FROM wl_users WHERE user_id = ? AND wl_user_id = ?", + Integer.class, uid, check); + + return !list.isEmpty() && list.get(0) == 1; } @Transactional(readOnly = true) @Override public boolean isInBL(final int uid, final int check) { - try { - return getJdbcTemplate().queryForObject("SELECT 1 FROM bl_users WHERE user_id=? AND bl_user_id=?", - Integer.class, uid, check) == 1; - } catch (EmptyResultDataAccessException e) { - return false; - } + List<Integer> list = getJdbcTemplate().queryForList( + "SELECT 1 FROM bl_users WHERE user_id = ? AND bl_user_id = ?", Integer.class, uid, check); + + return !list.isEmpty() && list.get(0) == 1; } @Transactional(readOnly = true) @Override public boolean isInBLAny(final int uid, final int uid2) { - try { - return getJdbcTemplate().queryForObject("SELECT 1 FROM bl_users " - + "WHERE (user_id=? AND bl_user_id=?) " - + "OR (user_id=? AND bl_user_id=?)", new Object[]{uid, uid2, uid2, uid}, Integer.class) == 1; - } catch (EmptyResultDataAccessException e) { - return false; - } + List<Integer> list = getJdbcTemplate().queryForList( + "SELECT 1 FROM bl_users WHERE (user_id = ? AND bl_user_id = ?) " + + "OR (user_id = ? AND bl_user_id = ?)", + new Object[]{uid, uid2, uid2, uid}, + Integer.class); + + return !list.isEmpty() && list.get(0) == 1; } @Transactional(readOnly = true) @Override - public List<Integer> checkBL(final int visitor, final List<Integer> uids) { - if (!uids.isEmpty()) { - return getJdbcTemplate().queryForList( - "SELECT user_id FROM bl_users WHERE bl_user_id=? and user_id IN (" + - StringUtils.collectionToCommaDelimitedString(uids) + ")", - Integer.class, - visitor); - } else { - return new ArrayList<>(); - } + public List<Integer> checkBL(final int visitor, final Collection<Integer> uids) { + if (CollectionUtils.isEmpty(uids)) + return Collections.emptyList(); + + return getNamedParameterJdbcTemplate().queryForList( + "SELECT user_id FROM bl_users WHERE bl_user_id = :visitor and user_id IN (:ids)", + new MapSqlParameterSource() + .addValue("visitor", visitor) + .addValue("ids", uids), + Integer.class); } @Transactional(readOnly = true) @Override public boolean isSubscribed(final int uid, final int check) { - try { - return getJdbcTemplate().queryForObject( - "SELECT 1 FROM subscr_users WHERE suser_id=? AND user_id=?", - Integer.class, uid, check) == 1; - } catch (EmptyResultDataAccessException e) { - return false; - } + List<Integer> list = getJdbcTemplate().queryForList( + "SELECT 1 FROM subscr_users WHERE suser_id = ? AND user_id = ?", + Integer.class, uid, check); + + return !list.isEmpty() && list.get(0) == 1; } @Transactional(readOnly = true) @@ -508,41 +510,30 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { @Transactional(readOnly = true) @Override public int getStatsIRead(final int uid) { - try { - return getJdbcTemplate().queryForObject("SELECT COUNT(*) FROM subscr_users WHERE suser_id=?", Integer.class, uid); - } catch (EmptyResultDataAccessException e) { - return 0; - } + List<Integer> list = getJdbcTemplate().queryForList( + "SELECT COUNT(*) FROM subscr_users WHERE suser_id = ?", Integer.class, uid); + return list.isEmpty() ? 0 : list.get(0); } @Transactional(readOnly = true) @Override public int getStatsMyReaders(final int uid) { - try { - return getJdbcTemplate().queryForObject("SELECT COUNT(*) FROM subscr_users WHERE user_id=?", Integer.class, uid); - } catch (EmptyResultDataAccessException e) { - return 0; - } + List<Integer> list = getJdbcTemplate().queryForList("SELECT COUNT(*) FROM subscr_users WHERE user_id = ?", Integer.class, uid); + return list.isEmpty() ? 0 : list.get(0); } @Transactional(readOnly = true) @Override public int getStatsMessages(final int uid) { - try { - return getJdbcTemplate().queryForObject("SELECT COUNT(*) FROM messages WHERE user_id=?", Integer.class, uid); - } catch (EmptyResultDataAccessException e) { - return 0; - } + List<Integer> list = getJdbcTemplate().queryForList("SELECT COUNT(*) FROM messages WHERE user_id = ?", Integer.class, uid); + return list.isEmpty() ? 0 : list.get(0); } @Transactional(readOnly = true) @Override public int getStatsReplies(final int uid) { - try { - return getJdbcTemplate().queryForObject("SELECT COUNT(*) FROM replies WHERE user_id=?", Integer.class, uid); - } catch (EmptyResultDataAccessException e) { - return 0; - } + List<Integer> list = getJdbcTemplate().queryForList("SELECT COUNT(*) FROM replies WHERE user_id = ?", Integer.class, uid); + return list.isEmpty() ? 0 : list.get(0); } @Transactional @@ -550,16 +541,10 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { public boolean setActiveStatusForJID(final String JID, final UserService.ActiveStatus jidStatus) { User user = getUserByJID(JID); if (user != null) { - return getJdbcTemplate().update(con -> { - PreparedStatement preparedStatement = con.prepareStatement( - "UPDATE jids SET active=? WHERE user_id=? AND jid=?"); - int newStatus = jidStatus == UserService.ActiveStatus.Active ? 1 : 0; - preparedStatement.setInt(1, newStatus); - preparedStatement.setInt(2, user.getUid()); - preparedStatement.setString(3, JID); - return preparedStatement; - - }) >= 0; + int newStatus = jidStatus == UserService.ActiveStatus.Active ? 1 : 0; + return getJdbcTemplate().update( + "UPDATE jids SET active = ? WHERE user_id = ? AND jid = ?", + newStatus, user.getUid(), JID) >= 0; } return false; } @@ -589,26 +574,19 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { @Transactional(readOnly = true) @Override public EmailOpts getEmailOpts(final User user) { - try { - return getJdbcTemplate().queryForObject( - "SELECT email,subscr_hour FROM emails WHERE user_id=? AND subscr_hour IS NOT NULL", - (rs, num) -> new EmailOpts(rs.getString(1), rs.getInt(2)), user.getUid()); - } catch (EmptyResultDataAccessException e) { - return null; - } + List<EmailOpts> list = getJdbcTemplate().query( + "SELECT email,subscr_hour FROM emails WHERE user_id=? AND subscr_hour IS NOT NULL", + (rs, num) -> new EmailOpts(rs.getString(1), rs.getInt(2)), user.getUid()); + return list.isEmpty() ? null : list.get(0); } @Transactional(readOnly = true) @Override public String getEmailHash(final User user) { - try { - return getJdbcTemplate().queryForObject( - "SELECT hash FROM mail WHERE user_id=?", - String.class, - user.getUid()) - + "@mail.juick.com"; - } catch (EmptyResultDataAccessException e) { - return ""; - } + List<String> list = getJdbcTemplate().queryForList( + "SELECT hash FROM mail WHERE user_id = ?", + String.class, + user.getUid()); + return list.isEmpty() ? "" : list.get(0) + "@mail.juick.com"; } } |