From 606f43f50904f7d811cf9b438e0e820e586be900 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Mon, 27 Jun 2016 13:16:43 +0300 Subject: spring-jdbc near complete --- .../java/com/juick/xmpp/s2s/XMPPComponent.java | 24 ++++++++-------------- 1 file changed, 9 insertions(+), 15 deletions(-) (limited to 'src/main/java/com/juick/xmpp/s2s/XMPPComponent.java') diff --git a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java index 13df5fd0..70f01553 100644 --- a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java +++ b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java @@ -3,6 +3,8 @@ package com.juick.xmpp.s2s; import com.juick.xmpp.Stanza; import com.juick.xmpp.StanzaChild; import com.juick.xmpp.extensions.JuickMessage; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.xmlpull.v1.XmlPullParserException; import javax.servlet.ServletContextEvent; @@ -42,7 +44,7 @@ public class XMPPComponent implements ServletContextListener { static final List outConnections = Collections.synchronizedList(new ArrayList<>()); static final List outCache = Collections.synchronizedList(new ArrayList<>()); static final Integer sqlSync = 0; - static java.sql.Connection sql; + static JdbcTemplate sql; final public static HashMap childParsers = new HashMap<>(); public static void addConnectionIn(ConnectionIn c) { @@ -176,9 +178,12 @@ public class XMPPComponent implements ServletContextListener { keystore = conf.getProperty("keystore"); keystorePassword = conf.getProperty("keystore_password"); brokenSSLhosts = Arrays.asList(conf.getProperty("broken_ssl_hosts", "").split(",")); - Class.forName("com.mysql.jdbc.Driver"); - sql = DriverManager.getConnection("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + - conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", "")); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.Driver")); + dataSource.setUrl(conf.getProperty("datasource_url")); + DriverManagerDataSource dataSourceSearch = new DriverManagerDataSource(); + dataSourceSearch.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.Driver")); + sql = new JdbcTemplate(dataSource); childParsers.put(JuickMessage.XMLNS, new JuickMessage()); executorService.submit(() -> connRouter = new ConnectionRouter(componentName, conf.getProperty("xmpp_password"))); @@ -215,17 +220,6 @@ public class XMPPComponent implements ServletContextListener { } catch (IOException e) { LOGGER.log(Level.WARNING, "router warning", e); } - - synchronized (XMPPComponent.sqlSync) { - if (XMPPComponent.sql != null) { - try { - XMPPComponent.sql.close(); - XMPPComponent.sql = null; - } catch (SQLException e) { - LOGGER.warning("SQL ERROR: " + e); - } - } - } // Now deregister JDBC drivers in this context's ClassLoader: // Get the webapp's ClassLoader ClassLoader cl = Thread.currentThread().getContextClassLoader(); -- cgit v1.2.3 From d48e3b71c27d6782a63dda84aced58780b54f309 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 6 Jul 2016 18:48:28 +0300 Subject: JdbcTemplate is thread-safe --- .../java/com/juick/xmpp/s2s/ConnectionRouter.java | 52 +++--- src/main/java/com/juick/xmpp/s2s/JuickBot.java | 182 +++++++++------------ .../java/com/juick/xmpp/s2s/XMPPComponent.java | 1 - 3 files changed, 100 insertions(+), 135 deletions(-) (limited to 'src/main/java/com/juick/xmpp/s2s/XMPPComponent.java') diff --git a/src/main/java/com/juick/xmpp/s2s/ConnectionRouter.java b/src/main/java/com/juick/xmpp/s2s/ConnectionRouter.java index 95878edd..0030834a 100644 --- a/src/main/java/com/juick/xmpp/s2s/ConnectionRouter.java +++ b/src/main/java/com/juick/xmpp/s2s/ConnectionRouter.java @@ -55,15 +55,13 @@ public class ConnectionRouter implements Stream.StreamListener, public void sendJuickMessage(JuickMessage jmsg) { List jids = new ArrayList<>(); - synchronized (XMPPComponent.sqlSync) { - if (jmsg.FriendsOnly) { - jids = SubscriptionsQueries.getJIDSubscribedToUser(XMPPComponent.sql, jmsg.getUser().getUID(), jmsg.FriendsOnly); - } else { - List users = SubscriptionsQueries.getSubscribedUsers(XMPPComponent.sql, jmsg.getUser().getUID(), jmsg.getMID()); - for (User user : users) { - for (String jid : UserQueries.getJIDsbyUID(XMPPComponent.sql, user.getUID())) { - jids.add(jid); - } + if (jmsg.FriendsOnly) { + jids = SubscriptionsQueries.getJIDSubscribedToUser(XMPPComponent.sql, jmsg.getUser().getUID(), jmsg.FriendsOnly); + } else { + List users = SubscriptionsQueries.getSubscribedUsers(XMPPComponent.sql, jmsg.getUser().getUID(), jmsg.getMID()); + for (User user : users) { + for (String jid : UserQueries.getJIDsbyUID(XMPPComponent.sql, user.getUID())) { + jids.add(jid); } } } @@ -103,13 +101,11 @@ public class ConnectionRouter implements Stream.StreamListener, String replyQuote; String replyTo; - synchronized (XMPPComponent.sqlSync) { - users = SubscriptionsQueries.getUsersSubscribedToComments(XMPPComponent.sql, jmsg.getMID(), jmsg.getUser().getUID()); - com.juick.Message replyMessage = jmsg.ReplyTo > 0 ? MessagesQueries.getReply(XMPPComponent.sql, jmsg.getMID(), jmsg.ReplyTo) - : MessagesQueries.getMessage(XMPPComponent.sql, jmsg.getMID()); - replyTo = replyMessage.getUser().getUName(); - replyQuote = getReplyQuote(replyMessage); - } + users = SubscriptionsQueries.getUsersSubscribedToComments(XMPPComponent.sql, jmsg.getMID(), jmsg.getUser().getUID()); + com.juick.Message replyMessage = jmsg.ReplyTo > 0 ? MessagesQueries.getReply(XMPPComponent.sql, jmsg.getMID(), jmsg.ReplyTo) + : MessagesQueries.getMessage(XMPPComponent.sql, jmsg.getMID()); + replyTo = replyMessage.getUser().getUName(); + replyQuote = getReplyQuote(replyMessage); String txt = "Reply by @" + jmsg.getUser().getUName() + ":\n" + replyQuote + "\n@" + replyTo + " "; String attachment = jmsg.getAttachmentURL(); @@ -124,11 +120,9 @@ public class ConnectionRouter implements Stream.StreamListener, msg.type = Message.Type.chat; msg.addChild(jmsg); for (User user : users) { - synchronized (XMPPComponent.sqlSync) { - for (String jid : UserQueries.getJIDsbyUID(XMPPComponent.sql, user.getUID())) { - msg.to = new JID(jid); - XMPPComponent.sendOut(msg); - } + for (String jid : UserQueries.getJIDsbyUID(XMPPComponent.sql, user.getUID())) { + msg.to = new JID(jid); + XMPPComponent.sendOut(msg); } } } @@ -146,11 +140,9 @@ public class ConnectionRouter implements Stream.StreamListener, public void sendJuickRecommendation(JuickMessage recomm) { List users; JuickMessage jmsg; - synchronized (XMPPComponent.sqlSync) { - jmsg = new JuickMessage(MessagesQueries.getMessage(XMPPComponent.sql, recomm.getMID())); - users = SubscriptionsQueries.getUsersSubscribedToUserRecommendations(XMPPComponent.sql, - recomm.getUser().getUID(), recomm.getMID(), jmsg.getUser().getUID()); - } + jmsg = new JuickMessage(MessagesQueries.getMessage(XMPPComponent.sql, recomm.getMID())); + users = SubscriptionsQueries.getUsersSubscribedToUserRecommendations(XMPPComponent.sql, + recomm.getUser().getUID(), recomm.getMID(), jmsg.getUser().getUID()); String txt = "Recommended by @" + recomm.getUser().getUName() + ":\n"; txt += "@" + jmsg.getUser().getUName() + ":" + jmsg.getTagsString() + "\n"; @@ -186,11 +178,9 @@ public class ConnectionRouter implements Stream.StreamListener, } for (User user : users) { - synchronized (XMPPComponent.sqlSync) { - for (String jid : UserQueries.getJIDsbyUID(XMPPComponent.sql, user.getUID())) { - msg.to = new JID(jid); - XMPPComponent.sendOut(msg); - } + for (String jid : UserQueries.getJIDsbyUID(XMPPComponent.sql, user.getUID())) { + msg.to = new JID(jid); + XMPPComponent.sendOut(msg); } } } diff --git a/src/main/java/com/juick/xmpp/s2s/JuickBot.java b/src/main/java/com/juick/xmpp/s2s/JuickBot.java index 1172d75f..357b070f 100644 --- a/src/main/java/com/juick/xmpp/s2s/JuickBot.java +++ b/src/main/java/com/juick/xmpp/s2s/JuickBot.java @@ -69,9 +69,7 @@ public class JuickBot { } else if (p.type.equals(Presence.Type.probe)) { int uid_to = 0; if (!toJuick) { - synchronized (XMPPComponent.sqlSync) { - uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, username); - } + uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, username); } if (toJuick || uid_to > 0) { @@ -94,12 +92,10 @@ public class JuickBot { if (toJuick) { canSubscribe = true; } else { - synchronized (XMPPComponent.sqlSync) { - int uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, username); - if (uid_to > 0) { - PMQueries.addPMinRoster(XMPPComponent.sql, uid_to, p.from.Bare()); - canSubscribe = true; - } + int uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, username); + if (uid_to > 0) { + PMQueries.addPMinRoster(XMPPComponent.sql, uid_to, p.from.Bare()); + canSubscribe = true; } } @@ -122,11 +118,9 @@ public class JuickBot { } } else if (p.type.equals(Presence.Type.unsubscribe)) { if (!toJuick) { - synchronized (XMPPComponent.sqlSync) { - int uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, username); - if (uid_to > 0) { - PMQueries.removePMinRoster(XMPPComponent.sql, uid_to, p.from.Bare()); - } + int uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, username); + if (uid_to > 0) { + PMQueries.removePMinRoster(XMPPComponent.sql, uid_to, p.from.Bare()); } } @@ -146,11 +140,9 @@ public class JuickBot { User user_from = null; String signuphash = ""; - synchronized (XMPPComponent.sqlSync) { - user_from = UserQueries.getUserByJID(XMPPComponent.sql, msg.from.Bare()); - if (user_from == null) { - signuphash = UserQueries.getSignUpHashByJID(XMPPComponent.sql, msg.from.Bare()); - } + user_from = UserQueries.getUserByJID(XMPPComponent.sql, msg.from.Bare()); + if (user_from == null) { + signuphash = UserQueries.getSignUpHashByJID(XMPPComponent.sql, msg.from.Bare()); } if (user_from == null) { @@ -168,10 +160,7 @@ public class JuickBot { return incomingMessageJuick(user_from, msg); } - int uid_to = 0; - synchronized (XMPPComponent.sqlSync) { - uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, username); - } + int uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, username); if (uid_to == 0) { Message reply = new Message(msg.to, msg.from, Message.Type.error); @@ -182,10 +171,8 @@ public class JuickBot { } boolean success = false; - synchronized (XMPPComponent.sqlSync) { - if (!UserQueries.isInBLAny(XMPPComponent.sql, uid_to, user_from.getUID())) { - success = PMQueries.createPM(XMPPComponent.sql, user_from.getUID(), uid_to, msg.body); - } + if (!UserQueries.isInBLAny(XMPPComponent.sql, uid_to, user_from.getUID())) { + success = PMQueries.createPM(XMPPComponent.sql, user_from.getUID(), uid_to, msg.body); } if (success) { @@ -193,9 +180,7 @@ public class JuickBot { m.from = new JID("juick", "juick.com", null); m.to = new JID(Integer.toString(uid_to), "push.juick.com", null); JuickMessage jmsg = new JuickMessage(); - synchronized (XMPPComponent.sqlSync) { - jmsg.setUser(user_from); - } + jmsg.setUser(user_from); jmsg.setText(msg.body); m.childs.add(jmsg); XMPPComponent.connRouter.router.send(m.toString()); @@ -205,22 +190,20 @@ public class JuickBot { List jids; boolean inroster = false; - synchronized (XMPPComponent.sqlSync) { - jids = UserQueries.getJIDsbyUID(XMPPComponent.sql, uid_to); - for (String jid : jids) { - Message mm = new Message(); - mm.to = new JID(jid); - mm.type = Message.Type.chat; - inroster = PMQueries.havePMinRoster(XMPPComponent.sql, user_from.getUID(), jid); - if (inroster) { - mm.from = new JID(jmsg.getUser().getUName(), "juick.com", "Juick"); - mm.body = msg.body; - } else { - mm.from = new JID("juick", "juick.com", "Juick"); - mm.body = "Private message from @" + jmsg.getUser().getUName() + ":\n" + msg.body; - } - XMPPComponent.sendOut(mm); + jids = UserQueries.getJIDsbyUID(XMPPComponent.sql, uid_to); + for (String jid : jids) { + Message mm = new Message(); + mm.to = new JID(jid); + mm.type = Message.Type.chat; + inroster = PMQueries.havePMinRoster(XMPPComponent.sql, user_from.getUID(), jid); + if (inroster) { + mm.from = new JID(jmsg.getUser().getUName(), "juick.com", "Juick"); + mm.body = msg.body; + } else { + mm.from = new JID("juick", "juick.com", "Juick"); + mm.body = "Private message from @" + jmsg.getUser().getUName() + ":\n" + msg.body; } + XMPPComponent.sendOut(mm); } } else { Message reply = new Message(msg.to, msg.from, Message.Type.error); @@ -299,77 +282,70 @@ public class JuickBot { List jids_to = null; boolean haveInRoster = false; - synchronized (XMPPComponent.sqlSync) { - if (user_to.indexOf('@') > 0) { - uid_to = UserQueries.getUIDbyJID(XMPPComponent.sql, user_to); - } else { - uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, user_to); - } + if (user_to.indexOf('@') > 0) { + uid_to = UserQueries.getUIDbyJID(XMPPComponent.sql, user_to); + } else { + uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, user_to); + } - if (uid_to > 0) { - if (!UserQueries.isInBLAny(XMPPComponent.sql, uid_to, user_from.getUID())) { - if (PMQueries.createPM(XMPPComponent.sql, user_from.getUID(), uid_to, body)) { - jids_to = UserQueries.getJIDsbyUID(XMPPComponent.sql, uid_to); - ret = 200; - } else { - ret = 500; - } + if (uid_to > 0) { + if (!UserQueries.isInBLAny(XMPPComponent.sql, uid_to, user_from.getUID())) { + if (PMQueries.createPM(XMPPComponent.sql, user_from.getUID(), uid_to, body)) { + jids_to = UserQueries.getJIDsbyUID(XMPPComponent.sql, uid_to); + ret = 200; } else { - ret = 403; + ret = 500; } } else { - ret = 404; + ret = 403; } + } else { + ret = 404; + } - if (ret == 200) { - Message msg = new Message(); - msg.from = new JID("juick", "juick.com", null); - msg.to = new JID(Integer.toString(uid_to), "push.juick.com", null); - JuickMessage jmsg = new JuickMessage(); - jmsg.setUser(user_from); - jmsg.setText(body); - msg.childs.add(jmsg); - XMPPComponent.connRouter.router.send(msg.toString()); - - msg.to.Host = "ws.juick.com"; - XMPPComponent.connRouter.router.send(msg.toString()); - - for (String jid : jids_to) { - Message mm = new Message(); - mm.to = new JID(jid); - mm.type = Message.Type.chat; - haveInRoster = PMQueries.havePMinRoster(XMPPComponent.sql, user_from.getUID(), jid); - if (haveInRoster) { - mm.from = new JID(user_from.getUName(), "juick.com", "Juick"); - mm.body = body; - } else { - mm.from = new JID("juick", "juick.com", "Juick"); - mm.body = "Private message from @" + user_from.getUName() + ":\n" + body; - } - XMPPComponent.sendOut(mm); + if (ret == 200) { + Message msg = new Message(); + msg.from = new JID("juick", "juick.com", null); + msg.to = new JID(Integer.toString(uid_to), "push.juick.com", null); + JuickMessage jmsg = new JuickMessage(); + jmsg.setUser(user_from); + jmsg.setText(body); + msg.childs.add(jmsg); + XMPPComponent.connRouter.router.send(msg.toString()); + + msg.to.Host = "ws.juick.com"; + XMPPComponent.connRouter.router.send(msg.toString()); + + for (String jid : jids_to) { + Message mm = new Message(); + mm.to = new JID(jid); + mm.type = Message.Type.chat; + haveInRoster = PMQueries.havePMinRoster(XMPPComponent.sql, user_from.getUID(), jid); + if (haveInRoster) { + mm.from = new JID(user_from.getUName(), "juick.com", "Juick"); + mm.body = body; + } else { + mm.from = new JID("juick", "juick.com", "Juick"); + mm.body = "Private message from @" + user_from.getUName() + ":\n" + body; } + XMPPComponent.sendOut(mm); } + } - Message reply = new Message(m.to, m.from); - if (ret == 200) { - reply.type = m.type; - reply.body = "Private message sent"; - } else { - reply.type = Message.Type.error; - reply.body = "Error " + ret; - } - XMPPComponent.sendOut(reply); + Message reply = new Message(m.to, m.from); + if (ret == 200) { + reply.type = m.type; + reply.body = "Private message sent"; + } else { + reply.type = Message.Type.error; + reply.body = "Error " + ret; } + XMPPComponent.sendOut(reply); } private static void commandBLShow(Message m, User user_from) throws Exception { - List blusers; - List bltags; - - synchronized (XMPPComponent.sqlSync) { - blusers = UserQueries.getUserBLUsers(XMPPComponent.sql, user_from.getUID()); - bltags = TagQueries.getUserBLTags(XMPPComponent.sql, user_from.getUID()); - } + List blusers = UserQueries.getUserBLUsers(XMPPComponent.sql, user_from.getUID()); + List bltags = TagQueries.getUserBLTags(XMPPComponent.sql, user_from.getUID()); String txt = ""; if (bltags.size() > 0) { diff --git a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java index 70f01553..bb736b5e 100644 --- a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java +++ b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java @@ -43,7 +43,6 @@ public class XMPPComponent implements ServletContextListener { static final List inConnections = Collections.synchronizedList(new ArrayList<>()); static final List outConnections = Collections.synchronizedList(new ArrayList<>()); static final List outCache = Collections.synchronizedList(new ArrayList<>()); - static final Integer sqlSync = 0; static JdbcTemplate sql; final public static HashMap childParsers = new HashMap<>(); -- cgit v1.2.3 From 02fd70cf59c30e3a9702eaf60d9e51f460efd8ca Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 6 Jul 2016 19:04:41 +0300 Subject: static components are evil --- src/main/java/com/juick/xmpp/s2s/CleaningUp.java | 25 +++-- src/main/java/com/juick/xmpp/s2s/Connection.java | 10 +- src/main/java/com/juick/xmpp/s2s/ConnectionIn.java | 44 +++++---- .../com/juick/xmpp/s2s/ConnectionListener.java | 12 ++- .../java/com/juick/xmpp/s2s/ConnectionOut.java | 34 +++---- .../java/com/juick/xmpp/s2s/ConnectionRouter.java | 36 +++---- src/main/java/com/juick/xmpp/s2s/JuickBot.java | 106 +++++++++++---------- .../java/com/juick/xmpp/s2s/XMPPComponent.java | 66 ++++++------- 8 files changed, 179 insertions(+), 154 deletions(-) (limited to 'src/main/java/com/juick/xmpp/s2s/XMPPComponent.java') diff --git a/src/main/java/com/juick/xmpp/s2s/CleaningUp.java b/src/main/java/com/juick/xmpp/s2s/CleaningUp.java index 48771580..14d97ed8 100644 --- a/src/main/java/com/juick/xmpp/s2s/CleaningUp.java +++ b/src/main/java/com/juick/xmpp/s2s/CleaningUp.java @@ -10,19 +10,24 @@ import java.util.Iterator; * @author ugnich */ public class CleaningUp implements Runnable { + XMPPComponent xmpp; + + public CleaningUp(XMPPComponent xmpp) { + this.xmpp = xmpp; + } @Override public void run() { while (true) { try { - PrintWriter statsFile = new PrintWriter(XMPPComponent.STATSFILE, "UTF-8"); + PrintWriter statsFile = new PrintWriter(xmpp.STATSFILE, "UTF-8"); statsFile.write("

Threads: " + Thread.activeCount() + "

"); - statsFile.write("

Out (" + XMPPComponent.outConnections.size() + ")

"); + statsFile.write("

Out (" + xmpp.outConnections.size() + ")

tosidinactiveout packetsout bytes
"); long now = System.currentTimeMillis(); - synchronized (XMPPComponent.outConnections) { - for (Iterator i = XMPPComponent.outConnections.iterator(); i.hasNext();) { + synchronized (xmpp.outConnections) { + for (Iterator i = xmpp.outConnections.iterator(); i.hasNext();) { ConnectionOut c = i.next(); int inactive = (int) ((double) (now - c.tsLocalData) / 1000.0); if (inactive > 900) { @@ -40,10 +45,10 @@ public class CleaningUp implements Runnable { } } - statsFile.write("
tosidinactiveout packetsout bytes

In (" + XMPPComponent.inConnections.size() + ")

"); + statsFile.write("
fromsidinactivein packets

In (" + xmpp.inConnections.size() + ")

"); - synchronized (XMPPComponent.inConnections) { - for (Iterator i = XMPPComponent.inConnections.iterator(); i.hasNext();) { + synchronized (xmpp.inConnections) { + for (Iterator i = xmpp.inConnections.iterator(); i.hasNext();) { ConnectionIn c = i.next(); int inactive = (int) ((double) (now - c.tsRemoteData) / 1000.0); if (inactive > 900) { @@ -73,10 +78,10 @@ public class CleaningUp implements Runnable { } } - statsFile.write("
fromsidinactivein packets

Cache (" + XMPPComponent.outCache.size() + ")

"); + statsFile.write("
hostlivesize

Cache (" + xmpp.outCache.size() + ")

"); - synchronized (XMPPComponent.outCache) { - for (Iterator i = XMPPComponent.outCache.iterator(); i.hasNext();) { + synchronized (xmpp.outCache) { + for (Iterator i = xmpp.outCache.iterator(); i.hasNext();) { CacheEntry c = i.next(); int inactive = (int) ((double) (now - c.tsCreated) / 1000.0); if (inactive > 600) { diff --git a/src/main/java/com/juick/xmpp/s2s/Connection.java b/src/main/java/com/juick/xmpp/s2s/Connection.java index c1bbf22e..eae6efaa 100644 --- a/src/main/java/com/juick/xmpp/s2s/Connection.java +++ b/src/main/java/com/juick/xmpp/s2s/Connection.java @@ -30,6 +30,7 @@ public class Connection { public long tsLocalData = 0; public long bytesLocal = 0; public long packetsLocal = 0; + XMPPComponent xmpp; Socket socket; public static final String NS_DB = "jabber:server:dialback"; public static final String NS_TLS = "urn:ietf:params:xml:ns:xmpp-tls"; @@ -52,17 +53,18 @@ public class Connection { }; - public Connection() throws XmlPullParserException, KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableKeyException, KeyManagementException { + public Connection(XMPPComponent xmpp) throws XmlPullParserException, KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableKeyException, KeyManagementException { + this.xmpp = xmpp; tsCreated = System.currentTimeMillis(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); KeyStore ks = KeyStore.getInstance("JKS"); - try (InputStream ksIs = new FileInputStream(XMPPComponent.keystore)) { - ks.load(ksIs, XMPPComponent.keystorePassword.toCharArray()); + try (InputStream ksIs = new FileInputStream(xmpp.keystore)) { + ks.load(ksIs, xmpp.keystorePassword.toCharArray()); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory .getDefaultAlgorithm()); - kmf.init(ks, XMPPComponent.keystorePassword.toCharArray()); + kmf.init(ks, xmpp.keystorePassword.toCharArray()); sc = SSLContext.getInstance("TLSv1.2"); sc.init(kmf.getKeyManagers(), trustAllCerts, new SecureRandom()); diff --git a/src/main/java/com/juick/xmpp/s2s/ConnectionIn.java b/src/main/java/com/juick/xmpp/s2s/ConnectionIn.java index 93e761a0..ea1cf0b1 100644 --- a/src/main/java/com/juick/xmpp/s2s/ConnectionIn.java +++ b/src/main/java/com/juick/xmpp/s2s/ConnectionIn.java @@ -31,9 +31,13 @@ public class ConnectionIn extends Connection implements Runnable { final public List from = new ArrayList<>(); public long tsRemoteData = 0; public long packetsRemote = 0; + XMPPComponent xmpp; + JuickBot bot; - public ConnectionIn(Socket socket) throws Exception { - super(); + public ConnectionIn(XMPPComponent xmpp, JuickBot bot, Socket socket) throws Exception { + super(xmpp); + this.xmpp = xmpp; + this.bot = bot; this.socket = socket; streamID = UUID.randomUUID().toString(); restartParser(); @@ -69,19 +73,19 @@ public class ConnectionIn extends Connection implements Runnable { String dfrom = parser.getAttributeValue(null, "from"); String to = parser.getAttributeValue(null, "to"); LOGGER.info("STREAM FROM " + dfrom + " TO " + to + " " + streamID + " ASKING FOR DIALBACK"); - if (dfrom.endsWith(XMPPComponent.HOSTNAME) && (dfrom.equals(XMPPComponent.HOSTNAME) || dfrom.endsWith("." + XMPPComponent.HOSTNAME))) { + if (dfrom.endsWith(xmpp.HOSTNAME) && (dfrom.equals(xmpp.HOSTNAME) || dfrom.endsWith("." + xmpp.HOSTNAME))) { break; } - if (to != null && to.equals(XMPPComponent.HOSTNAME)) { + if (to != null && to.equals(xmpp.HOSTNAME)) { String dbKey = XmlUtils.getTagText(parser); updateTsRemoteData(); - ConnectionOut c = XMPPComponent.getConnectionOut(dfrom, false); + ConnectionOut c = xmpp.getConnectionOut(dfrom, false); if (c != null) { c.sendDialbackVerify(streamID, dbKey); } else { - c = new ConnectionOut(dfrom, streamID, dbKey); - XMPPComponent.executorService.submit(c); + c = new ConnectionOut(xmpp, dfrom, streamID, dbKey); + xmpp.executorService.submit(c); } } else { throw new HostUnknownException("STREAM FROM " + dfrom + " " + streamID + " INVALID TO " + to); @@ -107,15 +111,15 @@ public class ConnectionIn extends Connection implements Runnable { } else if (tag.equals("presence") && checkFromTo(parser)) { Presence p = Presence.parse(parser, null); if (p != null && (p.type == null || !p.type.equals(Presence.Type.error))) { - JuickBot.incomingPresence(p); + bot.incomingPresence(p); } } else if (tag.equals("message") && checkFromTo(parser)) { updateTsRemoteData(); - Message msg = Message.parse(parser, XMPPComponent.childParsers); + Message msg = Message.parse(parser, xmpp.childParsers); if (msg != null && (msg.type == null || !msg.type.equals(Message.Type.error))) { LOGGER.info("STREAM " + streamID + ": " + msg.toString()); - if (!JuickBot.incomingMessage(msg)) { - XMPPComponent.connRouter.router.send(msg.toString()); + if (!bot.incomingMessage(msg)) { + xmpp.connRouter.router.send(msg.toString()); } } } else if (tag.equals("iq") && checkFromTo(parser)) { @@ -124,7 +128,7 @@ public class ConnectionIn extends Connection implements Runnable { String xml = XmlUtils.parseToString(parser, true); if (type == null || !type.equals(Iq.Type.error)) { LOGGER.info("STREAM " + streamID + ": " + xml); - XMPPComponent.connRouter.router.send(xml); + xmpp.connRouter.router.send(xml); } } else if (!isSecured() && tag.equals("starttls")) { LOGGER.info("STREAM " + streamID + " SECURING"); @@ -140,7 +144,7 @@ public class ConnectionIn extends Connection implements Runnable { } catch (SSLException sex) { LOGGER.warning("STREAM " + streamID + " SSL ERROR"); sendStanza(""); - XMPPComponent.removeConnectionIn(this); + xmpp.removeConnectionIn(this); closeConnection(); } } else if (isSecured() && tag.equals("stream") && parser.getNamespace().equals(NS_STREAM)) { @@ -150,17 +154,17 @@ public class ConnectionIn extends Connection implements Runnable { } } LOGGER.warning("STREAM " + streamID + " FINISHED"); - XMPPComponent.removeConnectionIn(this); + xmpp.removeConnectionIn(this); closeConnection(); } catch (EOFException ex) { LOGGER.info(String.format("STREAM %s CLOSED (dirty)", streamID)); - XMPPComponent.removeConnectionIn(this); + xmpp.removeConnectionIn(this); closeConnection(); } catch (HostUnknownException e) { LOGGER.warning(e.getMessage()); } catch (Exception e) { LOGGER.log(Level.WARNING, "STREAM " + streamID + " ERROR", e); - XMPPComponent.removeConnectionIn(this); + xmpp.removeConnectionIn(this); closeConnection(); } } @@ -172,10 +176,10 @@ public class ConnectionIn extends Connection implements Runnable { void sendOpenStream(String from, boolean xmppversionnew) throws IOException { String openStream = ""; + xmpp.HOSTNAME + "' id='" + streamID + "' version='1.0'>"; if (xmppversionnew) { openStream += ""; - if (!isSecured() && !XMPPComponent.brokenSSLhosts.contains(from)) { + if (!isSecured() && !xmpp.brokenSSLhosts.contains(from)) { openStream += ""; } openStream += ""; @@ -185,7 +189,7 @@ public class ConnectionIn extends Connection implements Runnable { public void sendDialbackResult(String sfrom, String type) { try { - sendStanza(""); + sendStanza(""); if (type.equals("valid")) { from.add(sfrom); LOGGER.info("STREAM FROM " + sfrom + " " + streamID + " READY"); @@ -200,7 +204,7 @@ public class ConnectionIn extends Connection implements Runnable { String cto = parser.getAttributeValue(null, "to"); if (cfrom != null && cto != null && !cfrom.isEmpty() && !cto.isEmpty()) { JID jidto = new JID(cto); - if (jidto.Host != null && jidto.Username != null && jidto.Host.equals(XMPPComponent.HOSTNAME) && jidto.Username.matches("^[a-zA-Z0-9\\-]{2,16}$")) { + if (jidto.Host != null && jidto.Username != null && jidto.Host.equals(xmpp.HOSTNAME) && jidto.Username.matches("^[a-zA-Z0-9\\-]{2,16}$")) { JID jidfrom = new JID(cfrom); int size = from.size(); for (int i = 0; i < size; i++) { diff --git a/src/main/java/com/juick/xmpp/s2s/ConnectionListener.java b/src/main/java/com/juick/xmpp/s2s/ConnectionListener.java index 569d3db0..607397a8 100644 --- a/src/main/java/com/juick/xmpp/s2s/ConnectionListener.java +++ b/src/main/java/com/juick/xmpp/s2s/ConnectionListener.java @@ -13,6 +13,12 @@ public class ConnectionListener implements Runnable { private static final Logger logger = Logger.getLogger(ConnectionListener.class.getName()); + XMPPComponent xmpp; + + public ConnectionListener(XMPPComponent xmpp) { + this.xmpp = xmpp; + } + @Override public void run() { try { @@ -21,9 +27,9 @@ public class ConnectionListener implements Runnable { while (true) { try { Socket socket = listener.accept(); - ConnectionIn client = new ConnectionIn(socket); - XMPPComponent.addConnectionIn(client); - XMPPComponent.executorService.submit(client); + ConnectionIn client = new ConnectionIn(xmpp, new JuickBot(xmpp), socket); + xmpp.addConnectionIn(client); + xmpp.executorService.submit(client); } catch (Exception e) { logger.log(Level.SEVERE, "s2s error", e); } diff --git a/src/main/java/com/juick/xmpp/s2s/ConnectionOut.java b/src/main/java/com/juick/xmpp/s2s/ConnectionOut.java index d3a10406..b79cb49a 100644 --- a/src/main/java/com/juick/xmpp/s2s/ConnectionOut.java +++ b/src/main/java/com/juick/xmpp/s2s/ConnectionOut.java @@ -26,16 +26,18 @@ public class ConnectionOut extends Connection implements Runnable { public boolean streamReady = false; public String to; + XMPPComponent xmpp; String checkSID = null; String dbKey = null; - public ConnectionOut(String hostname) throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, XmlPullParserException, KeyManagementException, KeyStoreException, IOException { - super(); + public ConnectionOut(XMPPComponent xmpp, String hostname) throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, XmlPullParserException, KeyManagementException, KeyStoreException, IOException { + super(xmpp); + this.xmpp = xmpp; to = hostname; } - public ConnectionOut(String hostname, String checkSID, String dbKey) throws Exception { - super(); + public ConnectionOut(XMPPComponent xmpp, String hostname, String checkSID, String dbKey) throws Exception { + super(xmpp); to = hostname; this.checkSID = checkSID; this.dbKey = dbKey; @@ -44,15 +46,15 @@ public class ConnectionOut extends Connection implements Runnable { void sendOpenStream() throws IOException { sendStanza(""); + xmpp.HOSTNAME + "' to='" + to + "' version='1.0'>"); } void processDialback() throws Exception { if (checkSID != null) { sendDialbackVerify(checkSID, dbKey); } - sendStanza("" + - generateDialbackKey(to, XMPPComponent.HOSTNAME, streamID) + ""); + sendStanza("" + + generateDialbackKey(to, xmpp.HOSTNAME, streamID) + ""); } @Override @@ -76,7 +78,7 @@ public class ConnectionOut extends Connection implements Runnable { } LOGGER.info("STREAM TO " + to + " " + streamID + " OPEN"); - XMPPComponent.addConnectionOut(ConnectionOut.this); + xmpp.addConnectionOut(ConnectionOut.this); boolean xmppversionnew = parser.getAttributeValue(null, "version") != null; if (!xmppversionnew) { processDialback(); @@ -95,7 +97,7 @@ public class ConnectionOut extends Connection implements Runnable { streamReady = true; LOGGER.info("STREAM TO " + to + " " + streamID + " READY"); - String cache = XMPPComponent.getFromCache(to); + String cache = xmpp.getFromCache(to); if (cache != null) { LOGGER.info("STREAM TO " + to + " " + streamID + " SENDING CACHE"); sendStanza(cache); @@ -110,7 +112,7 @@ public class ConnectionOut extends Connection implements Runnable { String type = parser.getAttributeValue(null, "type"); String sid = parser.getAttributeValue(null, "id"); if (from != null && from.equals(to) && sid != null && !sid.isEmpty() && type != null) { - ConnectionIn c = XMPPComponent.getConnectionIn(sid); + ConnectionIn c = xmpp.getConnectionIn(sid); if (c != null) { c.sendDialbackResult(from, type); } @@ -118,7 +120,7 @@ public class ConnectionOut extends Connection implements Runnable { XmlUtils.skip(parser); } else if (tag.equals("features") && parser.getNamespace().equals(NS_STREAM)) { StreamFeatures features = StreamFeatures.parse(parser); - if (!isSecured() && features.STARTTLS >= 0 && !XMPPComponent.brokenSSLhosts.contains(to)) { + if (!isSecured() && features.STARTTLS >= 0 && !xmpp.brokenSSLhosts.contains(to)) { System.out.println("STREAM TO " + to + " " + streamID + " SECURING"); sendStanza(""); } else { @@ -136,7 +138,7 @@ public class ConnectionOut extends Connection implements Runnable { } catch (SSLException sex) { LOGGER.log(Level.SEVERE, String.format("s2s ssl error: %s %s", to, streamID), sex); sendStanza(""); - XMPPComponent.removeConnectionOut(this); + xmpp.removeConnectionOut(this); closeConnection(); } } else if (isSecured() && tag.equals("stream") && parser.getNamespace().equals(NS_STREAM)) { @@ -147,22 +149,22 @@ public class ConnectionOut extends Connection implements Runnable { } LOGGER.warning("STREAM TO " + to + " " + streamID + " FINISHED"); - XMPPComponent.removeConnectionOut(ConnectionOut.this); + xmpp.removeConnectionOut(ConnectionOut.this); closeConnection(); } catch (EOFException eofex) { LOGGER.info(String.format("STREAM %s %s CLOSED (dirty)", to, streamID)); - XMPPComponent.removeConnectionOut(ConnectionOut.this); + xmpp.removeConnectionOut(ConnectionOut.this); closeConnection(); } catch (Exception e) { LOGGER.log(Level.SEVERE, String.format("s2s out exception: %s %s", to, streamID), e); - XMPPComponent.removeConnectionOut(ConnectionOut.this); + xmpp.removeConnectionOut(ConnectionOut.this); closeConnection(); } } public void sendDialbackVerify(String sid, String key) { try { - sendStanza("" + key + ""); + sendStanza("" + key + ""); } catch (IOException e) { LOGGER.log(Level.WARNING, "STREAM TO " + to + " " + streamID + " ERROR", e); } diff --git a/src/main/java/com/juick/xmpp/s2s/ConnectionRouter.java b/src/main/java/com/juick/xmpp/s2s/ConnectionRouter.java index 0030834a..588cfe2c 100644 --- a/src/main/java/com/juick/xmpp/s2s/ConnectionRouter.java +++ b/src/main/java/com/juick/xmpp/s2s/ConnectionRouter.java @@ -27,8 +27,10 @@ public class ConnectionRouter implements Stream.StreamListener, private String password; Stream router; Socket socket; + XMPPComponent xmpp; - ConnectionRouter(String componentName, String password) { + ConnectionRouter(XMPPComponent s2s, String componentName, String password) { + this.xmpp = s2s; this.componentName = componentName; this.password = password; reconnect(); @@ -56,11 +58,11 @@ public class ConnectionRouter implements Stream.StreamListener, List jids = new ArrayList<>(); if (jmsg.FriendsOnly) { - jids = SubscriptionsQueries.getJIDSubscribedToUser(XMPPComponent.sql, jmsg.getUser().getUID(), jmsg.FriendsOnly); + jids = SubscriptionsQueries.getJIDSubscribedToUser(xmpp.sql, jmsg.getUser().getUID(), jmsg.FriendsOnly); } else { - List users = SubscriptionsQueries.getSubscribedUsers(XMPPComponent.sql, jmsg.getUser().getUID(), jmsg.getMID()); + List users = SubscriptionsQueries.getSubscribedUsers(xmpp.sql, jmsg.getUser().getUID(), jmsg.getMID()); for (User user : users) { - for (String jid : UserQueries.getJIDsbyUID(XMPPComponent.sql, user.getUID())) { + for (String jid : UserQueries.getJIDsbyUID(xmpp.sql, user.getUID())) { jids.add(jid); } } @@ -92,7 +94,7 @@ public class ConnectionRouter implements Stream.StreamListener, for (String jid : jids) { msg.to = new JID(jid); - XMPPComponent.sendOut(msg); + xmpp.sendOut(msg); } } @@ -101,9 +103,9 @@ public class ConnectionRouter implements Stream.StreamListener, String replyQuote; String replyTo; - users = SubscriptionsQueries.getUsersSubscribedToComments(XMPPComponent.sql, jmsg.getMID(), jmsg.getUser().getUID()); - com.juick.Message replyMessage = jmsg.ReplyTo > 0 ? MessagesQueries.getReply(XMPPComponent.sql, jmsg.getMID(), jmsg.ReplyTo) - : MessagesQueries.getMessage(XMPPComponent.sql, jmsg.getMID()); + users = SubscriptionsQueries.getUsersSubscribedToComments(xmpp.sql, jmsg.getMID(), jmsg.getUser().getUID()); + com.juick.Message replyMessage = jmsg.ReplyTo > 0 ? MessagesQueries.getReply(xmpp.sql, jmsg.getMID(), jmsg.ReplyTo) + : MessagesQueries.getMessage(xmpp.sql, jmsg.getMID()); replyTo = replyMessage.getUser().getUName(); replyQuote = getReplyQuote(replyMessage); @@ -120,9 +122,9 @@ public class ConnectionRouter implements Stream.StreamListener, msg.type = Message.Type.chat; msg.addChild(jmsg); for (User user : users) { - for (String jid : UserQueries.getJIDsbyUID(XMPPComponent.sql, user.getUID())) { + for (String jid : UserQueries.getJIDsbyUID(xmpp.sql, user.getUID())) { msg.to = new JID(jid); - XMPPComponent.sendOut(msg); + xmpp.sendOut(msg); } } } @@ -140,8 +142,8 @@ public class ConnectionRouter implements Stream.StreamListener, public void sendJuickRecommendation(JuickMessage recomm) { List users; JuickMessage jmsg; - jmsg = new JuickMessage(MessagesQueries.getMessage(XMPPComponent.sql, recomm.getMID())); - users = SubscriptionsQueries.getUsersSubscribedToUserRecommendations(XMPPComponent.sql, + jmsg = new JuickMessage(MessagesQueries.getMessage(xmpp.sql, recomm.getMID())); + users = SubscriptionsQueries.getUsersSubscribedToUserRecommendations(xmpp.sql, recomm.getUser().getUID(), recomm.getMID(), jmsg.getUser().getUID()); String txt = "Recommended by @" + recomm.getUser().getUName() + ":\n"; @@ -178,9 +180,9 @@ public class ConnectionRouter implements Stream.StreamListener, } for (User user : users) { - for (String jid : UserQueries.getJIDsbyUID(XMPPComponent.sql, user.getUID())) { + for (String jid : UserQueries.getJIDsbyUID(xmpp.sql, user.getUID())) { msg.to = new JID(jid); - XMPPComponent.sendOut(msg); + xmpp.sendOut(msg); } } } @@ -190,7 +192,7 @@ public class ConnectionRouter implements Stream.StreamListener, JID jid = iq.to; if (!jid.Host.equals(componentName)) { logger.info("STREAM ROUTER (IQ): " + iq.toString()); - XMPPComponent.sendOut(iq); + xmpp.sendOut(iq); } return false; } @@ -213,7 +215,7 @@ public class ConnectionRouter implements Stream.StreamListener, } } } else { - XMPPComponent.sendOut(xmsg); + xmpp.sendOut(xmsg); } } @@ -222,7 +224,7 @@ public class ConnectionRouter implements Stream.StreamListener, JID jid = presence.to; if (!jid.Host.equals(componentName)) { logger.info("STREAM ROUTER (PRESENCE): " + presence.toString()); - XMPPComponent.sendOut(presence); + xmpp.sendOut(presence); } } diff --git a/src/main/java/com/juick/xmpp/s2s/JuickBot.java b/src/main/java/com/juick/xmpp/s2s/JuickBot.java index 357b070f..18e7580d 100644 --- a/src/main/java/com/juick/xmpp/s2s/JuickBot.java +++ b/src/main/java/com/juick/xmpp/s2s/JuickBot.java @@ -19,6 +19,10 @@ import java.util.regex.Pattern; * @author ugnich */ public class JuickBot { + XMPPComponent xmpp; + public JuickBot(XMPPComponent xmpp) { + this.xmpp = xmpp; + } public static final JID JuickJID = new JID("juick", "juick.com", "Juick"); private static final String HELPTEXT = @@ -55,7 +59,7 @@ public class JuickBot { + "\n" + "Read more: http://juick.com/help/"; - public static boolean incomingPresence(Presence p) throws Exception { + public boolean incomingPresence(Presence p) throws Exception { final String username = p.to.Username.toLowerCase(); final boolean toJuick = username.equals("juick"); @@ -64,12 +68,12 @@ public class JuickBot { reply.from = new JID(p.to.Username, p.to.Host, null); reply.to = new JID(p.from.Username, p.from.Host, null); reply.type = Presence.Type.unsubscribe; - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); return true; } else if (p.type.equals(Presence.Type.probe)) { int uid_to = 0; if (!toJuick) { - uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, username); + uid_to = UserQueries.getUIDbyName(xmpp.sql, username); } if (toJuick || uid_to > 0) { @@ -78,12 +82,12 @@ public class JuickBot { reply.from.Resource = "Juick"; reply.to = p.from; reply.priority = 10; - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); } else { Presence reply = new Presence(p.to, p.from, Presence.Type.error); reply.id = p.id; reply.addChild(new Error(Error.Type.cancel, "item-not-found")); - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); return true; } return true; @@ -92,46 +96,46 @@ public class JuickBot { if (toJuick) { canSubscribe = true; } else { - int uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, username); + int uid_to = UserQueries.getUIDbyName(xmpp.sql, username); if (uid_to > 0) { - PMQueries.addPMinRoster(XMPPComponent.sql, uid_to, p.from.Bare()); + PMQueries.addPMinRoster(xmpp.sql, uid_to, p.from.Bare()); canSubscribe = true; } } if (canSubscribe) { Presence reply = new Presence(p.to, p.from, Presence.Type.subscribed); - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); reply.from.Resource = "Juick"; reply.priority = 10; reply.type = null; - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); return true; } else { Presence reply = new Presence(p.to, p.from, Presence.Type.error); reply.id = p.id; reply.addChild(new Error(Error.Type.cancel, "item-not-found")); - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); return true; } } else if (p.type.equals(Presence.Type.unsubscribe)) { if (!toJuick) { - int uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, username); + int uid_to = UserQueries.getUIDbyName(xmpp.sql, username); if (uid_to > 0) { - PMQueries.removePMinRoster(XMPPComponent.sql, uid_to, p.from.Bare()); + PMQueries.removePMinRoster(xmpp.sql, uid_to, p.from.Bare()); } } Presence reply = new Presence(p.to, p.from, Presence.Type.unsubscribed); - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); } return false; } - public static boolean incomingMessage(Message msg) throws Exception { + public boolean incomingMessage(Message msg) throws Exception { if (msg.body == null || msg.body.isEmpty()) { return true; } @@ -140,9 +144,9 @@ public class JuickBot { User user_from = null; String signuphash = ""; - user_from = UserQueries.getUserByJID(XMPPComponent.sql, msg.from.Bare()); + user_from = UserQueries.getUserByJID(xmpp.sql, msg.from.Bare()); if (user_from == null) { - signuphash = UserQueries.getSignUpHashByJID(XMPPComponent.sql, msg.from.Bare()); + signuphash = UserQueries.getSignUpHashByJID(xmpp.sql, msg.from.Bare()); } if (user_from == null) { @@ -152,7 +156,7 @@ public class JuickBot { } else { reply.body = "Внимание, системное сообщение!\nВаш JabberID не обнаружен в списке доверенных. Для того, чтобы отправить сообщение пользователю " + username + "@juick.com, пожалуйста зарегистрируйте свой JabberID в системе: http://juick.com/signup?type=xmpp&hash=" + signuphash + "\nЕсли у вас уже есть учетная запись на Juick, вы сможете присоединить этот JabberID к ней.\n\nWarning, system message!\nYour JabberID is not found in our server's white list. To send a message to " + username + "@juick.com, please sign up: http://juick.com/signup?type=xmpp&hash=" + signuphash + "\nIf you already have an account on Juick, you will be proposed to attach this JabberID to your existing account."; } - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); return true; } @@ -160,19 +164,19 @@ public class JuickBot { return incomingMessageJuick(user_from, msg); } - int uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, username); + int uid_to = UserQueries.getUIDbyName(xmpp.sql, username); if (uid_to == 0) { Message reply = new Message(msg.to, msg.from, Message.Type.error); reply.id = msg.id; reply.addChild(new Error(Error.Type.cancel, "item-not-found")); - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); return true; } boolean success = false; - if (!UserQueries.isInBLAny(XMPPComponent.sql, uid_to, user_from.getUID())) { - success = PMQueries.createPM(XMPPComponent.sql, user_from.getUID(), uid_to, msg.body); + if (!UserQueries.isInBLAny(xmpp.sql, uid_to, user_from.getUID())) { + success = PMQueries.createPM(xmpp.sql, user_from.getUID(), uid_to, msg.body); } if (success) { @@ -183,19 +187,19 @@ public class JuickBot { jmsg.setUser(user_from); jmsg.setText(msg.body); m.childs.add(jmsg); - XMPPComponent.connRouter.router.send(m.toString()); + xmpp.connRouter.router.send(m.toString()); m.to.Host = "ws.juick.com"; - XMPPComponent.connRouter.router.send(m.toString()); + xmpp.connRouter.router.send(m.toString()); List jids; boolean inroster = false; - jids = UserQueries.getJIDsbyUID(XMPPComponent.sql, uid_to); + jids = UserQueries.getJIDsbyUID(xmpp.sql, uid_to); for (String jid : jids) { Message mm = new Message(); mm.to = new JID(jid); mm.type = Message.Type.chat; - inroster = PMQueries.havePMinRoster(XMPPComponent.sql, user_from.getUID(), jid); + inroster = PMQueries.havePMinRoster(xmpp.sql, user_from.getUID(), jid); if (inroster) { mm.from = new JID(jmsg.getUser().getUName(), "juick.com", "Juick"); mm.body = msg.body; @@ -203,20 +207,20 @@ public class JuickBot { mm.from = new JID("juick", "juick.com", "Juick"); mm.body = "Private message from @" + jmsg.getUser().getUName() + ":\n" + msg.body; } - XMPPComponent.sendOut(mm); + xmpp.sendOut(mm); } } else { Message reply = new Message(msg.to, msg.from, Message.Type.error); reply.id = msg.id; reply.addChild(new Error(Error.Type.cancel, "not-allowed")); - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); } return true; } private static Pattern regexPM = Pattern.compile("^\\@(\\S+)\\s+([\\s\\S]+)$"); - public static boolean incomingMessageJuick(User user_from, Message msg) throws Exception { + public boolean incomingMessageJuick(User user_from, Message msg) throws Exception { String command = msg.body.trim(); int commandlen = command.length(); @@ -253,29 +257,29 @@ public class JuickBot { return false; } - private static void commandPing(Message m) throws Exception { + private void commandPing(Message m) throws Exception { Presence p = new Presence(JuickJID, m.from); p.priority = 10; - XMPPComponent.sendOut(p); + xmpp.sendOut(p); Message reply = new Message(JuickJID, m.from, Message.Type.chat); reply.body = "PONG"; - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); } - private static void commandHelp(Message m) throws Exception { + private void commandHelp(Message m) throws Exception { Message reply = new Message(JuickJID, m.from, Message.Type.chat); reply.body = HELPTEXT; - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); } - private static void commandLogin(Message m, User user_from) throws Exception { + private void commandLogin(Message m, User user_from) throws Exception { Message reply = new Message(JuickJID, m.from, Message.Type.chat); - reply.body = "http://juick.com/login?" + UserQueries.getHashByUID(XMPPComponent.sql, user_from.getUID()); - XMPPComponent.sendOut(reply); + reply.body = "http://juick.com/login?" + UserQueries.getHashByUID(xmpp.sql, user_from.getUID()); + xmpp.sendOut(reply); } - private static void commandPM(Message m, User user_from, String user_to, String body) throws Exception { + private void commandPM(Message m, User user_from, String user_to, String body) throws Exception { int ret = 0; int uid_to = 0; @@ -283,15 +287,15 @@ public class JuickBot { boolean haveInRoster = false; if (user_to.indexOf('@') > 0) { - uid_to = UserQueries.getUIDbyJID(XMPPComponent.sql, user_to); + uid_to = UserQueries.getUIDbyJID(xmpp.sql, user_to); } else { - uid_to = UserQueries.getUIDbyName(XMPPComponent.sql, user_to); + uid_to = UserQueries.getUIDbyName(xmpp.sql, user_to); } if (uid_to > 0) { - if (!UserQueries.isInBLAny(XMPPComponent.sql, uid_to, user_from.getUID())) { - if (PMQueries.createPM(XMPPComponent.sql, user_from.getUID(), uid_to, body)) { - jids_to = UserQueries.getJIDsbyUID(XMPPComponent.sql, uid_to); + if (!UserQueries.isInBLAny(xmpp.sql, uid_to, user_from.getUID())) { + if (PMQueries.createPM(xmpp.sql, user_from.getUID(), uid_to, body)) { + jids_to = UserQueries.getJIDsbyUID(xmpp.sql, uid_to); ret = 200; } else { ret = 500; @@ -311,16 +315,16 @@ public class JuickBot { jmsg.setUser(user_from); jmsg.setText(body); msg.childs.add(jmsg); - XMPPComponent.connRouter.router.send(msg.toString()); + xmpp.connRouter.router.send(msg.toString()); msg.to.Host = "ws.juick.com"; - XMPPComponent.connRouter.router.send(msg.toString()); + xmpp.connRouter.router.send(msg.toString()); for (String jid : jids_to) { Message mm = new Message(); mm.to = new JID(jid); mm.type = Message.Type.chat; - haveInRoster = PMQueries.havePMinRoster(XMPPComponent.sql, user_from.getUID(), jid); + haveInRoster = PMQueries.havePMinRoster(xmpp.sql, user_from.getUID(), jid); if (haveInRoster) { mm.from = new JID(user_from.getUName(), "juick.com", "Juick"); mm.body = body; @@ -328,7 +332,7 @@ public class JuickBot { mm.from = new JID("juick", "juick.com", "Juick"); mm.body = "Private message from @" + user_from.getUName() + ":\n" + body; } - XMPPComponent.sendOut(mm); + xmpp.sendOut(mm); } } @@ -340,12 +344,12 @@ public class JuickBot { reply.type = Message.Type.error; reply.body = "Error " + ret; } - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); } - private static void commandBLShow(Message m, User user_from) throws Exception { - List blusers = UserQueries.getUserBLUsers(XMPPComponent.sql, user_from.getUID()); - List bltags = TagQueries.getUserBLTags(XMPPComponent.sql, user_from.getUID()); + private void commandBLShow(Message m, User user_from) throws Exception { + List blusers = UserQueries.getUserBLUsers(xmpp.sql, user_from.getUID()); + List bltags = TagQueries.getUserBLTags(xmpp.sql, user_from.getUID()); String txt = ""; if (bltags.size() > 0) { @@ -368,6 +372,6 @@ public class JuickBot { Message reply = new Message(JuickJID, m.from, Message.Type.chat); reply.body = txt; - XMPPComponent.sendOut(reply); + xmpp.sendOut(reply); } } diff --git a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java index bb736b5e..2b75fef1 100644 --- a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java +++ b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java @@ -32,45 +32,45 @@ public class XMPPComponent implements ServletContextListener { private static final Logger LOGGER = Logger.getLogger(XMPPComponent.class.getName()); - public static final ExecutorService executorService = Executors.newCachedThreadPool(); - - public static String HOSTNAME = null; - public static String STATSFILE = null; - public static String keystore; - public static String keystorePassword; - public static List brokenSSLhosts; - public static ConnectionRouter connRouter; - static final List inConnections = Collections.synchronizedList(new ArrayList<>()); - static final List outConnections = Collections.synchronizedList(new ArrayList<>()); - static final List outCache = Collections.synchronizedList(new ArrayList<>()); - static JdbcTemplate sql; - final public static HashMap childParsers = new HashMap<>(); - - public static void addConnectionIn(ConnectionIn c) { + public final ExecutorService executorService = Executors.newCachedThreadPool(); + + public String HOSTNAME = null; + public String STATSFILE = null; + public String keystore; + public String keystorePassword; + public List brokenSSLhosts; + public ConnectionRouter connRouter; + final List inConnections = Collections.synchronizedList(new ArrayList<>()); + final List outConnections = Collections.synchronizedList(new ArrayList<>()); + final List outCache = Collections.synchronizedList(new ArrayList<>()); + JdbcTemplate sql; + final public HashMap childParsers = new HashMap<>(); + + public void addConnectionIn(ConnectionIn c) { synchronized (inConnections) { inConnections.add(c); } } - public static void addConnectionOut(ConnectionOut c) { + public void addConnectionOut(ConnectionOut c) { synchronized (outConnections) { outConnections.add(c); } } - public static void removeConnectionIn(ConnectionIn c) { + public void removeConnectionIn(ConnectionIn c) { synchronized (inConnections) { inConnections.remove(c); } } - public static void removeConnectionOut(ConnectionOut c) { + public void removeConnectionOut(ConnectionOut c) { synchronized (outConnections) { outConnections.remove(c); } } - public static String getFromCache(String hostname) { + public String getFromCache(String hostname) { CacheEntry ret = null; synchronized (outCache) { for (Iterator i = outCache.iterator(); i.hasNext();) { @@ -85,7 +85,7 @@ public class XMPPComponent implements ServletContextListener { return (ret != null) ? ret.xml : null; } - public static ConnectionOut getConnectionOut(String hostname, boolean needReady) { + public ConnectionOut getConnectionOut(String hostname, boolean needReady) { synchronized (outConnections) { for (ConnectionOut c : outConnections) { if (c.to != null && c.to.equals(hostname) && (!needReady || c.streamReady)) { @@ -96,7 +96,7 @@ public class XMPPComponent implements ServletContextListener { return null; } - public static ConnectionIn getConnectionIn(String streamID) { + public ConnectionIn getConnectionIn(String streamID) { synchronized (inConnections) { for (ConnectionIn c : inConnections) { if (c.streamID != null && c.streamID.equals(streamID)) { @@ -107,11 +107,11 @@ public class XMPPComponent implements ServletContextListener { return null; } - public static void sendOut(Stanza s) { + public void sendOut(Stanza s) { sendOut(s.to.Host, s.toString()); } - public static void sendOut(String hostname, String xml) { + public void sendOut(String hostname, String xml) { boolean haveAnyConn = false; ConnectionOut connOut = null; @@ -155,8 +155,8 @@ public class XMPPComponent implements ServletContextListener { if (!haveAnyConn) { ConnectionOut connectionOut = null; try { - connectionOut = new ConnectionOut(hostname); - XMPPComponent.executorService.submit(connectionOut); + connectionOut = new ConnectionOut(this, hostname); + executorService.submit(connectionOut); } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | XmlPullParserException | KeyStoreException | KeyManagementException | IOException e) { LOGGER.log(Level.SEVERE, "s2s out error", e); } @@ -185,9 +185,9 @@ public class XMPPComponent implements ServletContextListener { sql = new JdbcTemplate(dataSource); childParsers.put(JuickMessage.XMLNS, new JuickMessage()); - executorService.submit(() -> connRouter = new ConnectionRouter(componentName, conf.getProperty("xmpp_password"))); - executorService.submit(new ConnectionListener()); - executorService.submit(new CleaningUp()); + executorService.submit(() -> connRouter = new ConnectionRouter(this, componentName, conf.getProperty("xmpp_password"))); + executorService.submit(new ConnectionListener(this)); + executorService.submit(new CleaningUp(this)); } catch (Exception e) { LOGGER.log(Level.SEVERE, "XMPPComponent error", e); } @@ -198,16 +198,16 @@ public class XMPPComponent implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent sce) { - synchronized (XMPPComponent.outConnections) { - for (Iterator i = XMPPComponent.outConnections.iterator(); i.hasNext();) { + synchronized (outConnections) { + for (Iterator i = outConnections.iterator(); i.hasNext();) { ConnectionOut c = i.next(); c.closeConnection(); i.remove(); } } - synchronized (XMPPComponent.inConnections) { - for (Iterator i = XMPPComponent.inConnections.iterator(); i.hasNext();) { + synchronized (inConnections) { + for (Iterator i = inConnections.iterator(); i.hasNext();) { ConnectionIn c = i.next(); c.closeConnection(); i.remove(); @@ -215,7 +215,7 @@ public class XMPPComponent implements ServletContextListener { } try { - XMPPComponent.connRouter.closeConnection(); + connRouter.closeConnection(); } catch (IOException e) { LOGGER.log(Level.WARNING, "router warning", e); } -- cgit v1.2.3 From 152f36927fa373c619778ca84c2f9532cc3f561b Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 6 Jul 2016 19:15:38 +0300 Subject: cleanup --- src/main/java/com/juick/xmpp/s2s/XMPPComponent.java | 2 -- 1 file changed, 2 deletions(-) (limited to 'src/main/java/com/juick/xmpp/s2s/XMPPComponent.java') diff --git a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java index 2b75fef1..245038d4 100644 --- a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java +++ b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java @@ -180,8 +180,6 @@ public class XMPPComponent implements ServletContextListener { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.Driver")); dataSource.setUrl(conf.getProperty("datasource_url")); - DriverManagerDataSource dataSourceSearch = new DriverManagerDataSource(); - dataSourceSearch.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.Driver")); sql = new JdbcTemplate(dataSource); childParsers.put(JuickMessage.XMLNS, new JuickMessage()); -- cgit v1.2.3 From 95869ef683a517eb48db1784150ded7661294f8a Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 6 Jul 2016 19:18:04 +0300 Subject: drop recursive dependency --- .../com/juick/xmpp/s2s/ConnectionListener.java | 41 ---------------------- .../java/com/juick/xmpp/s2s/XMPPComponent.java | 15 +++++++- 2 files changed, 14 insertions(+), 42 deletions(-) delete mode 100644 src/main/java/com/juick/xmpp/s2s/ConnectionListener.java (limited to 'src/main/java/com/juick/xmpp/s2s/XMPPComponent.java') diff --git a/src/main/java/com/juick/xmpp/s2s/ConnectionListener.java b/src/main/java/com/juick/xmpp/s2s/ConnectionListener.java deleted file mode 100644 index 607397a8..00000000 --- a/src/main/java/com/juick/xmpp/s2s/ConnectionListener.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.juick.xmpp.s2s; - -import java.net.ServerSocket; -import java.net.Socket; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * - * @author vt - */ -public class ConnectionListener implements Runnable { - - private static final Logger logger = Logger.getLogger(ConnectionListener.class.getName()); - - XMPPComponent xmpp; - - public ConnectionListener(XMPPComponent xmpp) { - this.xmpp = xmpp; - } - - @Override - public void run() { - try { - final ServerSocket listener = new ServerSocket(5269); - logger.info("s2s listener ready"); - while (true) { - try { - Socket socket = listener.accept(); - ConnectionIn client = new ConnectionIn(xmpp, new JuickBot(xmpp), socket); - xmpp.addConnectionIn(client); - xmpp.executorService.submit(client); - } catch (Exception e) { - logger.log(Level.SEVERE, "s2s error", e); - } - } - } catch (Exception e) { - logger.log(Level.SEVERE, "s2s listener exception", e); - } - } -} diff --git a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java index 245038d4..db7b11ac 100644 --- a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java +++ b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java @@ -10,6 +10,8 @@ import org.xmlpull.v1.XmlPullParserException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; @@ -184,8 +186,19 @@ public class XMPPComponent implements ServletContextListener { childParsers.put(JuickMessage.XMLNS, new JuickMessage()); executorService.submit(() -> connRouter = new ConnectionRouter(this, componentName, conf.getProperty("xmpp_password"))); - executorService.submit(new ConnectionListener(this)); executorService.submit(new CleaningUp(this)); + final ServerSocket listener = new ServerSocket(5269); + LOGGER.info("s2s listener ready"); + while (true) { + try { + Socket socket = listener.accept(); + ConnectionIn client = new ConnectionIn(this, new JuickBot(this), socket); + addConnectionIn(client); + executorService.submit(client); + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "s2s error", e); + } + } } catch (Exception e) { LOGGER.log(Level.SEVERE, "XMPPComponent error", e); } -- cgit v1.2.3 From 2ebd7a050acf477b68a72397395a026ec63d89dd Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 6 Jul 2016 19:34:54 +0300 Subject: separate thread for xmpp component --- src/main/java/com/juick/xmpp/s2s/XMPPComponent.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/main/java/com/juick/xmpp/s2s/XMPPComponent.java') diff --git a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java index db7b11ac..5cdce82a 100644 --- a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java +++ b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java @@ -35,6 +35,7 @@ public class XMPPComponent implements ServletContextListener { private static final Logger LOGGER = Logger.getLogger(XMPPComponent.class.getName()); public final ExecutorService executorService = Executors.newCachedThreadPool(); + ExecutorService xmppService = Executors.newSingleThreadExecutor(); public String HOSTNAME = null; public String STATSFILE = null; @@ -169,7 +170,7 @@ public class XMPPComponent implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { LOGGER.info("component initialized"); - executorService.submit(() -> { + xmppService.submit(() -> { Properties conf = new Properties(); try { conf.load(sce.getServletContext().getResourceAsStream("/WEB-INF/juick.conf")); -- cgit v1.2.3 From 7cbf108b84682fb17af15f528df3f0bd952fc58d Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 6 Jul 2016 19:47:18 +0300 Subject: refactoring --- .../java/com/juick/xmpp/s2s/XMPPComponent.java | 41 +++++++++++----------- 1 file changed, 21 insertions(+), 20 deletions(-) (limited to 'src/main/java/com/juick/xmpp/s2s/XMPPComponent.java') diff --git a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java index 5cdce82a..8ebdb76a 100644 --- a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java +++ b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java @@ -170,23 +170,23 @@ public class XMPPComponent implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { LOGGER.info("component initialized"); - xmppService.submit(() -> { - Properties conf = new Properties(); - try { - conf.load(sce.getServletContext().getResourceAsStream("/WEB-INF/juick.conf")); - HOSTNAME = conf.getProperty("hostname"); - String componentName = conf.getProperty("componentname"); - STATSFILE = conf.getProperty("statsfile"); - keystore = conf.getProperty("keystore"); - keystorePassword = conf.getProperty("keystore_password"); - brokenSSLhosts = Arrays.asList(conf.getProperty("broken_ssl_hosts", "").split(",")); - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.Driver")); - dataSource.setUrl(conf.getProperty("datasource_url")); - sql = new JdbcTemplate(dataSource); + Properties conf = new Properties(); + try { + conf.load(sce.getServletContext().getResourceAsStream("/WEB-INF/juick.conf")); + HOSTNAME = conf.getProperty("hostname"); + String componentName = conf.getProperty("componentname"); + STATSFILE = conf.getProperty("statsfile"); + keystore = conf.getProperty("keystore"); + keystorePassword = conf.getProperty("keystore_password"); + brokenSSLhosts = Arrays.asList(conf.getProperty("broken_ssl_hosts", "").split(",")); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.Driver")); + dataSource.setUrl(conf.getProperty("datasource_url")); + sql = new JdbcTemplate(dataSource); - childParsers.put(JuickMessage.XMLNS, new JuickMessage()); - executorService.submit(() -> connRouter = new ConnectionRouter(this, componentName, conf.getProperty("xmpp_password"))); + childParsers.put(JuickMessage.XMLNS, new JuickMessage()); + xmppService.submit(() -> { + connRouter = new ConnectionRouter(this, componentName, conf.getProperty("xmpp_password")); executorService.submit(new CleaningUp(this)); final ServerSocket listener = new ServerSocket(5269); LOGGER.info("s2s listener ready"); @@ -200,10 +200,11 @@ public class XMPPComponent implements ServletContextListener { LOGGER.log(Level.SEVERE, "s2s error", e); } } - } catch (Exception e) { - LOGGER.log(Level.SEVERE, "XMPPComponent error", e); - } - }); + }); + + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "XMPPComponent error", e); + } } -- cgit v1.2.3 From 8c8200933f01074b001b0f0f5bf7113ed6e29de6 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 6 Jul 2016 19:51:55 +0300 Subject: cleanup --- src/main/java/com/juick/CrosspostComponent.java | 20 -------------------- src/main/java/com/juick/PushComponent.java | 20 -------------------- src/main/java/com/juick/xmpp/s2s/XMPPComponent.java | 20 -------------------- 3 files changed, 60 deletions(-) (limited to 'src/main/java/com/juick/xmpp/s2s/XMPPComponent.java') diff --git a/src/main/java/com/juick/CrosspostComponent.java b/src/main/java/com/juick/CrosspostComponent.java index d7ee8724..eb4e2207 100644 --- a/src/main/java/com/juick/CrosspostComponent.java +++ b/src/main/java/com/juick/CrosspostComponent.java @@ -92,26 +92,6 @@ public class CrosspostComponent implements ServletContextListener, Stream.Strea @Override public void contextDestroyed(ServletContextEvent sce) { - // Now deregister JDBC drivers in this context's ClassLoader: - // Get the webapp's ClassLoader - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - // Loop through all drivers - Enumeration drivers = DriverManager.getDrivers(); - while (drivers.hasMoreElements()) { - Driver driver = drivers.nextElement(); - if (driver.getClass().getClassLoader() == cl) { - // This driver was registered by the webapp's ClassLoader, so deregister it: - try { - logger.info(String.format("Deregistering JDBC driver %s", driver.toString())); - DriverManager.deregisterDriver(driver); - } catch (SQLException ex) { - logger.log(Level.SEVERE, String.format("Error deregistering JDBC driver %s", driver), ex); - } - } else { - // driver was not registered by the webapp's ClassLoader and may be in use elsewhere - logger.log(Level.SEVERE, String.format("Not deregistering JDBC driver %s as it does not belong to this webapp's ClassLoader", driver)); - } - } executorService.shutdown(); logger.info("component destroyed"); } diff --git a/src/main/java/com/juick/PushComponent.java b/src/main/java/com/juick/PushComponent.java index e33d5fc3..d8401e51 100644 --- a/src/main/java/com/juick/PushComponent.java +++ b/src/main/java/com/juick/PushComponent.java @@ -107,26 +107,6 @@ public class PushComponent implements ServletContextListener, Stream.StreamListe @Override public void contextDestroyed(ServletContextEvent sce) { - // Now deregister JDBC drivers in this context's ClassLoader: - // Get the webapp's ClassLoader - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - // Loop through all drivers - Enumeration drivers = DriverManager.getDrivers(); - while (drivers.hasMoreElements()) { - Driver driver = drivers.nextElement(); - if (driver.getClass().getClassLoader() == cl) { - // This driver was registered by the webapp's ClassLoader, so deregister it: - try { - logger.info(String.format("Deregistering JDBC driver %s", driver.toString())); - DriverManager.deregisterDriver(driver); - } catch (SQLException ex) { - logger.log(Level.SEVERE, String.format("Error deregistering JDBC driver %s", driver), ex); - } - } else { - // driver was not registered by the webapp's ClassLoader and may be in use elsewhere - logger.log(Level.SEVERE, String.format("Not deregistering JDBC driver %s as it does not belong to this webapp's ClassLoader", driver)); - } - } executorService.shutdown(); logger.info("component destroyed"); } diff --git a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java index 8ebdb76a..ecfe1671 100644 --- a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java +++ b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java @@ -232,26 +232,6 @@ public class XMPPComponent implements ServletContextListener { } catch (IOException e) { LOGGER.log(Level.WARNING, "router warning", e); } - // Now deregister JDBC drivers in this context's ClassLoader: - // Get the webapp's ClassLoader - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - // Loop through all drivers - Enumeration drivers = DriverManager.getDrivers(); - while (drivers.hasMoreElements()) { - Driver driver = drivers.nextElement(); - if (driver.getClass().getClassLoader() == cl) { - // This driver was registered by the webapp's ClassLoader, so deregister it: - try { - LOGGER.info(String.format("Deregistering JDBC driver %s", driver.toString())); - DriverManager.deregisterDriver(driver); - } catch (SQLException ex) { - LOGGER.log(Level.SEVERE, String.format("Error deregistering JDBC driver %s", driver), ex); - } - } else { - // driver was not registered by the webapp's ClassLoader and may be in use elsewhere - LOGGER.log(Level.SEVERE, String.format("Not deregistering JDBC driver %s as it does not belong to this webapp's ClassLoader", driver)); - } - } executorService.shutdown(); LOGGER.info("component destroyed"); } -- cgit v1.2.3 From 6933a80515e454b45e03c1d3609093ad1abcef92 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 6 Jul 2016 20:07:45 +0300 Subject: merge router and component --- src/main/java/com/juick/CrosspostComponent.java | 4 - src/main/java/com/juick/PushComponent.java | 11 +- src/main/java/com/juick/xmpp/s2s/ConnectionIn.java | 4 +- .../java/com/juick/xmpp/s2s/ConnectionRouter.java | 241 -------------------- src/main/java/com/juick/xmpp/s2s/JuickBot.java | 13 +- .../java/com/juick/xmpp/s2s/XMPPComponent.java | 244 +++++++++++++++++++-- 6 files changed, 234 insertions(+), 283 deletions(-) delete mode 100644 src/main/java/com/juick/xmpp/s2s/ConnectionRouter.java (limited to 'src/main/java/com/juick/xmpp/s2s/XMPPComponent.java') diff --git a/src/main/java/com/juick/CrosspostComponent.java b/src/main/java/com/juick/CrosspostComponent.java index eb4e2207..8b07583f 100644 --- a/src/main/java/com/juick/CrosspostComponent.java +++ b/src/main/java/com/juick/CrosspostComponent.java @@ -38,10 +38,6 @@ import java.net.Socket; import java.net.URL; import java.net.URLEncoder; import java.security.Key; -import java.sql.Driver; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.Enumeration; import java.util.Properties; import java.util.UUID; import java.util.concurrent.ExecutorService; diff --git a/src/main/java/com/juick/PushComponent.java b/src/main/java/com/juick/PushComponent.java index d8401e51..3bb7cdc5 100644 --- a/src/main/java/com/juick/PushComponent.java +++ b/src/main/java/com/juick/PushComponent.java @@ -22,10 +22,8 @@ import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import com.juick.json.MessageSerializer; -import com.juick.server.MessagesQueries; import com.juick.server.PushQueries; import com.juick.server.SubscriptionsQueries; -import com.juick.server.UserQueries; import com.juick.xmpp.JID; import com.juick.xmpp.Message.MessageListener; import com.juick.xmpp.Stream; @@ -54,11 +52,10 @@ import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.io.IOException; import java.net.Socket; -import java.sql.Connection; -import java.sql.Driver; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; diff --git a/src/main/java/com/juick/xmpp/s2s/ConnectionIn.java b/src/main/java/com/juick/xmpp/s2s/ConnectionIn.java index bfc561b4..345caea9 100644 --- a/src/main/java/com/juick/xmpp/s2s/ConnectionIn.java +++ b/src/main/java/com/juick/xmpp/s2s/ConnectionIn.java @@ -117,7 +117,7 @@ public class ConnectionIn extends Connection implements Runnable { if (msg != null && (msg.type == null || !msg.type.equals(Message.Type.error))) { LOGGER.info("STREAM " + streamID + ": " + msg.toString()); if (!bot.incomingMessage(msg)) { - xmpp.connRouter.router.send(msg.toString()); + xmpp.router.send(msg.toString()); } } } else if (tag.equals("iq") && checkFromTo(parser)) { @@ -126,7 +126,7 @@ public class ConnectionIn extends Connection implements Runnable { String xml = XmlUtils.parseToString(parser, true); if (type == null || !type.equals(Iq.Type.error)) { LOGGER.info("STREAM " + streamID + ": " + xml); - xmpp.connRouter.router.send(xml); + xmpp.router.send(xml); } } else if (!isSecured() && tag.equals("starttls")) { LOGGER.info("STREAM " + streamID + " SECURING"); diff --git a/src/main/java/com/juick/xmpp/s2s/ConnectionRouter.java b/src/main/java/com/juick/xmpp/s2s/ConnectionRouter.java deleted file mode 100644 index 588cfe2c..00000000 --- a/src/main/java/com/juick/xmpp/s2s/ConnectionRouter.java +++ /dev/null @@ -1,241 +0,0 @@ -package com.juick.xmpp.s2s; - -import com.juick.User; -import com.juick.server.MessagesQueries; -import com.juick.server.SubscriptionsQueries; -import com.juick.server.UserQueries; -import com.juick.xmpp.*; -import com.juick.xmpp.extensions.JuickMessage; -import com.juick.xmpp.extensions.Nickname; -import com.juick.xmpp.extensions.XOOB; - -import java.io.IOException; -import java.net.Socket; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * @author ugnich - */ -public class ConnectionRouter implements Stream.StreamListener, - Message.MessageListener, Iq.IqListener, Presence.PresenceListener { - private static final Logger logger = Logger.getLogger(ConnectionRouter.class.getName()); - - private String componentName; - private String password; - Stream router; - Socket socket; - XMPPComponent xmpp; - - ConnectionRouter(XMPPComponent s2s, String componentName, String password) { - this.xmpp = s2s; - this.componentName = componentName; - this.password = password; - reconnect(); - } - public void reconnect() { - try { - socket = new Socket("localhost", 5347); - router = new StreamComponent(new JID("s2s"), socket.getInputStream(), socket.getOutputStream(), password); - router.addChildParser(new JuickMessage()); - router.addListener((Stream.StreamListener) this); - router.addListener((Message.MessageListener) this); - router.addListener((Iq.IqListener) this); - router.startParsing(); - logger.info("STREAM ROUTER START"); - } catch (IOException e) { - logger.log(Level.SEVERE, "router failed", e); - } - } - public void closeConnection() throws IOException { - router.logoff(); - socket.close(); - } - - public void sendJuickMessage(JuickMessage jmsg) { - List jids = new ArrayList<>(); - - if (jmsg.FriendsOnly) { - jids = SubscriptionsQueries.getJIDSubscribedToUser(xmpp.sql, jmsg.getUser().getUID(), jmsg.FriendsOnly); - } else { - List users = SubscriptionsQueries.getSubscribedUsers(xmpp.sql, jmsg.getUser().getUID(), jmsg.getMID()); - for (User user : users) { - for (String jid : UserQueries.getJIDsbyUID(xmpp.sql, user.getUID())) { - jids.add(jid); - } - } - } - - String txt = "@" + jmsg.getUser().getUName() + ":" + jmsg.getTagsString() + "\n"; - String attachment = jmsg.getAttachmentURL(); - if (attachment != null) { - txt += attachment + "\n"; - } - txt += jmsg.getText() + "\n\n"; - txt += "#" + jmsg.getMID() + " http://juick.com/" + jmsg.getMID(); - - Nickname nick = new Nickname(); - nick.Nickname = "@" + jmsg.getUser().getUName(); - - com.juick.xmpp.Message msg = new com.juick.xmpp.Message(); - msg.from = JuickBot.JuickJID; - msg.body = txt; - msg.type = Message.Type.chat; - msg.thread = "juick-" + jmsg.getMID(); - msg.addChild(jmsg); - msg.addChild(nick); - if (attachment != null) { - XOOB oob = new XOOB(); - oob.URL = attachment; - msg.addChild(oob); - } - - for (String jid : jids) { - msg.to = new JID(jid); - xmpp.sendOut(msg); - } - } - - public void sendJuickComment(JuickMessage jmsg) { - List users; - String replyQuote; - String replyTo; - - users = SubscriptionsQueries.getUsersSubscribedToComments(xmpp.sql, jmsg.getMID(), jmsg.getUser().getUID()); - com.juick.Message replyMessage = jmsg.ReplyTo > 0 ? MessagesQueries.getReply(xmpp.sql, jmsg.getMID(), jmsg.ReplyTo) - : MessagesQueries.getMessage(xmpp.sql, jmsg.getMID()); - replyTo = replyMessage.getUser().getUName(); - replyQuote = getReplyQuote(replyMessage); - - String txt = "Reply by @" + jmsg.getUser().getUName() + ":\n" + replyQuote + "\n@" + replyTo + " "; - String attachment = jmsg.getAttachmentURL(); - if (attachment != null) { - txt += attachment + "\n"; - } - txt += jmsg.getText() + "\n\n" + "#" + jmsg.getMID() + "/" + jmsg.getRID() + " http://juick.com/" + jmsg.getMID() + "#" + jmsg.getRID(); - - com.juick.xmpp.Message msg = new com.juick.xmpp.Message(); - msg.from = JuickBot.JuickJID; - msg.body = txt; - msg.type = Message.Type.chat; - msg.addChild(jmsg); - for (User user : users) { - for (String jid : UserQueries.getJIDsbyUID(xmpp.sql, user.getUID())) { - msg.to = new JID(jid); - xmpp.sendOut(msg); - } - } - } - - private String getReplyQuote(com.juick.Message q) { - String quote = q.getText(); - if (quote.length() > 50) { - quote = ">" + quote.substring(0, 47).replace('\n', ' ') + "...\n"; - } else if (quote.length() > 0) { - quote = ">" + quote.replace('\n', ' ') + "\n"; - } - return quote; - } - - public void sendJuickRecommendation(JuickMessage recomm) { - List users; - JuickMessage jmsg; - jmsg = new JuickMessage(MessagesQueries.getMessage(xmpp.sql, recomm.getMID())); - users = SubscriptionsQueries.getUsersSubscribedToUserRecommendations(xmpp.sql, - recomm.getUser().getUID(), recomm.getMID(), jmsg.getUser().getUID()); - - String txt = "Recommended by @" + recomm.getUser().getUName() + ":\n"; - txt += "@" + jmsg.getUser().getUName() + ":" + jmsg.getTagsString() + "\n"; - String attachment = jmsg.getAttachmentURL(); - if (attachment != null) { - txt += attachment + "\n"; - } - txt += jmsg.getText() + "\n\n"; - txt += "#" + jmsg.getMID(); - if (jmsg.Replies > 0) { - if (jmsg.Replies % 10 == 1 && jmsg.Replies % 100 != 11) { - txt += " (" + jmsg.Replies + " reply)"; - } else { - txt += " (" + jmsg.Replies + " replies)"; - } - } - txt += " http://juick.com/" + jmsg.getMID(); - - Nickname nick = new Nickname(); - nick.Nickname = "@" + jmsg.getUser().getUName(); - - com.juick.xmpp.Message msg = new com.juick.xmpp.Message(); - msg.from = JuickBot.JuickJID; - msg.body = txt; - msg.type = Message.Type.chat; - msg.thread = "juick-" + jmsg.getMID(); - msg.addChild(jmsg); - msg.addChild(nick); - if (attachment != null) { - XOOB oob = new XOOB(); - oob.URL = attachment; - msg.addChild(oob); - } - - for (User user : users) { - for (String jid : UserQueries.getJIDsbyUID(xmpp.sql, user.getUID())) { - msg.to = new JID(jid); - xmpp.sendOut(msg); - } - } - } - - @Override - public boolean onIq(Iq iq) { - JID jid = iq.to; - if (!jid.Host.equals(componentName)) { - logger.info("STREAM ROUTER (IQ): " + iq.toString()); - xmpp.sendOut(iq); - } - return false; - } - - @Override - public void onMessage(Message xmsg) { - logger.info("STREAM ROUTER (PROCESS): " + xmsg.toString()); - JuickMessage jmsg = (JuickMessage) xmsg.getChild(JuickMessage.XMLNS); - JID jid = xmsg.to; - if (jid.Host.equals(componentName)) { - if (jmsg != null) { - if (jid.Username != null && jid.Username.equals("recomm")) { - sendJuickRecommendation(jmsg); - } else { - if (jmsg.getRID() > 0) { - sendJuickComment(jmsg); - } else if (jmsg.getMID() > 0) { - sendJuickMessage(jmsg); - } - } - } - } else { - xmpp.sendOut(xmsg); - } - } - - @Override - public void onPresence(Presence presence) { - JID jid = presence.to; - if (!jid.Host.equals(componentName)) { - logger.info("STREAM ROUTER (PRESENCE): " + presence.toString()); - xmpp.sendOut(presence); - } - } - - @Override - public void onStreamReady() { - logger.info("STREAM ROUTER (READY)"); - } - - @Override - public void onStreamFail(Exception ex) { - logger.log(Level.SEVERE, "STREAM ROUTER (FAIL)", ex); - reconnect(); - } -} diff --git a/src/main/java/com/juick/xmpp/s2s/JuickBot.java b/src/main/java/com/juick/xmpp/s2s/JuickBot.java index 18e7580d..f0b71689 100644 --- a/src/main/java/com/juick/xmpp/s2s/JuickBot.java +++ b/src/main/java/com/juick/xmpp/s2s/JuickBot.java @@ -20,11 +20,12 @@ import java.util.regex.Pattern; */ public class JuickBot { XMPPComponent xmpp; - public JuickBot(XMPPComponent xmpp) { + public JuickBot(XMPPComponent xmpp, JID JuickJID) { this.xmpp = xmpp; + this.JuickJID = JuickJID; } - public static final JID JuickJID = new JID("juick", "juick.com", "Juick"); + public final JID JuickJID; private static final String HELPTEXT = "@username text - Send private message\n" + "*tagname Blah-blah-blah - Post a message with tag 'tagname'\n" @@ -187,10 +188,10 @@ public class JuickBot { jmsg.setUser(user_from); jmsg.setText(msg.body); m.childs.add(jmsg); - xmpp.connRouter.router.send(m.toString()); + xmpp.router.send(m.toString()); m.to.Host = "ws.juick.com"; - xmpp.connRouter.router.send(m.toString()); + xmpp.router.send(m.toString()); List jids; boolean inroster = false; @@ -315,10 +316,10 @@ public class JuickBot { jmsg.setUser(user_from); jmsg.setText(body); msg.childs.add(jmsg); - xmpp.connRouter.router.send(msg.toString()); + xmpp.router.send(msg.toString()); msg.to.Host = "ws.juick.com"; - xmpp.connRouter.router.send(msg.toString()); + xmpp.router.send(msg.toString()); for (String jid : jids_to) { Message mm = new Message(); diff --git a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java index ecfe1671..9b8bb07e 100644 --- a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java +++ b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java @@ -1,8 +1,13 @@ package com.juick.xmpp.s2s; -import com.juick.xmpp.Stanza; -import com.juick.xmpp.StanzaChild; +import com.juick.User; +import com.juick.server.MessagesQueries; +import com.juick.server.SubscriptionsQueries; +import com.juick.server.UserQueries; +import com.juick.xmpp.*; import com.juick.xmpp.extensions.JuickMessage; +import com.juick.xmpp.extensions.Nickname; +import com.juick.xmpp.extensions.XOOB; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.xmlpull.v1.XmlPullParserException; @@ -17,9 +22,6 @@ import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; -import java.sql.Driver; -import java.sql.DriverManager; -import java.sql.SQLException; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -30,19 +32,20 @@ import java.util.logging.Logger; * * @author ugnich */ -public class XMPPComponent implements ServletContextListener { +public class XMPPComponent implements ServletContextListener, Stream.StreamListener, + Message.MessageListener, Iq.IqListener, Presence.PresenceListener { - private static final Logger LOGGER = Logger.getLogger(XMPPComponent.class.getName()); + private static final Logger logger = Logger.getLogger(XMPPComponent.class.getName()); public final ExecutorService executorService = Executors.newCachedThreadPool(); - ExecutorService xmppService = Executors.newSingleThreadExecutor(); + StreamComponent router; + JuickBot bot; - public String HOSTNAME = null; + public String HOSTNAME, componentName; public String STATSFILE = null; public String keystore; public String keystorePassword; public List brokenSSLhosts; - public ConnectionRouter connRouter; final List inConnections = Collections.synchronizedList(new ArrayList<>()); final List outConnections = Collections.synchronizedList(new ArrayList<>()); final List outCache = Collections.synchronizedList(new ArrayList<>()); @@ -135,7 +138,7 @@ public class XMPPComponent implements ServletContextListener { try { connOut.sendStanza(xml); } catch (IOException e) { - LOGGER.warning("STREAM TO " + connOut.to + " " + connOut.streamID + " ERROR: " + e.toString()); + logger.warning("STREAM TO " + connOut.to + " " + connOut.streamID + " ERROR: " + e.toString()); } return; } @@ -161,7 +164,7 @@ public class XMPPComponent implements ServletContextListener { connectionOut = new ConnectionOut(this, hostname); executorService.submit(connectionOut); } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | XmlPullParserException | KeyStoreException | KeyManagementException | IOException e) { - LOGGER.log(Level.SEVERE, "s2s out error", e); + logger.log(Level.SEVERE, "s2s out error", e); } } } @@ -169,12 +172,13 @@ public class XMPPComponent implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { - LOGGER.info("component initialized"); + logger.info("component initialized"); Properties conf = new Properties(); try { conf.load(sce.getServletContext().getResourceAsStream("/WEB-INF/juick.conf")); HOSTNAME = conf.getProperty("hostname"); - String componentName = conf.getProperty("componentname"); + componentName = conf.getProperty("componentname"); + JID Jid = new JID(conf.getProperty("xmppbot_jid")); STATSFILE = conf.getProperty("statsfile"); keystore = conf.getProperty("keystore"); keystorePassword = conf.getProperty("keystore_password"); @@ -183,27 +187,34 @@ public class XMPPComponent implements ServletContextListener { dataSource.setDriverClassName(conf.getProperty("datasource_driver", "com.mysql.jdbc.Driver")); dataSource.setUrl(conf.getProperty("datasource_url")); sql = new JdbcTemplate(dataSource); + bot = new JuickBot(this, Jid); childParsers.put(JuickMessage.XMLNS, new JuickMessage()); - xmppService.submit(() -> { - connRouter = new ConnectionRouter(this, componentName, conf.getProperty("xmpp_password")); + Socket routerSocket = new Socket("localhost", 5347); + router = new StreamComponent(new JID("s2s"), routerSocket.getInputStream(), routerSocket.getOutputStream(), conf.getProperty("xmpp_password")); + router.addChildParser(new JuickMessage()); + router.addListener((Stream.StreamListener) this); + router.addListener((Message.MessageListener) this); + router.addListener((Iq.IqListener) this); + executorService.submit(() -> { + router.startParsing(); executorService.submit(new CleaningUp(this)); final ServerSocket listener = new ServerSocket(5269); - LOGGER.info("s2s listener ready"); + logger.info("s2s listener ready"); while (true) { try { Socket socket = listener.accept(); - ConnectionIn client = new ConnectionIn(this, new JuickBot(this), socket); + ConnectionIn client = new ConnectionIn(this, bot, socket); addConnectionIn(client); executorService.submit(client); } catch (Exception e) { - LOGGER.log(Level.SEVERE, "s2s error", e); + logger.log(Level.SEVERE, "s2s error", e); } } }); } catch (Exception e) { - LOGGER.log(Level.SEVERE, "XMPPComponent error", e); + logger.log(Level.SEVERE, "XMPPComponent error", e); } } @@ -228,11 +239,198 @@ public class XMPPComponent implements ServletContextListener { } try { - connRouter.closeConnection(); + closeRouterConnection(); } catch (IOException e) { - LOGGER.log(Level.WARNING, "router warning", e); + logger.log(Level.WARNING, "router warning", e); } executorService.shutdown(); - LOGGER.info("component destroyed"); + logger.info("component destroyed"); + } + public void closeRouterConnection() throws IOException { + router.logoff(); + } + + public void sendJuickMessage(JuickMessage jmsg) { + List jids = new ArrayList<>(); + + if (jmsg.FriendsOnly) { + jids = SubscriptionsQueries.getJIDSubscribedToUser(sql, jmsg.getUser().getUID(), jmsg.FriendsOnly); + } else { + List users = SubscriptionsQueries.getSubscribedUsers(sql, jmsg.getUser().getUID(), jmsg.getMID()); + for (User user : users) { + for (String jid : UserQueries.getJIDsbyUID(sql, user.getUID())) { + jids.add(jid); + } + } + } + + String txt = "@" + jmsg.getUser().getUName() + ":" + jmsg.getTagsString() + "\n"; + String attachment = jmsg.getAttachmentURL(); + if (attachment != null) { + txt += attachment + "\n"; + } + txt += jmsg.getText() + "\n\n"; + txt += "#" + jmsg.getMID() + " http://juick.com/" + jmsg.getMID(); + + Nickname nick = new Nickname(); + nick.Nickname = "@" + jmsg.getUser().getUName(); + + com.juick.xmpp.Message msg = new com.juick.xmpp.Message(); + msg.from = bot.JuickJID; + msg.body = txt; + msg.type = Message.Type.chat; + msg.thread = "juick-" + jmsg.getMID(); + msg.addChild(jmsg); + msg.addChild(nick); + if (attachment != null) { + XOOB oob = new XOOB(); + oob.URL = attachment; + msg.addChild(oob); + } + + for (String jid : jids) { + msg.to = new JID(jid); + sendOut(msg); + } + } + + public void sendJuickComment(JuickMessage jmsg) { + List users; + String replyQuote; + String replyTo; + + users = SubscriptionsQueries.getUsersSubscribedToComments(sql, jmsg.getMID(), jmsg.getUser().getUID()); + com.juick.Message replyMessage = jmsg.ReplyTo > 0 ? MessagesQueries.getReply(sql, jmsg.getMID(), jmsg.ReplyTo) + : MessagesQueries.getMessage(sql, jmsg.getMID()); + replyTo = replyMessage.getUser().getUName(); + replyQuote = getReplyQuote(replyMessage); + + String txt = "Reply by @" + jmsg.getUser().getUName() + ":\n" + replyQuote + "\n@" + replyTo + " "; + String attachment = jmsg.getAttachmentURL(); + if (attachment != null) { + txt += attachment + "\n"; + } + txt += jmsg.getText() + "\n\n" + "#" + jmsg.getMID() + "/" + jmsg.getRID() + " http://juick.com/" + jmsg.getMID() + "#" + jmsg.getRID(); + + com.juick.xmpp.Message msg = new com.juick.xmpp.Message(); + msg.from = bot.JuickJID; + msg.body = txt; + msg.type = Message.Type.chat; + msg.addChild(jmsg); + for (User user : users) { + for (String jid : UserQueries.getJIDsbyUID(sql, user.getUID())) { + msg.to = new JID(jid); + sendOut(msg); + } + } + } + + private String getReplyQuote(com.juick.Message q) { + String quote = q.getText(); + if (quote.length() > 50) { + quote = ">" + quote.substring(0, 47).replace('\n', ' ') + "...\n"; + } else if (quote.length() > 0) { + quote = ">" + quote.replace('\n', ' ') + "\n"; + } + return quote; + } + + public void sendJuickRecommendation(JuickMessage recomm) { + List users; + JuickMessage jmsg; + jmsg = new JuickMessage(MessagesQueries.getMessage(sql, recomm.getMID())); + users = SubscriptionsQueries.getUsersSubscribedToUserRecommendations(sql, + recomm.getUser().getUID(), recomm.getMID(), jmsg.getUser().getUID()); + + String txt = "Recommended by @" + recomm.getUser().getUName() + ":\n"; + txt += "@" + jmsg.getUser().getUName() + ":" + jmsg.getTagsString() + "\n"; + String attachment = jmsg.getAttachmentURL(); + if (attachment != null) { + txt += attachment + "\n"; + } + txt += jmsg.getText() + "\n\n"; + txt += "#" + jmsg.getMID(); + if (jmsg.Replies > 0) { + if (jmsg.Replies % 10 == 1 && jmsg.Replies % 100 != 11) { + txt += " (" + jmsg.Replies + " reply)"; + } else { + txt += " (" + jmsg.Replies + " replies)"; + } + } + txt += " http://juick.com/" + jmsg.getMID(); + + Nickname nick = new Nickname(); + nick.Nickname = "@" + jmsg.getUser().getUName(); + + com.juick.xmpp.Message msg = new com.juick.xmpp.Message(); + msg.from = bot.JuickJID; + msg.body = txt; + msg.type = Message.Type.chat; + msg.thread = "juick-" + jmsg.getMID(); + msg.addChild(jmsg); + msg.addChild(nick); + if (attachment != null) { + XOOB oob = new XOOB(); + oob.URL = attachment; + msg.addChild(oob); + } + + for (User user : users) { + for (String jid : UserQueries.getJIDsbyUID(sql, user.getUID())) { + msg.to = new JID(jid); + sendOut(msg); + } + } + } + + @Override + public boolean onIq(Iq iq) { + JID jid = iq.to; + if (!jid.Host.equals(componentName)) { + logger.info("STREAM ROUTER (IQ): " + iq.toString()); + sendOut(iq); + } + return false; + } + + @Override + public void onMessage(Message xmsg) { + logger.info("STREAM ROUTER (PROCESS): " + xmsg.toString()); + JuickMessage jmsg = (JuickMessage) xmsg.getChild(JuickMessage.XMLNS); + JID jid = xmsg.to; + if (jid.Host.equals(componentName)) { + if (jmsg != null) { + if (jid.Username != null && jid.Username.equals("recomm")) { + sendJuickRecommendation(jmsg); + } else { + if (jmsg.getRID() > 0) { + sendJuickComment(jmsg); + } else if (jmsg.getMID() > 0) { + sendJuickMessage(jmsg); + } + } + } + } else { + sendOut(xmsg); + } + } + + @Override + public void onPresence(Presence presence) { + JID jid = presence.to; + if (!jid.Host.equals(componentName)) { + logger.info("STREAM ROUTER (PRESENCE): " + presence.toString()); + sendOut(presence); + } + } + + @Override + public void onStreamReady() { + logger.info("STREAM ROUTER (READY)"); + } + + @Override + public void onStreamFail(Exception ex) { + logger.log(Level.SEVERE, "STREAM ROUTER (FAIL)", ex); } } -- cgit v1.2.3 From 5005833a6f4437c7ad0d3d36bbd8b2da99a904ee Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 6 Jul 2016 20:13:23 +0300 Subject: fix initialization --- src/main/java/com/juick/xmpp/s2s/XMPPComponent.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/main/java/com/juick/xmpp/s2s/XMPPComponent.java') diff --git a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java index 9b8bb07e..21efaeab 100644 --- a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java +++ b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java @@ -195,7 +195,8 @@ public class XMPPComponent implements ServletContextListener, Stream.StreamListe router.addChildParser(new JuickMessage()); router.addListener((Stream.StreamListener) this); router.addListener((Message.MessageListener) this); - router.addListener((Iq.IqListener) this); + router.addListener((Iq.IqListener) this); + executorService.submit(() -> router.startParsing()); executorService.submit(() -> { router.startParsing(); executorService.submit(new CleaningUp(this)); -- cgit v1.2.3 From a33e6c3926b41a29a5828677cbad265f7c503d57 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 6 Jul 2016 20:18:49 +0300 Subject: refactor --- .../java/com/juick/xmpp/s2s/XMPPComponent.java | 28 +++++++++++++--------- 1 file changed, 17 insertions(+), 11 deletions(-) (limited to 'src/main/java/com/juick/xmpp/s2s/XMPPComponent.java') diff --git a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java index 21efaeab..d0b231e2 100644 --- a/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java +++ b/src/main/java/com/juick/xmpp/s2s/XMPPComponent.java @@ -159,9 +159,8 @@ public class XMPPComponent implements ServletContextListener, Stream.StreamListe } if (!haveAnyConn) { - ConnectionOut connectionOut = null; try { - connectionOut = new ConnectionOut(this, hostname); + ConnectionOut connectionOut = new ConnectionOut(this, hostname); executorService.submit(connectionOut); } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | XmlPullParserException | KeyStoreException | KeyManagementException | IOException e) { logger.log(Level.SEVERE, "s2s out error", e); @@ -190,16 +189,22 @@ public class XMPPComponent implements ServletContextListener, Stream.StreamListe bot = new JuickBot(this, Jid); childParsers.put(JuickMessage.XMLNS, new JuickMessage()); - Socket routerSocket = new Socket("localhost", 5347); - router = new StreamComponent(new JID("s2s"), routerSocket.getInputStream(), routerSocket.getOutputStream(), conf.getProperty("xmpp_password")); - router.addChildParser(new JuickMessage()); - router.addListener((Stream.StreamListener) this); - router.addListener((Message.MessageListener) this); - router.addListener((Iq.IqListener) this); - executorService.submit(() -> router.startParsing()); + + executorService.submit(() -> { + Socket routerSocket = null; + try { + routerSocket = new Socket("localhost", 5347); + router = new StreamComponent(new JID("s2s"), routerSocket.getInputStream(), routerSocket.getOutputStream(), conf.getProperty("xmpp_password")); + router.addChildParser(new JuickMessage()); + router.addListener((Stream.StreamListener) this); + router.addListener((Message.MessageListener) this); + router.addListener((Iq.IqListener) this); + router.startParsing(); + } catch (IOException e) { + logger.log(Level.SEVERE, "router error", e); + } + }); executorService.submit(() -> { - router.startParsing(); - executorService.submit(new CleaningUp(this)); final ServerSocket listener = new ServerSocket(5269); logger.info("s2s listener ready"); while (true) { @@ -213,6 +218,7 @@ public class XMPPComponent implements ServletContextListener, Stream.StreamListe } } }); + executorService.submit(new CleaningUp(this)); } catch (Exception e) { logger.log(Level.SEVERE, "XMPPComponent error", e); -- cgit v1.2.3
hostlivesize