From a4897522174fb48864a4ef7d6276167f9da61f3b Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sat, 31 Oct 2015 01:36:15 +0300 Subject: moved to Gradle --- deps/com.juick | 1 + deps/com.juick.json | 1 + deps/com.juick.server | 1 + deps/com.juick.xmpp | 1 + 4 files changed, 4 insertions(+) create mode 160000 deps/com.juick create mode 160000 deps/com.juick.json create mode 160000 deps/com.juick.server create mode 160000 deps/com.juick.xmpp (limited to 'deps') diff --git a/deps/com.juick b/deps/com.juick new file mode 160000 index 00000000..a5766d12 --- /dev/null +++ b/deps/com.juick @@ -0,0 +1 @@ +Subproject commit a5766d12d6dbd80a44d6d1deee4d454016b37079 diff --git a/deps/com.juick.json b/deps/com.juick.json new file mode 160000 index 00000000..5f4602b3 --- /dev/null +++ b/deps/com.juick.json @@ -0,0 +1 @@ +Subproject commit 5f4602b34ccc3f899edd45e5e541cbb7307c9585 diff --git a/deps/com.juick.server b/deps/com.juick.server new file mode 160000 index 00000000..5f981ff9 --- /dev/null +++ b/deps/com.juick.server @@ -0,0 +1 @@ +Subproject commit 5f981ff945d7bad508d0fb56d037bfe3dccd0cf3 diff --git a/deps/com.juick.xmpp b/deps/com.juick.xmpp new file mode 160000 index 00000000..87ca4b93 --- /dev/null +++ b/deps/com.juick.xmpp @@ -0,0 +1 @@ +Subproject commit 87ca4b93d426c19b6fdaeec038202485515606d5 -- cgit v1.2.3 From 163ad495c3641f4eacd7394601cd02b8b6208c73 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 4 Nov 2015 14:20:04 +0300 Subject: sync deps --- deps/com.juick | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick b/deps/com.juick index a5766d12..c3d949e1 160000 --- a/deps/com.juick +++ b/deps/com.juick @@ -1 +1 @@ -Subproject commit a5766d12d6dbd80a44d6d1deee4d454016b37079 +Subproject commit c3d949e11a4380a2353fca0abf12292285fde02c -- cgit v1.2.3 From bbad6cd8c52fe0757c9c409ea6d6bc4ea89e7837 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 4 Nov 2015 15:26:24 +0300 Subject: sync deps --- deps/com.juick | 2 +- deps/com.juick.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'deps') diff --git a/deps/com.juick b/deps/com.juick index c3d949e1..5f08b8b1 160000 --- a/deps/com.juick +++ b/deps/com.juick @@ -1 +1 @@ -Subproject commit c3d949e11a4380a2353fca0abf12292285fde02c +Subproject commit 5f08b8b1cfaacf1e78c56e7752277533eb84b02e diff --git a/deps/com.juick.json b/deps/com.juick.json index 5f4602b3..655b821e 160000 --- a/deps/com.juick.json +++ b/deps/com.juick.json @@ -1 +1 @@ -Subproject commit 5f4602b34ccc3f899edd45e5e541cbb7307c9585 +Subproject commit 655b821e274ca4be078389475a8bb33139c55a4f -- cgit v1.2.3 From 03f9e91ff8d61e63c6b4a49a5a15af52e87fd63a Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 27 Nov 2015 16:52:28 +0300 Subject: update deps --- build.gradle | 2 +- deps/com.juick.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'deps') diff --git a/build.gradle b/build.gradle index 4a98c4d2..14e74f02 100644 --- a/build.gradle +++ b/build.gradle @@ -49,7 +49,6 @@ project(':deps:com.juick.json') { } dependencies { - compile 'org.json:json:20140107' compile core compile server compile xmpp @@ -60,6 +59,7 @@ dependencies { "org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}", "org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}" testCompile 'junit:junit:4.12' + runtime 'mysql:mysql-connector-java:5.1.37' } compileJava.options.encoding = 'UTF-8' diff --git a/deps/com.juick.json b/deps/com.juick.json index 655b821e..d4cbeb80 160000 --- a/deps/com.juick.json +++ b/deps/com.juick.json @@ -1 +1 @@ -Subproject commit 655b821e274ca4be078389475a8bb33139c55a4f +Subproject commit d4cbeb802cba9fb3bd0885c31807bdff7b3f6b29 -- cgit v1.2.3 From 5d3433e0e7eae2f71b6e3e935010b82e01236e8c Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sun, 10 Jan 2016 18:25:34 +0300 Subject: update deps --- deps/com.juick.json | 2 +- deps/com.juick.server | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'deps') diff --git a/deps/com.juick.json b/deps/com.juick.json index d4cbeb80..c152ab72 160000 --- a/deps/com.juick.json +++ b/deps/com.juick.json @@ -1 +1 @@ -Subproject commit d4cbeb802cba9fb3bd0885c31807bdff7b3f6b29 +Subproject commit c152ab72d3ba8f662706eb4b1342d839762a243a diff --git a/deps/com.juick.server b/deps/com.juick.server index 5f981ff9..03316e2a 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 5f981ff945d7bad508d0fb56d037bfe3dccd0cf3 +Subproject commit 03316e2af6989e026318e6860f27d26e6e805d4d -- cgit v1.2.3 From 9eba4bda6dce22fb37d9156a5291f2cee3243361 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sun, 10 Jan 2016 18:43:23 +0300 Subject: update deps --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index 03316e2a..c37ed56f 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 03316e2af6989e026318e6860f27d26e6e805d4d +Subproject commit c37ed56f884661666b964e47efd23a36be9b24d4 -- cgit v1.2.3 From 690b3ea447a7a2434ecf1d210e5f5ef89ce27f04 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 15 Jan 2016 12:51:21 +0300 Subject: spring-jdbc WIP --- build.gradle | 2 ++ deps/com.juick.server | 2 +- src/main/java/com/juick/api/Main.java | 47 ++++++++++++++----------- src/main/java/com/juick/api/Messages.java | 54 ++++++++++++++++++++++++----- src/main/java/com/juick/api/Others.java | 5 +-- src/main/java/com/juick/api/PM.java | 12 +++---- src/main/java/com/juick/api/Users.java | 6 ++-- src/main/java/com/juick/api/Utils.java | 7 ++-- src/test/java/com/juick/tests/ApiTests.java | 40 +++++++++++++++++++++ 9 files changed, 131 insertions(+), 44 deletions(-) create mode 100644 src/test/java/com/juick/tests/ApiTests.java (limited to 'deps') diff --git a/build.gradle b/build.gradle index 14e74f02..c2ca747e 100644 --- a/build.gradle +++ b/build.gradle @@ -53,6 +53,8 @@ dependencies { compile server compile xmpp compile json + compile "org.springframework:spring-jdbc:4.2.4.RELEASE" + compile "org.apache.commons:commons-dbcp2:2.1.1" providedCompile 'javax.servlet:javax.servlet-api:3.1.0' def tomcatVersion = '7.0.+' tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}", diff --git a/deps/com.juick.server b/deps/com.juick.server index c37ed56f..9bd8a41c 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit c37ed56f884661666b964e47efd23a36be9b24d4 +Subproject commit 9bd8a41c0db5a1027a184facfca8d0152945c078 diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index 09dd4cbd..71f7f2d7 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -20,6 +20,9 @@ package com.juick.api; import com.juick.xmpp.JID; import com.juick.xmpp.Stream; import com.juick.xmpp.StreamComponent; +import org.apache.commons.dbcp2.BasicDataSource; +import org.springframework.jdbc.core.JdbcTemplate; + import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; @@ -28,7 +31,6 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; -import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -46,6 +48,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { Connection sql; Connection sqlSearch; + JdbcTemplate jdbc; Stream xmpp; Messages messages; Users users; @@ -58,19 +61,22 @@ public class Main extends HttpServlet implements Stream.StreamListener { try { Properties conf = new Properties(); conf.load(new FileInputStream("/etc/juick/api.conf")); - - Class.forName("com.mysql.jdbc.Driver"); + final String driverClassName = "com.mysql.jdbc.Driver"; + Class.forName(driverClassName); sql = DriverManager.getConnection("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", "")); sqlSearch = DriverManager.getConnection("jdbc:mysql://127.0.0.1:9306/juick?autoReconnect=true&characterEncoding=utf8&maxAllowedPacket=512000&relaxAutoCommit=true&user=root&password="); - - messages = new Messages(sql); - users = new Users(sql); - pm = new PM(sql); - others = new Others(sql); + BasicDataSource dataSource = new BasicDataSource(); + dataSource.setUrl(sql.getMetaData().getURL()); + dataSource.setDriverClassName(driverClassName); + jdbc = new JdbcTemplate(dataSource); + messages = new Messages(jdbc); + users = new Users(jdbc); + pm = new PM(jdbc); + others = new Others(jdbc); setupXmppComponent(conf.getProperty("xmpp_password")); - } catch (Exception e) { + } catch (IOException | ClassNotFoundException | SQLException e) { log(null, e); } } @@ -135,7 +141,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { int vuid = Utils.getHttpAuthUID(sql, request); if (vuid == 0) { - vuid = Utils.getVisitorQueryStringUID(sql, request); + vuid = Utils.getVisitorQueryStringUID(jdbc, request); } String uri = request.getRequestURI(); @@ -193,7 +199,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { int vuid = Utils.getHttpAuthUID(sql, request); if (vuid == 0) { - vuid = Utils.getVisitorQueryStringUID(sql, request); + vuid = Utils.getVisitorQueryStringUID(jdbc, request); } if (vuid == 0) { response.sendError(401); @@ -201,11 +207,15 @@ public class Main extends HttpServlet implements Stream.StreamListener { } String uri = request.getRequestURI(); - if (uri.equals("/post")) { - } else if (uri.equals("/pm")) { - pm.doPostPM(request, response, xmpp, vuid); - } else { - response.sendError(405); + switch (uri) { + case "/post": + break; + case "/pm": + pm.doPostPM(request, response, xmpp, vuid); + break; + default: + response.sendError(405); + break; } } @@ -218,8 +228,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { callback = null; } - PrintWriter out = response.getWriter(); - try { + try (PrintWriter out = response.getWriter()) { if (callback != null) { out.print(callback + "("); out.print(json); @@ -227,8 +236,6 @@ public class Main extends HttpServlet implements Stream.StreamListener { } else { out.print(json); } - } finally { - out.close(); } } } diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java index cde3987f..e3dcabfd 100644 --- a/src/main/java/com/juick/api/Messages.java +++ b/src/main/java/com/juick/api/Messages.java @@ -1,17 +1,21 @@ package com.juick.api; +import com.juick.Tag; +import com.juick.User; import com.juick.json.MessageSerializer; import com.juick.server.MessagesQueries; +import com.juick.server.TagQueries; +import com.juick.server.UserQueries; import com.juick.xmpp.JID; import com.juick.xmpp.Message; import com.juick.xmpp.Stream; import com.juick.xmpp.extensions.JuickMessage; +import org.springframework.jdbc.core.JdbcTemplate; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.sql.Connection; import java.util.List; /** @@ -20,11 +24,32 @@ import java.util.List; */ public class Messages { - Connection sql; + JdbcTemplate sql; MessageSerializer messageSerializer = new MessageSerializer(); - public Messages(Connection sql) { + enum MediaType { + ALL("all"), + PHOTO("photo"), + VIDEO("video"), + NONE(""); + + private final String value; + + MediaType(final String value) { + this.value = value; + } + public String getValue() { + return value; + } + + @Override + public String toString() { + return this.getValue(); + } + } + + public Messages(JdbcTemplate sql) { this.sql = sql; } @@ -45,8 +70,19 @@ public class Messages { } } - public void doGetRecommended(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + public void doGet(HttpServletRequest request, HttpServletResponse response, int vuid) + throws ServletException, IOException { + User user = UserQueries.getUserByName(sql, request.getParameter("uname")); int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0); + int page = Utils.parseInt(request.getParameter("page"), 0); + MediaType media = MediaType.valueOf(request.getParameter("media")); + boolean popular = Boolean.valueOf(request.getParameter("popular")); + Tag tag = TagQueries.getTag(sql, request.getParameter("tag"), false); + + } + + public void doGetRecommended(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + /*int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0); List mids = MessagesQueries.getUserRecommendations(sql, vuid, before_mid); if (mids != null && !mids.isEmpty()) { @@ -59,21 +95,21 @@ public class Messages { } } else { response.sendError(404); - } + }*/ } public void doSetPrivacy(HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid) throws ServletException, IOException { - int mid = Utils.parseInt(request.getParameter("mid"), 0); + /*int mid = Utils.parseInt(request.getParameter("mid"), 0); com.juick.User user = MessagesQueries.getMessageAuthor(sql, mid); if (user != null && user.UID == vuid && MessagesQueries.setMessagePrivacy(sql, mid)) { Main.replyJSON(request, response, "{\"status\":\"ok\"}"); } else { response.sendError(400); - } + }*/ } public void doSetPopular(HttpServletRequest request, HttpServletResponse response, Stream xmpp) throws ServletException, IOException { - int mid = Utils.parseInt(request.getParameter("mid"), 0); + /*int mid = Utils.parseInt(request.getParameter("mid"), 0); int popular = Utils.parseInt(request.getParameter("popular"), 0); if (mid > 0) { @@ -105,6 +141,6 @@ public class Messages { } Main.replyJSON(request, response, "{\"status\":\"ok\"}"); - } + }*/ } } diff --git a/src/main/java/com/juick/api/Others.java b/src/main/java/com/juick/api/Others.java index 323ed41a..3c8d4a96 100644 --- a/src/main/java/com/juick/api/Others.java +++ b/src/main/java/com/juick/api/Others.java @@ -3,6 +3,7 @@ package com.juick.api; import com.juick.User; import com.juick.json.UserSerializer; import com.juick.server.PMQueries; +import org.springframework.jdbc.core.JdbcTemplate; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -17,11 +18,11 @@ import java.util.List; */ public class Others { - Connection sql; + JdbcTemplate sql; UserSerializer userSerializer = new UserSerializer(); - public Others(Connection sql) { + public Others(JdbcTemplate sql) { this.sql = sql; } diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java index f22a4add..01a5669a 100644 --- a/src/main/java/com/juick/api/PM.java +++ b/src/main/java/com/juick/api/PM.java @@ -7,9 +7,9 @@ import com.juick.xmpp.JID; import com.juick.xmpp.Message; import com.juick.xmpp.Stream; import com.juick.xmpp.extensions.JuickMessage; +import org.springframework.jdbc.core.JdbcTemplate; + import java.io.IOException; -import java.sql.Connection; -import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -21,11 +21,11 @@ import javax.servlet.http.HttpServletResponse; */ public class PM { - Connection sql; - - MessageSerializer messageSerializer = new MessageSerializer(); + JdbcTemplate sql; + + MessageSerializer messageSerializer = new MessageSerializer(); - public PM(Connection sql) { + public PM(JdbcTemplate sql) { this.sql = sql; } diff --git a/src/main/java/com/juick/api/Users.java b/src/main/java/com/juick/api/Users.java index 5bae4028..d3818a5a 100644 --- a/src/main/java/com/juick/api/Users.java +++ b/src/main/java/com/juick/api/Users.java @@ -2,12 +2,12 @@ package com.juick.api; import com.juick.json.UserSerializer; import com.juick.server.UserQueries; +import org.springframework.jdbc.core.JdbcTemplate; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.sql.Connection; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; @@ -19,11 +19,11 @@ import java.util.List; */ public class Users { - Connection sql; + JdbcTemplate sql; UserSerializer userSerializer = new UserSerializer(); - public Users(Connection sql) { + public Users(JdbcTemplate sql) { this.sql = sql; } diff --git a/src/main/java/com/juick/api/Utils.java b/src/main/java/com/juick/api/Utils.java index 10e0cccb..db73fdaa 100644 --- a/src/main/java/com/juick/api/Utils.java +++ b/src/main/java/com/juick/api/Utils.java @@ -27,6 +27,7 @@ import java.util.ArrayList; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.jdbc.core.JdbcTemplate; import sun.misc.BASE64Decoder; /** @@ -47,7 +48,7 @@ public class Utils { return null; } - public static com.juick.User getVisitorUser(Connection sql, HttpServletRequest request) { + public static com.juick.User getVisitorUser(JdbcTemplate sql, HttpServletRequest request) { String hash = getCookie(request, "hash"); if (hash != null) { return com.juick.server.UserQueries.getUserByHash(sql, hash); @@ -56,7 +57,7 @@ public class Utils { } } - public static int getVisitorUID(Connection sql, HttpServletRequest request) { + public static int getVisitorUID(JdbcTemplate sql, HttpServletRequest request) { Cookie cookies[] = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { @@ -84,7 +85,7 @@ public class Utils { return 0; } - public static int getVisitorQueryStringUID(Connection sql, HttpServletRequest request) { + public static int getVisitorQueryStringUID(JdbcTemplate sql, HttpServletRequest request) { String hash = request.getParameter("hash"); if (hash != null && hash.length() == 16) { return com.juick.server.UserQueries.getUIDbyHash(sql, hash); diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java new file mode 100644 index 00000000..01cdd4c5 --- /dev/null +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -0,0 +1,40 @@ +package com.juick.tests; + +import com.juick.User; +import com.juick.server.UserQueries; +import junit.framework.Assert; +import org.apache.commons.dbcp2.BasicDataSource; +import org.junit.Before; +import org.junit.Test; +import org.springframework.jdbc.core.JdbcTemplate; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Properties; + +/** + * Created by vt on 14.01.2016. + */ +public class ApiTests { + JdbcTemplate jdbc; + @Before + public void setupConnection() { + Properties conf = new Properties(); + try { + conf.load(new FileInputStream("/etc/juick/api.conf")); + BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName("com.mysql.jdbc.Driver"); + dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + + conf.getProperty("mysql_username", "") + + "&password=" + conf.getProperty("mysql_password", "")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + public void userTests() { + User user = UserQueries.getUserByUID(jdbc, 3694); + Assert.assertEquals("it should be me", "vt", user.UName); + } +} -- cgit v1.2.3 From 552bc5210ecc06e58dcf4d67fb6191dbac2a219c Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 15 Jan 2016 13:14:30 +0300 Subject: sync deps --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index 9bd8a41c..1ef890d2 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 9bd8a41c0db5a1027a184facfca8d0152945c078 +Subproject commit 1ef890d21db2ed9aeefc37b71ff82d0f59df8516 -- cgit v1.2.3 From f9d5099bf4be816aa267e02b5713a672fd4da562 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 15 Jan 2016 14:49:51 +0300 Subject: spring-jdbc WIP --- deps/com.juick.server | 2 +- src/main/java/com/juick/api/Messages.java | 12 ++++++------ src/test/java/com/juick/tests/ApiTests.java | 9 +++++++++ 3 files changed, 16 insertions(+), 7 deletions(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index 1ef890d2..2635d618 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 1ef890d21db2ed9aeefc37b71ff82d0f59df8516 +Subproject commit 2635d6187ecd48c732d21e4f510f1df8451ce646 diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java index e3dcabfd..fb9be051 100644 --- a/src/main/java/com/juick/api/Messages.java +++ b/src/main/java/com/juick/api/Messages.java @@ -82,7 +82,7 @@ public class Messages { } public void doGetRecommended(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { - /*int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0); + int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0); List mids = MessagesQueries.getUserRecommendations(sql, vuid, before_mid); if (mids != null && !mids.isEmpty()) { @@ -95,21 +95,21 @@ public class Messages { } } else { response.sendError(404); - }*/ + } } public void doSetPrivacy(HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid) throws ServletException, IOException { - /*int mid = Utils.parseInt(request.getParameter("mid"), 0); + int mid = Utils.parseInt(request.getParameter("mid"), 0); com.juick.User user = MessagesQueries.getMessageAuthor(sql, mid); if (user != null && user.UID == vuid && MessagesQueries.setMessagePrivacy(sql, mid)) { Main.replyJSON(request, response, "{\"status\":\"ok\"}"); } else { response.sendError(400); - }*/ + } } public void doSetPopular(HttpServletRequest request, HttpServletResponse response, Stream xmpp) throws ServletException, IOException { - /*int mid = Utils.parseInt(request.getParameter("mid"), 0); + int mid = Utils.parseInt(request.getParameter("mid"), 0); int popular = Utils.parseInt(request.getParameter("popular"), 0); if (mid > 0) { @@ -141,6 +141,6 @@ public class Messages { } Main.replyJSON(request, response, "{\"status\":\"ok\"}"); - }*/ + } } } diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java index f111ffc7..e67c23f2 100644 --- a/src/test/java/com/juick/tests/ApiTests.java +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -1,7 +1,9 @@ package com.juick.tests; +import com.juick.Message; import com.juick.User; import com.juick.server.UserQueries; +import com.juick.server.MessagesQueries; import junit.framework.Assert; import org.apache.commons.dbcp2.BasicDataSource; import org.junit.Before; @@ -38,4 +40,11 @@ public class ApiTests { User user = UserQueries.getUserByUID(jdbc, 3694); Assert.assertEquals("it should be me", "vt", user.UName); } + + @Test void messageTests() { + Message msg = MessagesQueries.getMessage(jdbc, 2817722); + User ugnich = msg.User; + Assert.assertEquals("ugnich", ugnich.UName); + Assert.assertEquals("Microsoft", msg.Tags.get(0)); + } } -- cgit v1.2.3 From 09ed21dc11cecb55596a8356b8779be31b3efb98 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 15 Jan 2016 15:01:24 +0300 Subject: sync deps --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index 2635d618..392b0e33 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 2635d6187ecd48c732d21e4f510f1df8451ce646 +Subproject commit 392b0e333248665a72eaf1febee4ccea9a7edf1f -- cgit v1.2.3 From 45e243c10ce25460c6782d5189c6c9e4860ad516 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 15 Jan 2016 15:20:42 +0300 Subject: sync deps --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index 392b0e33..0ac9d76d 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 392b0e333248665a72eaf1febee4ccea9a7edf1f +Subproject commit 0ac9d76d6348f487ada697678395d15abee244c9 -- cgit v1.2.3 From 30068e18a3d8ae37b509f5cd766515735a818692 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 15 Jan 2016 15:54:04 +0300 Subject: update core --- deps/com.juick | 2 +- deps/com.juick.server | 2 +- src/main/java/com/juick/api/Messages.java | 23 ++++++++++++++++------- src/main/java/com/juick/api/Others.java | 4 +++- src/main/java/com/juick/api/PM.java | 16 ++++++++++------ src/main/java/com/juick/api/Users.java | 20 +++++++++++++------- src/test/java/com/juick/tests/ApiTests.java | 6 +++--- 7 files changed, 47 insertions(+), 26 deletions(-) (limited to 'deps') diff --git a/deps/com.juick b/deps/com.juick index 5f08b8b1..1df19b47 160000 --- a/deps/com.juick +++ b/deps/com.juick @@ -1 +1 @@ -Subproject commit 5f08b8b1cfaacf1e78c56e7752277533eb84b02e +Subproject commit 1df19b47f7f463e6cafa7dcf877cb42967fff166 diff --git a/deps/com.juick.server b/deps/com.juick.server index 0ac9d76d..f14eea2c 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 0ac9d76d6348f487ada697678395d15abee244c9 +Subproject commit f14eea2cfc80dac5e9b304a57457e7f82842a8ed diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java index fb9be051..e242d05b 100644 --- a/src/main/java/com/juick/api/Messages.java +++ b/src/main/java/com/juick/api/Messages.java @@ -53,7 +53,9 @@ public class Messages { this.sql = sql; } - public void doGetHome(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + public void doGetHome(HttpServletRequest request, + HttpServletResponse response, int vuid) + throws ServletException, IOException { int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0); List mids = MessagesQueries.getMyFeed(sql, vuid, before_mid); @@ -70,7 +72,8 @@ public class Messages { } } - public void doGet(HttpServletRequest request, HttpServletResponse response, int vuid) + public void doGet(HttpServletRequest request, + HttpServletResponse response, int vuid) throws ServletException, IOException { User user = UserQueries.getUserByName(sql, request.getParameter("uname")); int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0); @@ -81,7 +84,9 @@ public class Messages { } - public void doGetRecommended(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + public void doGetRecommended(HttpServletRequest request, + HttpServletResponse response, int vuid) + throws ServletException, IOException { int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0); List mids = MessagesQueries.getUserRecommendations(sql, vuid, before_mid); @@ -98,17 +103,21 @@ public class Messages { } } - public void doSetPrivacy(HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid) throws ServletException, IOException { + public void doSetPrivacy(HttpServletRequest request, + HttpServletResponse response, Stream xmpp, int vuid) + throws ServletException, IOException { int mid = Utils.parseInt(request.getParameter("mid"), 0); com.juick.User user = MessagesQueries.getMessageAuthor(sql, mid); - if (user != null && user.UID == vuid && MessagesQueries.setMessagePrivacy(sql, mid)) { + if (user != null && user.getUID() == vuid && MessagesQueries.setMessagePrivacy(sql, mid)) { Main.replyJSON(request, response, "{\"status\":\"ok\"}"); } else { response.sendError(400); } } - public void doSetPopular(HttpServletRequest request, HttpServletResponse response, Stream xmpp) throws ServletException, IOException { + public void doSetPopular(HttpServletRequest request, + HttpServletResponse response, Stream xmpp) + throws ServletException, IOException { int mid = Utils.parseInt(request.getParameter("mid"), 0); int popular = Utils.parseInt(request.getParameter("popular"), 0); @@ -123,7 +132,7 @@ public class Messages { msg.from = new JID("juick", "juick.com", null); msg.to = new JID(null, "crosspost.juick.com", null); JuickMessage jmsg = new JuickMessage(m); - jmsg.User.UID = 11574; + jmsg.setUser(UserQueries.getUserByUID(sql, 11574)); msg.childs.add(jmsg); msg.to.Username = "twitter"; diff --git a/src/main/java/com/juick/api/Others.java b/src/main/java/com/juick/api/Others.java index 3c8d4a96..12849f90 100644 --- a/src/main/java/com/juick/api/Others.java +++ b/src/main/java/com/juick/api/Others.java @@ -26,7 +26,9 @@ public class Others { this.sql = sql; } - public void doGetGroupsPMs(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + public void doGetGroupsPMs(HttpServletRequest request, + HttpServletResponse response, int vuid) + throws ServletException, IOException { int cnt = 5; try { String cntStr = request.getParameter("cnt"); diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java index 01a5669a..3ca9eada 100644 --- a/src/main/java/com/juick/api/PM.java +++ b/src/main/java/com/juick/api/PM.java @@ -29,7 +29,9 @@ public class PM { this.sql = sql; } - public void doGetPM(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + public void doGetPM(HttpServletRequest request, + HttpServletResponse response, int vuid) + throws ServletException, IOException { String uname = request.getParameter("uname"); int uid = 0; if (uname != null && uname.matches("^[a-zA-Z0-9\\-]{2,16}$")) { @@ -50,7 +52,9 @@ public class PM { } } - public void doPostPM(HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid) throws ServletException, IOException { + public void doPostPM(HttpServletRequest request, + HttpServletResponse response, Stream xmpp, int vuid) + throws ServletException, IOException { String uname = request.getParameter("uname"); int uid = 0; if (UserQueries.checkUserNameValid(uname)) { @@ -73,8 +77,8 @@ public class PM { msg.from = new JID("juick", "juick.com", null); msg.to = new JID(Integer.toString(uid), "push.juick.com", null); JuickMessage jmsg = new JuickMessage(); - jmsg.User = UserQueries.getUserByUID(sql, vuid); - jmsg.Text = body; + jmsg.setUser(UserQueries.getUserByUID(sql, vuid)); + jmsg.setText(body); msg.childs.add(jmsg); xmpp.send(msg); @@ -89,11 +93,11 @@ public class PM { mm.to = new JID(jid); mm.type = Message.Type.chat; if (PMQueries.havePMinRoster(sql, vuid, jid)) { - mm.from = new JID(jmsg.User.UName, "juick.com", "Juick"); + mm.from = new JID(jmsg.getUser().getUName(), "juick.com", "Juick"); mm.body = body; } else { mm.from = new JID("juick", "juick.com", "Juick"); - mm.body = "Private message from @" + jmsg.User.UName + ":\n" + body; + mm.body = "Private message from @" + jmsg.getUser().getUName() + ":\n" + body; } xmpp.send(mm); } diff --git a/src/main/java/com/juick/api/Users.java b/src/main/java/com/juick/api/Users.java index d3818a5a..57f8c4b9 100644 --- a/src/main/java/com/juick/api/Users.java +++ b/src/main/java/com/juick/api/Users.java @@ -27,7 +27,9 @@ public class Users { this.sql = sql; } - public void doGetUsers(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + public void doGetUsers(HttpServletRequest request, + HttpServletResponse response, int vuid) + throws ServletException, IOException { List users = new ArrayList<>(); String punames[] = request.getParameterValues("uname"); @@ -66,7 +68,9 @@ public class Users { } } - public void doGetUserRead(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + public void doGetUserRead(HttpServletRequest request, + HttpServletResponse response, int vuid) + throws ServletException, IOException { int uid = 0; String uname = request.getParameter("uname"); if (uname == null) { @@ -74,8 +78,8 @@ public class Users { } else { if (UserQueries.checkUserNameValid(uname)) { com.juick.User u = UserQueries.getUserByName(sql, uname); - if (u != null && u.UID > 0) { - uid = u.UID; + if (u != null && u.getUID() > 0) { + uid = u.getUID(); } } } @@ -94,7 +98,9 @@ public class Users { response.sendError(404); } - public void doGetUserReaders(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { + public void doGetUserReaders(HttpServletRequest request, + HttpServletResponse response, int vuid) + throws ServletException, IOException { int uid = 0; String uname = request.getParameter("uname"); if (uname == null) { @@ -102,8 +108,8 @@ public class Users { } else { if (UserQueries.checkUserNameValid(uname)) { com.juick.User u = UserQueries.getUserByName(sql, uname); - if (u != null && u.UID > 0) { - uid = u.UID; + if (u != null && u.getUID() > 0) { + uid = u.getUID(); } } } diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java index b679f528..046077ef 100644 --- a/src/test/java/com/juick/tests/ApiTests.java +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -38,14 +38,14 @@ public class ApiTests { @Test public void userTests() { User user = UserQueries.getUserByUID(jdbc, 3694); - Assert.assertEquals("it should be me", "vt", user.UName); + Assert.assertEquals("it should be me", "vt", user.getUName()); } @Test public void messageTests() { Message msg = MessagesQueries.getMessage(jdbc, 2817722); - User ugnich = msg.User; - Assert.assertEquals("ugnich", ugnich.UName); + User ugnich = msg.getUser(); + Assert.assertEquals("ugnich", ugnich.getUName()); Assert.assertEquals("Microsoft", msg.Tags.get(0)); } } -- cgit v1.2.3 From fab3c7d5462cd0b54de3a8cdd377e3476fa90285 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sat, 16 Jan 2016 14:04:21 +0300 Subject: sync deps --- deps/com.juick.json | 2 +- deps/com.juick.server | 2 +- deps/com.juick.xmpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'deps') diff --git a/deps/com.juick.json b/deps/com.juick.json index c152ab72..ee0e13e7 160000 --- a/deps/com.juick.json +++ b/deps/com.juick.json @@ -1 +1 @@ -Subproject commit c152ab72d3ba8f662706eb4b1342d839762a243a +Subproject commit ee0e13e7243abecf242236c224551774195524a3 diff --git a/deps/com.juick.server b/deps/com.juick.server index f14eea2c..09fd6b8e 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit f14eea2cfc80dac5e9b304a57457e7f82842a8ed +Subproject commit 09fd6b8ee40802eceff9746d3c23aa8446ccbd64 diff --git a/deps/com.juick.xmpp b/deps/com.juick.xmpp index 87ca4b93..c266eb31 160000 --- a/deps/com.juick.xmpp +++ b/deps/com.juick.xmpp @@ -1 +1 @@ -Subproject commit 87ca4b93d426c19b6fdaeec038202485515606d5 +Subproject commit c266eb31e454dc382caadf8efc19d688125ac287 -- cgit v1.2.3 From f0834c91bfcd8b5d6f658c946334ad6b89ad36a3 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sat, 16 Jan 2016 18:33:36 +0300 Subject: almost working with spring-jdbc --- build.gradle | 1 + deps/com.juick | 2 +- deps/com.juick.json | 2 +- deps/com.juick.server | 2 +- deps/com.juick.xmpp | 2 +- src/main/java/com/juick/api/Main.java | 39 ++------ src/main/java/com/juick/api/Utils.java | 2 +- src/test/java/com/juick/tests/ApiTests.java | 127 +++++++++++++++++++++------ src/test/java/com/juick/tests/JsonTests.java | 55 ------------ src/test/java/com/juick/tests/original.json | 1 - 10 files changed, 110 insertions(+), 123 deletions(-) delete mode 100644 src/test/java/com/juick/tests/JsonTests.java delete mode 100644 src/test/java/com/juick/tests/original.json (limited to 'deps') diff --git a/build.gradle b/build.gradle index 380f5b39..ea705d8c 100644 --- a/build.gradle +++ b/build.gradle @@ -61,6 +61,7 @@ dependencies { "org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}" testCompile 'junit:junit:4.12' runtime 'mysql:mysql-connector-java:5.1.37' + testRuntime 'com.h2database:h2:1.4.190' } compileJava.options.encoding = 'UTF-8' diff --git a/deps/com.juick b/deps/com.juick index 1df19b47..39ec74ab 160000 --- a/deps/com.juick +++ b/deps/com.juick @@ -1 +1 @@ -Subproject commit 1df19b47f7f463e6cafa7dcf877cb42967fff166 +Subproject commit 39ec74abe77cdab5aa8f50c2524e6f71c2dbbd01 diff --git a/deps/com.juick.json b/deps/com.juick.json index ee0e13e7..9a50ad8d 160000 --- a/deps/com.juick.json +++ b/deps/com.juick.json @@ -1 +1 @@ -Subproject commit ee0e13e7243abecf242236c224551774195524a3 +Subproject commit 9a50ad8dea5e9ebc5eb1c5efb19aa7a784283e14 diff --git a/deps/com.juick.server b/deps/com.juick.server index 09fd6b8e..714a267a 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 09fd6b8ee40802eceff9746d3c23aa8446ccbd64 +Subproject commit 714a267ae35354e86512288e0ac91990937f95ab diff --git a/deps/com.juick.xmpp b/deps/com.juick.xmpp index c266eb31..a096ecc6 160000 --- a/deps/com.juick.xmpp +++ b/deps/com.juick.xmpp @@ -1 +1 @@ -Subproject commit c266eb31e454dc382caadf8efc19d688125ac287 +Subproject commit a096ecc6d011bf0f6c738b10d7d0a7319ffcf2dc diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index 4233c45d..cdced593 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -33,9 +33,6 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; import java.util.Properties; /** @@ -46,8 +43,6 @@ import java.util.Properties; @MultipartConfig public class Main extends HttpServlet implements Stream.StreamListener { - Connection sql; - Connection sqlSearch; JdbcTemplate jdbc; Stream xmpp; Messages messages; @@ -62,11 +57,8 @@ public class Main extends HttpServlet implements Stream.StreamListener { Properties conf = new Properties(); conf.load(new FileInputStream("/etc/juick/api.conf")); final String driverClassName = "com.mysql.jdbc.Driver"; - Class.forName(driverClassName); - sql = DriverManager.getConnection("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", "")); - sqlSearch = DriverManager.getConnection("jdbc:mysql://127.0.0.1:9306/juick?autoReconnect=true&characterEncoding=utf8&maxAllowedPacket=512000&relaxAutoCommit=true&user=root&password="); DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setUrl(sql.getMetaData().getURL()); + dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", "")); dataSource.setDriverClassName(driverClassName); jdbc = new JdbcTemplate(dataSource); messages = new Messages(jdbc); @@ -76,8 +68,8 @@ public class Main extends HttpServlet implements Stream.StreamListener { setupXmppComponent(conf.getProperty("xmpp_password")); - } catch (IOException | ClassNotFoundException | SQLException e) { - log(null, e); + } catch (IOException e) { + log("API initialization error", e); } } @@ -105,27 +97,6 @@ public class Main extends HttpServlet implements Stream.StreamListener { System.err.println("XMPP STREAM READY"); } - @Override - public void destroy() { - super.destroy(); - if (sql != null) { - try { - sql.close(); - sql = null; - } catch (SQLException e) { - log(null, e); - } - } - if (sqlSearch != null) { - try { - sqlSearch.close(); - sqlSearch = null; - } catch (SQLException e) { - log(null, e); - } - } - } - /** * Handles the HTTP GET method. * @param request servlet request @@ -139,7 +110,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { request.setCharacterEncoding("UTF-8"); } - int vuid = Utils.getHttpAuthUID(sql, request); + int vuid = Utils.getHttpAuthUID(jdbc, request); if (vuid == 0) { vuid = Utils.getVisitorQueryStringUID(jdbc, request); } @@ -197,7 +168,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { request.setCharacterEncoding("UTF-8"); } - int vuid = Utils.getHttpAuthUID(sql, request); + int vuid = Utils.getHttpAuthUID(jdbc, request); if (vuid == 0) { vuid = Utils.getVisitorQueryStringUID(jdbc, request); } diff --git a/src/main/java/com/juick/api/Utils.java b/src/main/java/com/juick/api/Utils.java index db73fdaa..ccb81f8e 100644 --- a/src/main/java/com/juick/api/Utils.java +++ b/src/main/java/com/juick/api/Utils.java @@ -70,7 +70,7 @@ public class Utils { return 0; } - public static int getHttpAuthUID(Connection sql, HttpServletRequest request) { + public static int getHttpAuthUID(JdbcTemplate sql, HttpServletRequest request) { String auth = request.getHeader("Authorization"); if (auth != null && auth.length() > 8 && auth.startsWith("Basic ")) { try { diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java index f7d6d6ac..83afb62e 100644 --- a/src/test/java/com/juick/tests/ApiTests.java +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -1,18 +1,21 @@ package com.juick.tests; import com.juick.Message; +import com.juick.Tag; import com.juick.User; import com.juick.server.MessagesQueries; +import com.juick.server.TagQueries; import com.juick.server.UserQueries; import junit.framework.Assert; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Properties; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; /** * Created by vt on 14.01.2016. @@ -21,35 +24,103 @@ public class ApiTests { JdbcTemplate jdbc; @Before public void setupConnection() { - Properties conf = new Properties(); - try { - conf.load(new FileInputStream("/etc/juick/api.conf")); - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user=" - + conf.getProperty("mysql_username", "") - + "&password=" + conf.getProperty("mysql_password", "")); - jdbc = new JdbcTemplate(dataSource); - } catch (IOException e) { - e.printStackTrace(); - } + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.h2.Driver"); + dataSource.setUrl("jdbc:h2:~/test"); + jdbc = new JdbcTemplate(dataSource); + jdbc.execute("CREATE TABLE bl_users (user_id int(10) unsigned NOT NULL, " + + "bl_user_id int(10) unsigned NOT NULL, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP )"); + jdbc.execute("CREATE TABLE messages (" + + "message_id int(10) unsigned NOT NULL AUTO_INCREMENT," + + "user_id int(10) unsigned NOT NULL," + + "place_id int(10) unsigned DEFAULT NULL," + + "lat decimal(10,7) DEFAULT NULL," + + "lon decimal(10,7) DEFAULT NULL," + + "ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP," + + "replies smallint(5) unsigned NOT NULL DEFAULT 0," + + "maxreplyid smallint(5) unsigned NOT NULL DEFAULT 0," + + "privacy tinyint(4) NOT NULL DEFAULT '1'," + + "attach nchar(3) check (attach in ('jpg', 'mp4', 'png'))," + + "readonly tinyint(1) NOT NULL DEFAULT 0," + + "likes smallint(6) NOT NULL DEFAULT 0," + + "hidden tinyint(3) unsigned NOT NULL DEFAULT 0" + + ")"); + jdbc.execute("CREATE TABLE messages_tags (" + + "message_id int(10) unsigned NOT NULL," + + "tag_id int(10) unsigned NOT NULL" + + ")"); + jdbc.execute("CREATE TABLE users (" + + "id int(10) unsigned NOT NULL AUTO_INCREMENT," + + "nick char(64) NOT NULL," + + "passw char(32) NOT NULL," + + "banned tinyint(3) unsigned NOT NULL DEFAULT 0)"); + jdbc.execute("CREATE TABLE useroptions (" + + "user_id int(10) unsigned NOT NULL," + + "jnotify tinyint(1) NOT NULL DEFAULT 1," + + "subscr_active tinyint(1) NOT NULL DEFAULT 1)"); + jdbc.execute("CREATE TABLE subscr_users (" + + "user_id int(10) unsigned NOT NULL," + + "suser_id int(10) unsigned NOT NULL," + + "jid char(64) DEFAULT NULL," + + "active tinyint(1) NOT NULL DEFAULT 1," + + "ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)"); + jdbc.execute("CREATE TABLE messages_txt (" + + "message_id int(10) unsigned NOT NULL," + + "tags varchar(255)," + + "repliesby varchar(96)," + + "txt TEXT)"); + jdbc.execute("CREATE TABLE tags(" + + "tag_id int(10) unsigned NOT NULL AUTO_INCREMENT," + + "synonym_id int(10) unsigned DEFAULT NULL," + + "name char(48) NOT NULL," + + "top tinyint(1) unsigned NOT NULL DEFAULT 0," + + "stat_messages int(10) unsigned NOT NULL DEFAULT 0," + + "stat_users smallint(5) unsigned NOT NULL DEFAULT 0)"); + jdbc.execute("CREATE TABLE replies (" + + "message_id int(10) unsigned NOT NULL," + + "reply_id smallint(5) unsigned NOT NULL," + + "user_id int(10) unsigned NOT NULL," + + "replyto smallint(5) unsigned NOT NULL DEFAULT 0," + + "ts timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," + + "attach nchar(3) check (attach in ('jpg', 'mp4', 'png'))," + + "txt text)"); } - - @Test - public void userTests() { - User user = UserQueries.getUserByUID(jdbc, 3694); - Assert.assertEquals("it should be me", "vt", user.getUName()); + @After + public void tearDown() { + jdbc.execute("DROP ALL OBJECTS DELETE FILES"); } + @Test public void messageTests() { - Message msg = MessagesQueries.getMessage(jdbc, 2817722); - User ugnich = msg.getUser(); - Assert.assertEquals("ugnich", ugnich.getUName()); - org.junit.Assert.assertEquals("ugnich", MessagesQueries.getMessageAuthor(jdbc, 2817722).getUName()); - Assert.assertEquals("Microsoft", msg.Tags.get(0)); - Message reply = MessagesQueries.getReply(jdbc, 2817722, 8); - User linda = reply.getUser(); - Assert.assertEquals("Linda-chan", linda.getUName()); + int user_id = UserQueries.createUser(jdbc, "me", "secret"); + User user = UserQueries.getUserByUID(jdbc, user_id); + Assert.assertEquals("it should be me", "me", user.getUName()); + int mid = MessagesQueries.createMessage(jdbc, user_id, "yo", null, new ArrayList<>()); + Message msg = MessagesQueries.getMessage(jdbc, mid); + org.junit.Assert.assertEquals("yo", msg.getText()); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(msg.getDate()); + org.junit.Assert.assertEquals(2016, calendar.get(Calendar.YEAR)); + User me = msg.getUser(); + Assert.assertEquals("me", me.getUName()); + org.junit.Assert.assertEquals("me", MessagesQueries.getMessageAuthor(jdbc, mid).getUName()); + int tagID = TagQueries.createTag(jdbc, "weather"); + Tag tag = TagQueries.getTag(jdbc, tagID); + List tagList = new ArrayList<>(); + tagList.add(tag); + int mid2 = MessagesQueries.createMessage(jdbc, user_id, "yo2", null, tagList); + Message msg2 = MessagesQueries.getMessage(jdbc, mid2); + org.junit.Assert.assertEquals(1, msg2.Tags.size()); + int ugnich_id = UserQueries.createUser(jdbc, "ugnich", "x"); + User ugnich = UserQueries.getUserByUID(jdbc, ugnich_id); + int rid = MessagesQueries.createReply(jdbc, msg2.getMID(), 0, ugnich.getUID(), "bla-bla", null); + org.junit.Assert.assertEquals(1, rid); + Message msg3 = MessagesQueries.getMessage(jdbc, mid2); + org.junit.Assert.assertEquals(1, msg3.Replies); + org.junit.Assert.assertEquals("weather", msg3.Tags.get(0)); + org.junit.Assert.assertEquals(ugnich.getUID(), UserQueries.checkPassword(jdbc, ugnich.getUName(), "x")); + org.junit.Assert.assertEquals(-1, UserQueries.checkPassword(jdbc, ugnich.getUName(), "xy")); } + } diff --git a/src/test/java/com/juick/tests/JsonTests.java b/src/test/java/com/juick/tests/JsonTests.java deleted file mode 100644 index 795b3429..00000000 --- a/src/test/java/com/juick/tests/JsonTests.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.juick.tests; - -import com.juick.json.MessageSerializer; -import com.juick.server.MessagesQueries; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.jdbc.datasource.DriverManagerDataSource; - -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.List; -import java.util.Properties; - -public class JsonTests { - - JdbcTemplate jdbc; - @Before - public void setupConnection() { - Properties conf = new Properties(); - try { - conf.load(new FileInputStream("/etc/juick/api.conf")); - DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setDriverClassName("com.mysql.jdbc.Driver"); - dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user=" - + conf.getProperty("mysql_username", "") - + "&password=" + conf.getProperty("mysql_password", "")); - jdbc = new JdbcTemplate(dataSource); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Test - public void CompareSerializers() { - List mids = MessagesQueries.getMyFeed(jdbc, 3694, 2799786); - MessageSerializer messageSerializer = new MessageSerializer(); - if (mids != null && !mids.isEmpty()) { - List msgs = MessagesQueries.getMessages(jdbc, mids); - if (msgs != null && !msgs.isEmpty()) { - String json = messageSerializer.serializeList(msgs); - try { - String data = new String(Files.readAllBytes(Paths.get("original.json")), "UTF-8"); - Assert.assertEquals("json should match", data, json); - } catch (IOException e) { - e.printStackTrace(); - } - - } - } - } -} diff --git a/src/test/java/com/juick/tests/original.json b/src/test/java/com/juick/tests/original.json deleted file mode 100644 index 2f4e42a3..00000000 --- a/src/test/java/com/juick/tests/original.json +++ /dev/null @@ -1 +0,0 @@ -[{"mid":2799784,"user":{"uid":27928,"uname":"Rainbow-Spike"},"body":"это не стили, а ё-аный пиздец какой-то","tags":["докувики","MLP","CSS"],"timestamp":"2015-08-22 02:01:49"},{"mid":2799783,"user":{"uid":14276,"uname":"waterlaz"},"body":"Катались с Ляхом по грунтовым дорожкам Труханового острова на тандеме, заехали в песок и погнули вилку, а я сильно ударил себе тазобедренную кость. Успех.","tags":["велосипеды","тандем","L29Ah"],"timestamp":"2015-08-22 01:12:22","replies":1,"repliesby":"@failman"},{"mid":2799782,"user":{"uid":25625,"uname":"provaton"},"body":"Посмотрел отрывки из озеровского "направления главного удара", и вот никак не могу отделаться от навязчивой мысли. Каково было немецким актерам там играть? Гитлер и его генералы там выставлены немного в клоунском свете. А ведь в эту войну немецкий народ вложил почти все свои силы. Это ж не только мы в блокадном ленинграде умирали - неемцы там тоже не объедались, особенно к концу войны. И бомбили их в тылу союзнички нещадно, и на фронтах били превосходящие силы. Но немцы бились как звери, в условиях подавляющего превосходства врага. Бились искренне, за Родину. А тут бери и играй роль мудака, которого великие русские отымели как последнего дебила. Не понимаю.","tags":["тег"],"timestamp":"2015-08-22 00:58:20"},{"mid":2799781,"user":{"uid":14978,"uname":"ndtimofeev"},"body":"Моя женщина ткнула меня в Lindemann - Skills in Pills. Это целый альбом который выглядит как песни не вошедшие в Liebe ist für alle da потому что там и так до хрена всего^W^W^W^W^Wих нельзя крутить по радио исполненные в немного электронном варианте. Я рад.","tags":["rammstein","music"],"timestamp":"2015-08-22 00:56:06"},{"mid":2799780,"user":{"uid":14978,"uname":"ndtimofeev"},"body":"Одна из причин по которой haskell хреново заменяет python состоит в том что он работает как помешательство у малковиан: кинул кубик и всё сделал в 500 строк, кинул кубик ещё раз и добавил блэкджек и шлюх, кинул ещё и обнаружил что уже неделю сидишь и читаешь статьи по какой-то абстрактной фигне.","tags":["vtm","Haskell"],"timestamp":"2015-08-22 00:50:32","replies":1},{"mid":2799779,"user":{"uid":25625,"uname":"provaton"},"body":"http://jpgazeta.ru/priznayte-menya-russkoy/\n\nЕще одну романтичную душу долбануло российской бюрократией по самые помидоры.","tags":["тег"],"timestamp":"2015-08-21 23:51:10","replies":1,"repliesby":"@ig276"},{"mid":2799778,"user":{"uid":28473,"uname":"complemento"},"body":"[Курс доллара подскочил до 69 рублей][https://news.mail.ru/economics/23055957/]","tags":["3m"],"timestamp":"2015-08-21 23:48:28"},{"mid":2799777,"user":{"uid":16608,"uname":"lurker"},"body":"...","tags":["альтернатива"],"timestamp":"2015-08-21 23:40:34","replies":2,"photo":{"thumbnail":"http://i.juick.com/ps/2799777.jpg","small":"http://i.juick.com/photos-512/2799777.jpg","medium":"http://i.juick.com/photos-1024/2799777.jpg"}},{"mid":2799776,"user":{"uid":176,"uname":"bighouse"},"body":"Не долго музыка играла... Откатываюсь с 10 ки на 8.1.. Не впечатлила десятка. Минусов куча, а плюсов не обнаружил.","tags":["вин"],"timestamp":"2015-08-21 23:33:19","replies":1,"repliesby":"@SolderStain"},{"mid":2799775,"user":{"uid":17560,"uname":"iZevg"},"body":"Ребятки, посоветуйте хостинг с 5Гб HDD, CPanel и PHP до 200 руб/м","tags":["?","web"],"timestamp":"2015-08-21 22:48:37","replies":2},{"mid":2799774,"user":{"uid":23893,"uname":"Shizokl"},"body":"Мировая экономика, бессердечная ты сука, остановись, прекрати. Тебя уже не существует уже который месяц. Верни нефть-матушку в исконное стодолларовое равновесие, бо лепо было и любо!","tags":["."],"timestamp":"2015-08-21 22:39:31"},{"mid":2799773,"user":{"uid":6715,"uname":"O01eg"},"body":"http://blog.kittysanders.com/interviewmovie/\n"Посмотрела нашумевшее «Интервью», то самое, где убивают Ким Чен Ына, из-за чего оный Ын взбесился и начал нервно угрожать США.\nВ последнее время снимается много фильмов, «высмеивающих тоталитаризм», какие-то из них более удачные, какие-то — совершенно кривые, как вышедший недавно «Джеки в царстве женщин», о котором мы поговорим отдельно. Проблема в том, что США (и, если говорить шире, «Запад») умеют бороться только тогда, когда в Белом доме и в Голливуде доминируют правые параноики, которые понимают очарование тоталитаризма. Они понимают, что ощущают люди, ставшие частью единого коллективного тела, люди, утратившие «Я» и приобретшие «Мы». Они знают, как волнующе звучит старое доброе «война — это мир, свобода — это рабство, незнание — сила». И эти параноики используют верные ходы в борьбе с этой притягательностью зла. Потому что они его понимают, они говорят с ним на одном языке, их лица обожжены дыханием Бельфегора, они сталкивались с ним и смогли преодолеть соблазн.\nЕсли мне зачем-то нужно будет рассказать о том, что свобода — это рабство, я смогу без подготовки говорить минут 10-15. Если вы скажете мне, что в нижеприведенном стихе нет чего-то, цепляющего вашу глубокую, грязную, обычно тихо лежащую тихо, часть, которую вы со стыдом прячете от всех, потому что она плохая, вы это знаете, как ребенок, которого родители застали за плохими занятиями — вы либо соврете, либо вы не настолько носитель этого, скорее всего, выросший в какой-то благополучной стране. Но вообще, это задевает густую чёрную дрянь, которая залегает очень глубоко. Как нефть. Эта нефть есть в большинстве из нас, людей с высоким IQ и низкой усвоенностью социальных норм, родом из мест, достаточно развитых, чтобы дать нам возможность образоваться, но достаточно жестоких, чтобы периодически пытаться нас унитожить как личностей. Вопрос в том, чтобы держать ее под контролем. Потому что она — зло. Тот, кто писал эти стихи — «аулия эш-шайтан», «святой Сатаны». Надо это осознавать. Как надо осознавать, что героин в больших количествах отправит вас в ад бесконечной трансформации в собственный кошмар, и вы целую вечность будете маяться, не понимая, что умерли, куда там Тибецкой Книге Мёртвых. Но если ваше тело само производит героин, то с этим надо как-то жить и что-то предпринимать, иначе рано или поздно будет передоз.\nА век поджидает на мостовой,\nСосредоточен, как часовой.\nИди — и не бойся с ним рядом встать.\nТвое одиночество веку под стать.\nОглянешься — а вокруг враги;\nРуки протянешь — и нет друзей;\nНо если он скажет: «Солги»,- солги.\nНо если он скажет: «Убей»,- убей.\nЯ тоже почувствовал тяжкий груз\nОпущенной на плечо руки.\nПодстриженный по-солдатски ус\nКасался тоже моей щеки.\nИ стол мой раскидывался, как страна,\nВ крови, в чернилах квадрат сукна,\nРжавчина перьев, бумаги клок —\nВсё друга и недруга стерегло.\nВраги приходили — на тот же стул\nСадились и рушились в пустоту.\nИх нежные кости сосала грязь.\nНад ними захлопывались рвы.\nИ подпись на приговоре вилась\nСтруей из простреленной головы.\nВас встряхивает от этого стиха? Меня да. Я уже давно бросила притворяться. Подобно Адаму Чаплину, в лопатке которого жило существо без имени, я дала ему имя\nя буду звать тебя… Дерек\nи научилась жить с ним. А вы нет? Ну тогда у вас, наверное, много стресса в жизни, соболезную. Вы еще не поняли, что боль, страдание и вообще весь этот дискурс «подавления» — это бонус, если его держать под контролем, понимать, что он есть ваш внутренний «дьявол» и рационализировать его."","tags":["прекрасное"],"timestamp":"2015-08-21 22:35:51","replies":1},{"mid":2799772,"user":{"uid":16870,"uname":"AlexVK"},"body":"* MATE с 1 гиг занятым при загруденной IDE - неплохо, неплохо, впечатляет.","tags":["Linux","Fedora"],"timestamp":"2015-08-21 22:34:54","replies":3,"repliesby":"@AlexVK"},{"mid":2799771,"user":{"uid":6715,"uname":"O01eg"},"body":"https://2ch.hk/po/src/10469747/14401550234011.webm","tags":["прекрасное","говнорашка","humor"],"timestamp":"2015-08-21 22:31:39"},{"mid":2799770,"user":{"uid":8836,"uname":"OCTAGRAM"},"body":"Слушаю Аксёнова на [крымском госсовете](https://youtu.be/-nuoP7qI-dY?t=15m42s), и уши в трубочку сворачиваются от его предложений:\n– Предлагает ввести праздник: день виноградарства и виноделия\n– Пытается разделить «винный туризм» и «злоупотребление алкоголем», как если бы существовало употребление алкоголя, не являющееся злоупотреблением\n– Разрешить продавать в розницу вино на туристических, сельскохозяйственных и винных выставках, ярмарках и фестивалях\n– Рекомендовать врачам применять лечение вином\n\nНаверное, если бы Афганистан вырвался из–под управления США и вошёл в состав РФ, то его глава, понимая, как он впух, был бы тоже вынужден либо просить средства на то, чтобы переобучить чему–нибудь достойному всех этих бездельников, которые волею судеб ничего другого просто делать не умеют, либо вводить праздники, налаживать «опиумный туризм» с продажей опиума в розницу на выставках, ярмарках и фестивалях, рекомендовать врачам применять лечение опиумом, и даже нашёл бы таких учёных, которые подведут соответствующую базу","tags":["вещества","легалайз","Крым","алкоголь"],"timestamp":"2015-08-21 22:30:03"},{"mid":2799769,"user":{"uid":6715,"uname":"O01eg"},"body":"Жизнь эталонного пидороквадратника 30ых: сегодня ты дрочишь на Путина и лаешь на "пятую колонну", а завтра "пятая колонна" - ты: https://pbs.twimg.com/media/CM9EVRYWcAAzOdR.jpg:orig\n> В марте 1938 года был снят с поста начальника Московского управления НКВД и назначен начальником треста Камлесосплав. В апреле 1938 года снят с этого поста, уволен из НКВД, исключён из ВКП(б) и арестован 19 апреля 1938 года по обвинению в «создании латышской контрреволюционной организации в НКВД, а также шпионаже в пользу Германии, Польши, Англии». Расстрелян 29 августа 1938 года. После смерти Сталина реабилитирован не был.","tags":["прекрасное","говнорашка","сталирасты","history"],"timestamp":"2015-08-21 22:22:21","replies":2,"repliesby":"@Kim, @alv"},{"mid":2799768,"user":{"uid":6715,"uname":"O01eg"},"body":"https://i.imgur.com/nvoqXFY.jpg","tags":["прекрасное","говнорашка"],"timestamp":"2015-08-21 22:07:37","replies":6,"repliesby":"@Bounty, @O01eg, @Kim"},{"mid":2799767,"user":{"uid":16791,"uname":"alex0b"},"body":"Играем в некое подобие эрудита (скраблз). Мама вводит новое правило: нельзя одновременно две пустышки выставлять под видом разных букв. Детеныш сидит, мается в муках творчества, от недостатка гласных и избытка пустышек: "эх, жаль, что нельзя разногласие устроить". \nПодсказываю ему вариант: "синоним слова чёрт". Думает, пыхтит: "Не помню, но кажется /гадлёныш/".","tags":["слова","детеныш"],"timestamp":"2015-08-21 22:00:47","replies":1,"repliesby":"@Greederius"},{"mid":2799766,"user":{"uid":24531,"uname":"justonemore"},"body":"Прекрасная сценка из "The Chronicles of Riddick: Assault On Dark Athena": http://www.youtube.com/watch?v=Zizc3Dnf2fk&t=42m34s","tags":["games","riddick","видео"],"timestamp":"2015-08-21 21:32:02","replies":1},{"mid":2799765,"user":{"uid":6715,"uname":"O01eg"},"body":"https://pbs.twimg.com/media/CM7YQo1UkAAnLPZ.jpg:orig","tags":["прекрасное","humor","говнорашка"],"timestamp":"2015-08-21 21:26:33"}] \ No newline at end of file -- cgit v1.2.3 From 25e1314e1586e8f2f5bf9577527708da5d4d8efc Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sat, 16 Jan 2016 19:04:58 +0300 Subject: update deps --- deps/com.juick.json | 2 +- deps/com.juick.server | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'deps') diff --git a/deps/com.juick.json b/deps/com.juick.json index 9a50ad8d..1a39696a 160000 --- a/deps/com.juick.json +++ b/deps/com.juick.json @@ -1 +1 @@ -Subproject commit 9a50ad8dea5e9ebc5eb1c5efb19aa7a784283e14 +Subproject commit 1a39696a6eaf4ea41447e4426ccdcfacec657554 diff --git a/deps/com.juick.server b/deps/com.juick.server index 714a267a..27976585 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 714a267ae35354e86512288e0ac91990937f95ab +Subproject commit 279765857724cf35addc0e3f5e7180a8724d23b9 -- cgit v1.2.3 From 5cc1d595463e2e7b365fa99b59b552044eb3b776 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sat, 16 Jan 2016 19:13:44 +0300 Subject: sync deps --- deps/com.juick.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.json b/deps/com.juick.json index 1a39696a..143513ce 160000 --- a/deps/com.juick.json +++ b/deps/com.juick.json @@ -1 +1 @@ -Subproject commit 1a39696a6eaf4ea41447e4426ccdcfacec657554 +Subproject commit 143513cec90ab176e5c174fb4ed98c249652bda6 -- cgit v1.2.3 From 261d89f398bde4aeb6d84c2ae789a90732793272 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sat, 16 Jan 2016 19:16:58 +0300 Subject: update deps --- deps/com.juick.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.json b/deps/com.juick.json index 143513ce..9dfad84f 160000 --- a/deps/com.juick.json +++ b/deps/com.juick.json @@ -1 +1 @@ -Subproject commit 143513cec90ab176e5c174fb4ed98c249652bda6 +Subproject commit 9dfad84fa487960fde4cc4b0ac6760c8dd5f4ac9 -- cgit v1.2.3 From d8f9f16d16f4e2f7133de464ba8d3f6cc704bd00 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sun, 17 Jan 2016 00:18:33 +0300 Subject: almost working messages api --- .gitignore | 26 ++++---- build.gradle | 1 + deps/com.juick.server | 2 +- src/main/java/com/juick/api/Main.java | 31 +++++---- src/main/java/com/juick/api/Messages.java | 97 +++++++++++++++++++---------- src/main/java/com/juick/api/Utils.java | 5 ++ src/main/webapp/WEB-INF/juick.conf.example | 6 ++ src/test/java/com/juick/tests/ApiTests.java | 11 ++-- 8 files changed, 118 insertions(+), 61 deletions(-) create mode 100644 src/main/webapp/WEB-INF/juick.conf.example (limited to 'deps') diff --git a/.gitignore b/.gitignore index b25773e5..56340f6c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,14 @@ -build/* -.gradle/* -deps/* -.idea/* -**/*.iml -**/juick.conf -/build/ -/bin/ -/.nb-gradle/ -.settings/* -.classpath -.project +build/* +.gradle/* +deps/* +.idea/* +**/*.iml +**/juick.conf +/build/ +/bin/ +/.nb-gradle/ +.settings/* +.classpath +.project +**/*.properties +**/*.conf diff --git a/build.gradle b/build.gradle index ea705d8c..b76df16a 100644 --- a/build.gradle +++ b/build.gradle @@ -53,6 +53,7 @@ dependencies { compile server compile xmpp compile json + compile "org.apache.commons:commons-lang3:3.4" compile "org.springframework:spring-jdbc:4.2.4.RELEASE" providedCompile 'javax.servlet:javax.servlet-api:3.1.0' def tomcatVersion = '7.0.+' diff --git a/deps/com.juick.server b/deps/com.juick.server index 27976585..9232bdcb 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 279765857724cf35addc0e3f5e7180a8724d23b9 +Subproject commit 9232bdcb144bc3b94f4b825b3a4cb588078bd72d diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index cdced593..cc068ccd 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -29,11 +29,13 @@ import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.Properties; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.logging.LogManager; /** * @@ -54,37 +56,38 @@ public class Main extends HttpServlet implements Stream.StreamListener { public void init() throws ServletException { super.init(); try { + LogManager.getLogManager().readConfiguration(getServletContext().getResourceAsStream("WEB-INF/logging.properties")); Properties conf = new Properties(); - conf.load(new FileInputStream("/etc/juick/api.conf")); - final String driverClassName = "com.mysql.jdbc.Driver"; + conf.load(getServletContext().getResourceAsStream("WEB-INF/juick.conf")); DriverManagerDataSource dataSource = new DriverManagerDataSource(); - dataSource.setUrl("jdbc:mysql://localhost/juick?autoReconnect=true&user=" + conf.getProperty("mysql_username", "") + "&password=" + conf.getProperty("mysql_password", "")); - dataSource.setDriverClassName(driverClassName); + dataSource.setDriverClassName(conf.getProperty("datasource_driver")); + dataSource.setUrl(conf.getProperty("datasource_url")); jdbc = new JdbcTemplate(dataSource); messages = new Messages(jdbc); users = new Users(jdbc); pm = new PM(jdbc); others = new Others(jdbc); - setupXmppComponent(conf.getProperty("xmpp_password")); + setupXmppComponent(conf.getProperty("xmpp_host", "localhost"), Integer.parseInt(conf.getProperty("xmpp_port", "5347")), + conf.getProperty("xmpp_jid", "api.localhost"), conf.getProperty("xmpp_password")); } catch (IOException e) { log("API initialization error", e); } } - public void setupXmppComponent(final String password) { - Thread thr = new Thread(() -> { + public void setupXmppComponent(final String host, final int port, final String jid, final String password) { + ExecutorService executorService = Executors.newSingleThreadExecutor(); + executorService.submit(() -> { try { - Socket socket = new Socket("localhost", 5347); - xmpp = new StreamComponent(new JID("", "api.juick.com", ""), socket.getInputStream(), socket.getOutputStream(), password); + Socket socket = new Socket(host, port); + xmpp = new StreamComponent(new JID(jid), socket.getInputStream(), socket.getOutputStream(), password); xmpp.addListener(Main.this); xmpp.startParsing(); } catch (IOException e) { log("XMPP exception", e); } }); - thr.start(); } @Override @@ -94,7 +97,7 @@ public class Main extends HttpServlet implements Stream.StreamListener { @Override public void onStreamReady() { - System.err.println("XMPP STREAM READY"); + log("XMPP STREAM READY"); } /** @@ -122,6 +125,10 @@ public class Main extends HttpServlet implements Stream.StreamListener { } else { response.sendError(401); } + } else if (uri.equals("/messages")) { + messages.doGet(request, response, vuid); + } else if (uri.equals("/thread")) { + messages.doThreadGet(request, response, vuid); } else if (uri.equals("/users")) { users.doGetUsers(request, response, vuid); } else if (uri.equals("/users/read")) { diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java index e242d05b..d86193f1 100644 --- a/src/main/java/com/juick/api/Messages.java +++ b/src/main/java/com/juick/api/Messages.java @@ -11,6 +11,7 @@ import com.juick.xmpp.Message; import com.juick.xmpp.Stream; import com.juick.xmpp.extensions.JuickMessage; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.util.StringUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -28,37 +29,11 @@ public class Messages { MessageSerializer messageSerializer = new MessageSerializer(); - enum MediaType { - ALL("all"), - PHOTO("photo"), - VIDEO("video"), - NONE(""); - - private final String value; - - MediaType(final String value) { - this.value = value; - } - public String getValue() { - return value; - } - - @Override - public String toString() { - return this.getValue(); - } - } - public Messages(JdbcTemplate sql) { this.sql = sql; } - public void doGetHome(HttpServletRequest request, - HttpServletResponse response, int vuid) - throws ServletException, IOException { - int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0); - - List mids = MessagesQueries.getMyFeed(sql, vuid, before_mid); + void feedMessages(HttpServletRequest request, HttpServletResponse response, List mids) throws IOException { if (mids != null && !mids.isEmpty()) { List msgs = MessagesQueries.getMessages(sql, mids); if (msgs != null && !msgs.isEmpty()) { @@ -72,16 +47,74 @@ public class Messages { } } + public void doGetHome(HttpServletRequest request, + HttpServletResponse response, int vuid) + throws ServletException, IOException { + int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0); + + feedMessages(request, response, MessagesQueries.getMyFeed(sql, vuid, before_mid)); + + } + public void doGet(HttpServletRequest request, HttpServletResponse response, int vuid) throws ServletException, IOException { - User user = UserQueries.getUserByName(sql, request.getParameter("uname")); int before_mid = Utils.parseInt(request.getParameter("before_mid"), 0); - int page = Utils.parseInt(request.getParameter("page"), 0); - MediaType media = MediaType.valueOf(request.getParameter("media")); - boolean popular = Boolean.valueOf(request.getParameter("popular")); - Tag tag = TagQueries.getTag(sql, request.getParameter("tag"), false); + String uname = request.getParameter("uname"); + String popular = request.getParameter("popular"); + String media = request.getParameter("media"); + String tag = request.getParameter("tag"); + if (!StringUtils.isEmpty(uname)) { + User user = UserQueries.getUserByName(sql, uname); + if (user != null) { + if (!StringUtils.isEmpty(media)) { + feedMessages(request, response, MessagesQueries.getUserPhotos(sql, user.getUID(), 0, before_mid)); + } else if (!StringUtils.isEmpty(tag)) { + Tag tagObject = TagQueries.getTag(sql, tag, false); + if (tagObject != null) { + feedMessages(request, response, MessagesQueries.getUserTag(sql, user.getUID(), tagObject.TID, 0, before_mid)); + } else { + response.sendError(404); + } + } else { + feedMessages(request, response, MessagesQueries.getUserBlog(sql, user.getUID(), 0, before_mid)); + } + } else { + response.sendError(404); + } + } else { + if (!StringUtils.isEmpty(popular)) { + feedMessages(request, response, MessagesQueries.getPopular(sql, before_mid)); + } else if (!StringUtils.isEmpty(media)) { + feedMessages(request, response, MessagesQueries.getPhotos(sql, vuid, before_mid)); + } else if (!StringUtils.isEmpty(tag)) { + Tag tagObject = TagQueries.getTag(sql, tag, false); + if (tagObject != null) { + feedMessages(request, response, MessagesQueries.getTag(sql, tagObject.TID, vuid, before_mid, 20)); + } else { + response.sendError(404); + } + } else { + feedMessages(request, response, MessagesQueries.getAll(sql, vuid, before_mid)); + } + } + } + public void doThreadGet(HttpServletRequest request, HttpServletResponse response, int vuid) throws IOException { + int mid = Utils.parseInt(request.getParameter("mid"), 0); + com.juick.Message msg = MessagesQueries.getMessage(sql, mid); + if (msg != null) { + if (!MessagesQueries.canViewThread(sql, mid, vuid)) { + response.sendError(403); + } else { + List replies = MessagesQueries.getReplies(sql, mid); + replies.add(0, msg); + String json = messageSerializer.serializeList(replies); + Main.replyJSON(request, response, json); + } + } else { + response.sendError(404); + } } public void doGetRecommended(HttpServletRequest request, diff --git a/src/main/java/com/juick/api/Utils.java b/src/main/java/com/juick/api/Utils.java index ccb81f8e..6383fec0 100644 --- a/src/main/java/com/juick/api/Utils.java +++ b/src/main/java/com/juick/api/Utils.java @@ -24,6 +24,8 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -36,6 +38,8 @@ import sun.misc.BASE64Decoder; */ public class Utils { + private static final Logger LOGGER = Logger.getLogger(Utils.class.getName()); + public static String getCookie(HttpServletRequest request, String name) { Cookie cookies[] = request.getCookies(); if (cookies != null) { @@ -80,6 +84,7 @@ public class Utils { return UserQueries.checkPassword(sql, loginpassw[0], loginpassw[1]); } } catch (IOException e) { + LOGGER.log(Level.WARNING, "Auth", e); } } return 0; diff --git a/src/main/webapp/WEB-INF/juick.conf.example b/src/main/webapp/WEB-INF/juick.conf.example new file mode 100644 index 00000000..61ebbc29 --- /dev/null +++ b/src/main/webapp/WEB-INF/juick.conf.example @@ -0,0 +1,6 @@ +datasource_driver=org.h2.Driver +datasource_url=jdbc:h2:~/test +xmpp_host=localhost +xmpp_port=5347 +xmpp_jid=api.localhost +xmpp_password=secret \ No newline at end of file diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java index 83afb62e..7b0264c0 100644 --- a/src/test/java/com/juick/tests/ApiTests.java +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -4,6 +4,7 @@ import com.juick.Message; import com.juick.Tag; import com.juick.User; import com.juick.server.MessagesQueries; +import com.juick.server.SubscriptionsQueries; import com.juick.server.TagQueries; import com.juick.server.UserQueries; import junit.framework.Assert; @@ -28,6 +29,7 @@ public class ApiTests { dataSource.setDriverClassName("org.h2.Driver"); dataSource.setUrl("jdbc:h2:~/test"); jdbc = new JdbcTemplate(dataSource); + jdbc.execute("DROP ALL OBJECTS DELETE FILES"); jdbc.execute("CREATE TABLE bl_users (user_id int(10) unsigned NOT NULL, " + "bl_user_id int(10) unsigned NOT NULL, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP )"); jdbc.execute("CREATE TABLE messages (" + @@ -64,6 +66,9 @@ public class ApiTests { "jid char(64) DEFAULT NULL," + "active tinyint(1) NOT NULL DEFAULT 1," + "ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)"); + jdbc.execute("CREATE TABLE subscr_messages (" + + "message_id int(10) unsigned NOT NULL," + + "suser_id int(10) unsigned NOT NULL)"); jdbc.execute("CREATE TABLE messages_txt (" + "message_id int(10) unsigned NOT NULL," + "tags varchar(255)," + @@ -85,10 +90,6 @@ public class ApiTests { "attach nchar(3) check (attach in ('jpg', 'mp4', 'png'))," + "txt text)"); } - @After - public void tearDown() { - jdbc.execute("DROP ALL OBJECTS DELETE FILES"); - } @Test @@ -121,6 +122,8 @@ public class ApiTests { org.junit.Assert.assertEquals("weather", msg3.Tags.get(0)); org.junit.Assert.assertEquals(ugnich.getUID(), UserQueries.checkPassword(jdbc, ugnich.getUName(), "x")); org.junit.Assert.assertEquals(-1, UserQueries.checkPassword(jdbc, ugnich.getUName(), "xy")); + SubscriptionsQueries.subscribeMessage(jdbc, msg.getMID(), ugnich.getUID()); + Assert.assertEquals(1, SubscriptionsQueries.getUsersSubscribedToComments(jdbc, msg.getMID(), user.getUID()).size()); } } -- cgit v1.2.3 From ca45d2216ccef8231860aa349a5e745ab17dc43c Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sun, 17 Jan 2016 01:08:24 +0300 Subject: POST --- build.gradle | 2 +- deps/com.juick.server | 2 +- src/main/java/com/juick/api/Main.java | 233 +++++++++++++++++++++++++++++++++ src/main/java/com/juick/api/Utils.java | 87 ++++++++++++ 4 files changed, 322 insertions(+), 2 deletions(-) (limited to 'deps') diff --git a/build.gradle b/build.gradle index b76df16a..e82e7e96 100644 --- a/build.gradle +++ b/build.gradle @@ -62,7 +62,7 @@ dependencies { "org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}" testCompile 'junit:junit:4.12' runtime 'mysql:mysql-connector-java:5.1.37' - testRuntime 'com.h2database:h2:1.4.190' + testTuntime 'com.h2database:h2:1.4.190' } compileJava.options.encoding = 'UTF-8' diff --git a/deps/com.juick.server b/deps/com.juick.server index 9232bdcb..27e4beeb 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 9232bdcb144bc3b94f4b825b3a4cb588078bd72d +Subproject commit 27e4beeb2ed195985942262f3f94a8c5b069ba66 diff --git a/src/main/java/com/juick/api/Main.java b/src/main/java/com/juick/api/Main.java index cc068ccd..c43804d7 100644 --- a/src/main/java/com/juick/api/Main.java +++ b/src/main/java/com/juick/api/Main.java @@ -17,9 +17,16 @@ */ package com.juick.api; +import com.juick.Tag; +import com.juick.json.MessageSerializer; +import com.juick.server.*; import com.juick.xmpp.JID; +import com.juick.xmpp.Message; import com.juick.xmpp.Stream; import com.juick.xmpp.StreamComponent; +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; @@ -32,6 +39,11 @@ import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; +import java.net.URL; +import java.net.URLEncoder; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -187,6 +199,12 @@ public class Main extends HttpServlet implements Stream.StreamListener { String uri = request.getRequestURI(); switch (uri) { case "/post": + int mid = Utils.parseInt(request.getParameter("mid"), 0); + if (mid == 0) { + doPostMessage(jdbc, request, response, xmpp, vuid); + } else { + doPostComment(jdbc, request, response, xmpp, vuid); + } break; case "/pm": pm.doPostPM(request, response, xmpp, vuid); @@ -197,6 +215,221 @@ public class Main extends HttpServlet implements Stream.StreamListener { } } + public void doPostMessage(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid) + throws ServletException, IOException { + String body = request.getParameter("body"); + if (body == null || body.length() < 1 || body.length() > 4096) { + response.sendError(400); + return; + } + body = body.replace("\r", ""); + + String tagsStr = request.getParameter("tags"); + List tags = new ArrayList<>(); + String tagsArr[] = new String[1]; + if (tagsStr != null && !tagsStr.isEmpty()) { + tagsArr = tagsStr.split("[ \\,]"); + for (int i = 0; i < tagsArr.length; i++) { + if (tagsArr[i].startsWith("*")) { + tagsArr[i] = tagsArr[i].substring(1); + } + if (tagsArr[i].length() > 64) { + tagsArr[i] = tagsArr[i].substring(0, 64); + } + } + tags = TagQueries.getTags(sql, tagsArr, true); + while (tags.size() > 5) { + tags.remove(5); + } + } + + String attachmentFName = null; + try { + attachmentFName = Utils.receiveMultiPartFile(request, "attach"); + } catch (Exception e) { + System.out.println("MULTIPART ERROR: " + e.toString()); + response.sendError(400); + return; + } + + String paramImg = request.getParameter("img"); + if (attachmentFName == null && paramImg != null && paramImg.length() > 10 ) { + try { + URL imgUrl = new URL(paramImg); + attachmentFName = Utils.downloadImage(imgUrl); + } catch (Exception e) { + System.out.println("DOWNLOAD ERROR: " + e.toString()); + response.sendError(500); + return; + } + } + + String attachmentType = attachmentFName != null ? attachmentFName.substring(attachmentFName.length() - 3) : null; + int mid = MessagesQueries.createMessage(sql, vuid, body, attachmentType, tags); + SubscriptionsQueries.subscribeMessage(sql, mid, vuid); + JuickMessage jmsg = new JuickMessage(MessagesQueries.getMessage(sql, mid)); + if (xmpp != null) { + Message xmsg = new Message(); + xmsg.from = new JID("juick", "juick.com", null); + xmsg.type = Message.Type.chat; + xmsg.thread = "juick-" + mid; + + xmsg.addChild(jmsg); + + Nickname nick = new Nickname(); + nick.Nickname = "@" + jmsg.getUser().getUName(); + xmsg.addChild(nick); + + if (attachmentFName != null) { + String fname = mid + "." + attachmentType; + String attachmentURL = "http://i.juick.com/photos-1024/" + fname; + + Runtime.getRuntime().exec("/var/www/juick.com/cgi/p-convert.sh /var/www/juick.com/i/tmp/" + attachmentFName + " " + fname); + + body = attachmentURL + "\n" + body; + XOOB xoob = new XOOB(); + xoob.URL = attachmentURL; + xmsg.addChild(xoob); + } + + String tagsStr2 = ""; + for (String tag : tagsArr) { + tagsStr2 += " *" + tag; + } + xmsg.body = "@" + jmsg.getUser().getUName() + ":" + tagsStr2 + "\n" + body + "\n\n#" + mid + " http://juick.com/" + mid; + + xmsg.to = new JID("juick", "s2s.juick.com", null); + xmpp.send(xmsg); + + xmsg.to.Host = "ws.juick.com"; + xmpp.send(xmsg); + + xmsg.to.Host = "push.juick.com"; + xmpp.send(xmsg); + + xmsg.to.Host = "crosspost.juick.com"; + xmsg.to.Username = "twitter"; + xmpp.send(xmsg); + xmsg.to.Username = "fb"; + xmpp.send(xmsg); + + xmsg.to.Host = "nologin.ru"; + xmsg.to.Username = "jubo"; + xmpp.send(xmsg); + } else { + log("XMPP unavailable"); + } + MessageSerializer serializer = new MessageSerializer(); + Main.replyJSON(request, response, serializer.serialize(jmsg).toString()); + } + + public void doPostComment(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response, Stream xmpp, int vuid) + throws ServletException, IOException { + int mid = Utils.parseInt(request.getParameter("mid"), 0); + if (mid == 0) { + response.sendError(400); + return; + } + com.juick.Message msg = MessagesQueries.getMessage(sql, mid); + if (msg == null) { + response.sendError(404); + return; + } + + int rid = Utils.parseInt(request.getParameter("rid"), 0); + com.juick.Message reply = null; + if (rid > 0) { + reply = MessagesQueries.getReply(sql, mid, rid); + if (reply == null) { + response.sendError(404); + return; + } + } + + String body = request.getParameter("body"); + if (body == null || body.length() < 1 || body.length() > 4096) { + response.sendError(400); + return; + } + body = body.replace("\r", ""); + + if ((msg.ReadOnly && msg.getUser().getUID() != vuid) || UserQueries.isInBLAny(sql, msg.getUser().getUID(), vuid) + || (reply != null && UserQueries.isInBLAny(sql, reply.getUser().getUID(), vuid))) { + response.sendError(403); + return; + } + + String attachmentFName = null; + try { + attachmentFName = Utils.receiveMultiPartFile(request, "attach"); + } catch (Exception e) { + System.out.println("MULTIPART ERROR: " + e.toString()); + response.sendError(400); + return; + } + + String paramImg = request.getParameter("img"); + if (attachmentFName == null && paramImg != null && paramImg.length() > 10) { + try { + attachmentFName = Utils.downloadImage(new URL(paramImg)); + } catch (Exception e) { + System.out.println("DOWNLOAD ERROR: " + e.toString()); + response.sendError(500); + return; + } + } + + String attachmentType = attachmentFName != null ? attachmentFName.substring(attachmentFName.length() - 3) : null; + int ridnew = MessagesQueries.createReply(sql, mid, rid, vuid, body, attachmentType); + SubscriptionsQueries.subscribeMessage(sql, mid, vuid); + + JuickMessage jmsg = new JuickMessage(MessagesQueries.getReply(sql, mid, ridnew)); + + if (xmpp != null) { + Message xmsg = new Message(); + xmsg.from = new JID("juick", "juick.com", null); + xmsg.type = Message.Type.chat; + xmsg.thread = "juick-" + mid; + xmsg.addChild(jmsg); + + String quote = reply != null ? reply.getText() : msg.getText(); + if (quote.length() >= 50) { + quote = quote.substring(0, 47) + "..."; + } + + Nickname nick = new Nickname(); + nick.Nickname = "@" + jmsg.getUser().getUName(); + xmsg.addChild(nick); + + if (attachmentFName != null) { + String fname = mid + "-" + ridnew + "." + attachmentType; + String attachmentURL = "http://i.juick.com/photos-1024/" + fname; + + Runtime.getRuntime().exec("/var/www/juick.com/cgi/p-convert.sh /var/www/juick.com/i/tmp/" + attachmentFName + " " + fname); + + body = attachmentURL + "\n" + body; + XOOB xoob = new XOOB(); + xoob.URL = attachmentURL; + xmsg.addChild(xoob); + } + + xmsg.body = "Reply by @" + jmsg.getUser().getUName() + ":\n>" + quote + "\n" + body + "\n\n#" + mid + "/" + ridnew + " http://juick.com/" + mid + "#" + ridnew; + + xmsg.to = new JID("juick", "s2s.juick.com", null); + xmpp.send(xmsg); + + xmsg.to.Host = "ws.juick.com"; + xmpp.send(xmsg); + + xmsg.to.Host = "push.juick.com"; + xmpp.send(xmsg); + } else { + log("XMPP unavailable"); + } + MessageSerializer serializer = new MessageSerializer(); + Main.replyJSON(request, response, serializer.serialize(jmsg).toString()); + } + public static void replyJSON(HttpServletRequest request, HttpServletResponse response, String json) throws IOException { response.setContentType("application/json; charset=UTF-8"); response.setHeader("Access-Control-Allow-Origin", "*"); diff --git a/src/main/java/com/juick/api/Utils.java b/src/main/java/com/juick/api/Utils.java index 6383fec0..7a498a10 100644 --- a/src/main/java/com/juick/api/Utils.java +++ b/src/main/java/com/juick/api/Utils.java @@ -18,17 +18,25 @@ package com.juick.api; import com.juick.server.UserQueries; + +import java.io.FileOutputStream; import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; +import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.Part; + import org.springframework.jdbc.core.JdbcTemplate; import sun.misc.BASE64Decoder; @@ -152,4 +160,83 @@ public class Utils { } return ret; } + public static String getPartFilename(Part part) { + for (String cd : part.getHeader("content-disposition").split(";")) { + if (cd.trim().startsWith("filename")) { + String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", ""); + return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix. + } + } + return null; + } + public static String receiveMultiPartFile(HttpServletRequest request, String name) throws Exception { + String attachmentFName = null; + + Part filePart = request.getPart("attach"); + if (filePart != null) { + String partname = Utils.getPartFilename(filePart); + if (partname != null && partname.length() > 0) { + String attachmentType = partname.substring(partname.length() - 3).toLowerCase(); + if (attachmentType.equals("jpg") || attachmentType.equals("peg") || attachmentType.equals("png")) { + if (attachmentType.equals("peg")) { + attachmentType = "jpg"; + } + attachmentFName = UUID.randomUUID().toString() + "." + attachmentType; + filePart.write("/var/www/juick.com/i/tmp/" + attachmentFName); + } else { + throw new Exception("Wrong file type"); + } + } + } + + return attachmentFName; + } + public static String downloadImage(URL url) throws Exception { + String attachmentFName = null; + Exception ex = null; + + InputStream is = null; + FileOutputStream fos = null; + try { + URLConnection urlConn = url.openConnection(); + is = urlConn.getInputStream(); + String mime = urlConn.getContentType(); + + String attachmentType; + if (mime != null && mime.equals("image/jpeg")) { + attachmentType = "jpg"; + } else if (mime != null && mime.equals("image/png")) { + attachmentType = "png"; + } else { + throw new Exception("Wrong file type"); + } + + attachmentFName = UUID.randomUUID().toString() + "." + attachmentType; + fos = new FileOutputStream("/var/www/juick.com/i/tmp/" + attachmentFName); + byte[] buffer = new byte[10240]; + int len; + while ((len = is.read(buffer)) > 0) { + fos.write(buffer, 0, len); + } + } catch (Exception e) { + ex = e; + attachmentFName = null; + } finally { + try { + if (is != null) { + is.close(); + } + } finally { + if (fos != null) { + fos.close(); + } + } + } + + if (ex != null) { + throw ex; + } else { + return attachmentFName; + } + } } -- cgit v1.2.3 From 911f4c11cea887645e0da6549ed3e7586006badf Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Sun, 17 Jan 2016 01:37:16 +0300 Subject: fixes --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index 27e4beeb..8ae5d9e3 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 27e4beeb2ed195985942262f3f94a8c5b069ba66 +Subproject commit 8ae5d9e3ce643bf0b8488c4566eff133b2cb2f11 -- cgit v1.2.3 From 01e9c27dcebf8a64100af8f6649f3060eb8769e9 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Tue, 26 Jan 2016 02:14:56 +0300 Subject: update deps --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index 8ae5d9e3..e292163f 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 8ae5d9e3ce643bf0b8488c4566eff133b2cb2f11 +Subproject commit e292163fd4c343764889f1d6161720a2d57dfc84 -- cgit v1.2.3 From 128a8d9834d0897855bb6115e933c785563bd2ac Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 11 May 2016 03:41:10 +0300 Subject: update deps --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index e292163f..69a435df 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit e292163fd4c343764889f1d6161720a2d57dfc84 +Subproject commit 69a435dfef1bc656dc1d9d3da0f049f86d18fdaf -- cgit v1.2.3 From cb6953b7674114b976cf9ee25061b34657032af0 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 11 May 2016 15:35:26 +0300 Subject: update deps --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index 69a435df..0a9cd317 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 69a435dfef1bc656dc1d9d3da0f049f86d18fdaf +Subproject commit 0a9cd317b878d6c2c777ec4eb19173a7d651abe5 -- cgit v1.2.3 From 8dec265d21dd4285adc8ace9b565b6c9e9a4bc75 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 12 May 2016 09:55:27 +0300 Subject: update deps --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index 0a9cd317..c95b63af 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 0a9cd317b878d6c2c777ec4eb19173a7d651abe5 +Subproject commit c95b63af82ed58c68876563692340d74ced156f2 -- cgit v1.2.3 From c8156fc1361b7467306d731cd57f5a4f2a9b2006 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 13 May 2016 16:13:08 +0300 Subject: telegram login --- deps/com.juick.server | 2 +- src/main/java/com/juick/api/TelegramBotHook.java | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index c95b63af..ea43e78c 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit c95b63af82ed58c68876563692340d74ced156f2 +Subproject commit ea43e78cb8dc20c2f54a15e37dba638b963f65ec diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index cf0979cd..9b75a4ae 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -1,6 +1,7 @@ package com.juick.api; import com.juick.json.MessageSerializer; +import com.juick.server.UserQueries; import com.neovisionaries.ws.client.*; import com.pengrad.telegrambot.BotUtils; import com.pengrad.telegrambot.Callback; @@ -19,6 +20,7 @@ import java.io.BufferedReader; import java.io.IOException; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; @@ -106,7 +108,16 @@ public class TelegramBotHook { if (!chats.contains(message.chat().id())) { addChat(message.chat().id()); logger.info("added chat with " + message.from().firstName()); - bot.execute(new SendMessage(message.chat().id(), "Subscribed!"), new Callback() { + createTelegramUser(message.from().id(), message.from().username()); + bot.execute(new SendMessage(message.chat().id(), + "You are subscribed to all Juick messages. " + + "Create or link an existing Juick account to control " + + "what do you want to receive").replyMarkup( + new InlineKeyboardMarkup( + new InlineKeyboardButton[]{ + new InlineKeyboardButton("LOGIN").url("http://juick.com/signup?type=d&hash=" + + UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue())) + })), new Callback() { @Override public void onResponse(SendMessage request, SendResponse response) { logger.info("got response: " + response.message().toString()); @@ -120,4 +131,8 @@ public class TelegramBotHook { } } } + private boolean createTelegramUser(long tgID, String tgName) { + return jdbc.update("INSERT INTO telegram(tg_ig, tg_name, loginhash) VALUES(?,?,?)", + tgID, tgName, UUID.randomUUID().toString()) > 0; + } } -- cgit v1.2.3 From cc0a29650d3ba9b848a86cce73fbe6e3ff5d8693 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 19 May 2016 19:46:31 +0300 Subject: telegram: notify subcribed users --- deps/com.juick.server | 2 +- src/main/java/com/juick/api/TelegramBotHook.java | 57 ++++++++++++++++-------- 2 files changed, 40 insertions(+), 19 deletions(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index ea43e78c..3fe5180f 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit ea43e78cb8dc20c2f54a15e37dba638b963f65ec +Subproject commit 3fe5180ff7f2488966d3c940629ddefcfc84467f diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index c68d829a..907898f2 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -1,5 +1,6 @@ package com.juick.api; +import com.juick.User; import com.juick.json.MessageSerializer; import com.juick.server.UserQueries; import com.neovisionaries.ws.client.*; @@ -13,6 +14,7 @@ import com.pengrad.telegrambot.model.request.InlineKeyboardMarkup; import com.pengrad.telegrambot.request.SendMessage; import com.pengrad.telegrambot.response.SendResponse; import org.json.JSONObject; +import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import javax.servlet.http.HttpServletRequest; @@ -20,6 +22,7 @@ import java.io.BufferedReader; import java.io.IOException; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; @@ -66,25 +69,12 @@ public class TelegramBotHook { sb.append(jmsg.getAttachmentURL()); } String msg = sb.toString(); + List users = getSubscribers(jmsg.getUser().getUID()); List chats = getChats(); - chats.stream().forEach(c -> { - bot.execute(new SendMessage(c, msg).replyMarkup( - new InlineKeyboardMarkup( - new InlineKeyboardButton[] { - new InlineKeyboardButton("See on Juick").url("https://juick.com/" + jmsg.getMID()) - } - )), new Callback() { - @Override - public void onResponse(SendMessage request, SendResponse response) { - logger.info("got response: " + response.message().toString()); - } - - @Override - public void onFailure(SendMessage request, IOException e) { - logger.log(Level.WARNING, "telegram failure", e); - } - }); - }); + // registered subscribed users + users.stream().forEach(c -> telegramNotify(c, msg, jmsg.getMID())); + // anonymous + chats.stream().filter(u -> !getUser(u).isPresent()).forEach(c -> telegramNotify(c, msg, jmsg.getMID())); } }); ws.connect(); @@ -93,6 +83,25 @@ public class TelegramBotHook { } } + private void telegramNotify(Long c, String msg, int mid) { + bot.execute(new SendMessage(c, msg).replyMarkup( + new InlineKeyboardMarkup( + new InlineKeyboardButton[] { + new InlineKeyboardButton("See on Juick").url("https://juick.com/" + mid) + } + )), new Callback() { + @Override + public void onResponse(SendMessage request, SendResponse response) { + logger.info("got response: " + response.message().toString()); + } + + @Override + public void onFailure(SendMessage request, IOException e) { + logger.log(Level.WARNING, "telegram failure", e); + } + }); + } + List getChats() { return jdbc.queryForList("SELECT chat_id FROM telegram_chats", Long.class); } @@ -135,4 +144,16 @@ public class TelegramBotHook { return jdbc.update("INSERT INTO telegram(tg_id, tg_name, loginhash) VALUES(?,?,?)", tgID, tgName, UUID.randomUUID().toString()) > 0; } + private Optional getUser(long tgId) { + try { + return Optional.of(jdbc.queryForObject("SELECT id, name, banned FROM users INNER JOIN telegram" + + "ON telegram.user_id = users.id WHERE telegram.tg_id=?", new UserQueries.UserMapper(), tgId)); + } catch (EmptyResultDataAccessException e) { + return Optional.empty(); + } + } + private List getSubscribers(int uid) { + return jdbc.queryForList("SELECT tg_id FROM telegram INNER JOIN subscr_users " + + "ON (subscr_users.user_id=? AND telegram.tg_id=subscr_users.suser_id)", Long.class, uid, uid); + } } -- cgit v1.2.3 From 2cef33327a837cba6f7dca2bf3dec3293591cc65 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 19 May 2016 21:14:11 +0300 Subject: fix deps --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index 3fe5180f..a4110979 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 3fe5180ff7f2488966d3c940629ddefcfc84467f +Subproject commit a41109795f6f6a3803d52606df9bd1a0da641f43 -- cgit v1.2.3 From 7fb8cdfb02c24c265a081499c858f3aca1efbb2b Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 19 May 2016 23:24:22 +0300 Subject: update server api and try to fix anonymous chats --- deps/com.juick.server | 2 +- src/main/java/com/juick/api/Messages.java | 2 +- src/main/java/com/juick/api/PM.java | 2 +- src/main/java/com/juick/api/TelegramBotHook.java | 12 ++++++------ src/test/java/com/juick/tests/ApiTests.java | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index a4110979..b633724c 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit a41109795f6f6a3803d52606df9bd1a0da641f43 +Subproject commit b633724c75081eb05b70ceee74636f19576a4483 diff --git a/src/main/java/com/juick/api/Messages.java b/src/main/java/com/juick/api/Messages.java index d86193f1..18c868f4 100644 --- a/src/main/java/com/juick/api/Messages.java +++ b/src/main/java/com/juick/api/Messages.java @@ -165,7 +165,7 @@ public class Messages { msg.from = new JID("juick", "juick.com", null); msg.to = new JID(null, "crosspost.juick.com", null); JuickMessage jmsg = new JuickMessage(m); - jmsg.setUser(UserQueries.getUserByUID(sql, 11574)); + jmsg.setUser(UserQueries.getUserByUID(sql, 11574).get()); msg.childs.add(jmsg); msg.to.Username = "twitter"; diff --git a/src/main/java/com/juick/api/PM.java b/src/main/java/com/juick/api/PM.java index 3ca9eada..c7123d0a 100644 --- a/src/main/java/com/juick/api/PM.java +++ b/src/main/java/com/juick/api/PM.java @@ -77,7 +77,7 @@ public class PM { msg.from = new JID("juick", "juick.com", null); msg.to = new JID(Integer.toString(uid), "push.juick.com", null); JuickMessage jmsg = new JuickMessage(); - jmsg.setUser(UserQueries.getUserByUID(sql, vuid)); + jmsg.setUser(UserQueries.getUserByUID(sql, vuid).get()); jmsg.setText(body); msg.childs.add(jmsg); xmpp.send(msg); diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index 6b1f946c..8bbf0e33 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -76,7 +76,7 @@ public class TelegramBotHook { String msgUrl = "https://juick.com/" + jmsg.getMID(); users.stream().forEach(c -> telegramNotify(c, msg, msgUrl)); // anonymous - chats.stream().filter(u -> !getUser(u).isPresent()).forEach(c -> telegramNotify(c, msg, msgUrl)); + chats.stream().filter(u -> getUser(u) == 0).forEach(c -> telegramNotify(c, msg, msgUrl)); } }); ws.connect(); @@ -146,7 +146,7 @@ public class TelegramBotHook { public void doPost(HttpServletRequest request) throws IOException { try (BufferedReader reader = request.getReader()) { Message message = BotUtils.parseUpdate(reader).message(); - User user_from = getUser(message.chat().id()).orElse(new User()); + User user_from = UserQueries.getUserByUID(jdbc, getUser(message.chat().id())).orElse(new User()); logger.info(String.format("got telegram msg %s from juick user %d", message.toString(), user_from.getUID())); List chats = getChats(); if (!chats.contains(message.chat().id())) { @@ -192,12 +192,12 @@ public class TelegramBotHook { return jdbc.update("INSERT INTO telegram(tg_id, tg_name, loginhash) VALUES(?,?,?)", tgID, tgName, UUID.randomUUID().toString()) > 0; } - private Optional getUser(long tgId) { + private int getUser(long tgId) { try { - return Optional.of(jdbc.queryForObject("SELECT id, nick, banned FROM users INNER JOIN telegram " + - "ON telegram.user_id = users.id WHERE telegram.tg_id=?", new UserQueries.UserMapper(), tgId)); + return jdbc.queryForObject("SELECT id, nick, banned FROM users INNER JOIN telegram " + + "ON telegram.user_id = users.id WHERE telegram.tg_id=?", Integer.class, tgId); } catch (EmptyResultDataAccessException e) { - return Optional.empty(); + return 0; } } private List getSubscribers(int uid) { diff --git a/src/test/java/com/juick/tests/ApiTests.java b/src/test/java/com/juick/tests/ApiTests.java index 5bd90509..2bae183d 100644 --- a/src/test/java/com/juick/tests/ApiTests.java +++ b/src/test/java/com/juick/tests/ApiTests.java @@ -94,7 +94,7 @@ public class ApiTests { @Test public void messageTests() { int user_id = UserQueries.createUser(jdbc, "me", "secret"); - User user = UserQueries.getUserByUID(jdbc, user_id); + User user = UserQueries.getUserByUID(jdbc, user_id).orElse(new User()); Assert.assertEquals("it should be me", "me", user.getUName()); int mid = MessagesQueries.createMessage(jdbc, user_id, "yo", null, new ArrayList<>()); Message msg = MessagesQueries.getMessage(jdbc, mid); @@ -113,7 +113,7 @@ public class ApiTests { Message msg2 = MessagesQueries.getMessage(jdbc, mid2); org.junit.Assert.assertEquals(1, msg2.Tags.size()); int ugnich_id = UserQueries.createUser(jdbc, "ugnich", "x"); - User ugnich = UserQueries.getUserByUID(jdbc, ugnich_id); + User ugnich = UserQueries.getUserByUID(jdbc, ugnich_id).orElse(new User()); int rid = MessagesQueries.createReply(jdbc, msg2.getMID(), 0, ugnich.getUID(), "bla-bla", null); org.junit.Assert.assertEquals(1, rid); Message msg3 = MessagesQueries.getMessage(jdbc, mid2); -- cgit v1.2.3 From 740fa16a06f9aeae839ffda6344c663a258d8e85 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Tue, 24 May 2016 14:44:11 +0300 Subject: fix telegram signup --- deps/com.juick.server | 2 +- src/main/java/com/juick/api/TelegramBotHook.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index b633724c..1ce6bc55 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit b633724c75081eb05b70ceee74636f19576a4483 +Subproject commit 1ce6bc55817129159b1cda5076d039e9c3bc8508 diff --git a/src/main/java/com/juick/api/TelegramBotHook.java b/src/main/java/com/juick/api/TelegramBotHook.java index fa05c2f0..8c23973e 100644 --- a/src/main/java/com/juick/api/TelegramBotHook.java +++ b/src/main/java/com/juick/api/TelegramBotHook.java @@ -153,10 +153,10 @@ public class TelegramBotHook { addChat(message.chat().id()); logger.info("added chat with " + message.from().firstName()); createTelegramUser(message.from().id(), message.from().username()); - telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue())); + telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue(), message.from().username())); } else { if (user_from.getUID() == 0) { - telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue())); + telegramSignupNotify(message.from().id().longValue(), UserQueries.getSignUpHashByTelegramID(jdbc, message.from().id().longValue(), message.from().username())); } else if (message.text().equalsIgnoreCase("/login")) { String msg = String.format("Hi, %s!\nTap to log in", user_from.getUName()); String msgUrl = "http://juick.com/login?" + UserQueries.getHashByUID(jdbc, user_from.getUID()); -- cgit v1.2.3 From 0c8c5c596067766f45c18084820cdb213f17cfc9 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Thu, 30 Jun 2016 15:34:38 +0300 Subject: fix deps --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index 1ce6bc55..79794224 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 1ce6bc55817129159b1cda5076d039e9c3bc8508 +Subproject commit 797942249b0d5e38285e806bc0e73e755e6ffede -- cgit v1.2.3 From a2d11294adca359bb6f7021a9b5db13647b5f504 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Fri, 1 Jul 2016 12:27:53 +0300 Subject: update deps --- deps/com.juick.server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'deps') diff --git a/deps/com.juick.server b/deps/com.juick.server index 79794224..53a4aaac 160000 --- a/deps/com.juick.server +++ b/deps/com.juick.server @@ -1 +1 @@ -Subproject commit 797942249b0d5e38285e806bc0e73e755e6ffede +Subproject commit 53a4aaacf585e70aadd3b1133319a5bb1e08f0c4 -- cgit v1.2.3